babylon.2.0-alpha.debug.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815
  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.RotationXToRef = function (angle, result) {
  1389. var s = Math.sin(angle);
  1390. var c = Math.cos(angle);
  1391. result.m[0] = 1.0;
  1392. result.m[15] = 1.0;
  1393. result.m[5] = c;
  1394. result.m[10] = c;
  1395. result.m[9] = -s;
  1396. result.m[6] = s;
  1397. result.m[1] = 0;
  1398. result.m[2] = 0;
  1399. result.m[3] = 0;
  1400. result.m[4] = 0;
  1401. result.m[7] = 0;
  1402. result.m[8] = 0;
  1403. result.m[11] = 0;
  1404. result.m[12] = 0;
  1405. result.m[13] = 0;
  1406. result.m[14] = 0;
  1407. };
  1408. Matrix.RotationY = function (angle) {
  1409. var result = new Matrix();
  1410. Matrix.RotationYToRef(angle, result);
  1411. return result;
  1412. };
  1413. Matrix.RotationYToRef = function (angle, result) {
  1414. var s = Math.sin(angle);
  1415. var c = Math.cos(angle);
  1416. result.m[5] = 1.0;
  1417. result.m[15] = 1.0;
  1418. result.m[0] = c;
  1419. result.m[2] = -s;
  1420. result.m[8] = s;
  1421. result.m[10] = c;
  1422. result.m[1] = 0;
  1423. result.m[3] = 0;
  1424. result.m[4] = 0;
  1425. result.m[6] = 0;
  1426. result.m[7] = 0;
  1427. result.m[9] = 0;
  1428. result.m[11] = 0;
  1429. result.m[12] = 0;
  1430. result.m[13] = 0;
  1431. result.m[14] = 0;
  1432. };
  1433. Matrix.RotationZ = function (angle) {
  1434. var result = new Matrix();
  1435. Matrix.RotationZToRef(angle, result);
  1436. return result;
  1437. };
  1438. Matrix.RotationZToRef = function (angle, result) {
  1439. var s = Math.sin(angle);
  1440. var c = Math.cos(angle);
  1441. result.m[10] = 1.0;
  1442. result.m[15] = 1.0;
  1443. result.m[0] = c;
  1444. result.m[1] = s;
  1445. result.m[4] = -s;
  1446. result.m[5] = c;
  1447. result.m[2] = 0;
  1448. result.m[3] = 0;
  1449. result.m[6] = 0;
  1450. result.m[7] = 0;
  1451. result.m[8] = 0;
  1452. result.m[9] = 0;
  1453. result.m[11] = 0;
  1454. result.m[12] = 0;
  1455. result.m[13] = 0;
  1456. result.m[14] = 0;
  1457. };
  1458. Matrix.RotationAxis = function (axis, angle) {
  1459. var s = Math.sin(-angle);
  1460. var c = Math.cos(-angle);
  1461. var c1 = 1 - c;
  1462. axis.normalize();
  1463. var result = Matrix.Zero();
  1464. result.m[0] = (axis.x * axis.x) * c1 + c;
  1465. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1466. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1467. result.m[3] = 0.0;
  1468. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1469. result.m[5] = (axis.y * axis.y) * c1 + c;
  1470. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1471. result.m[7] = 0.0;
  1472. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1473. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1474. result.m[10] = (axis.z * axis.z) * c1 + c;
  1475. result.m[11] = 0.0;
  1476. result.m[15] = 1.0;
  1477. return result;
  1478. };
  1479. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1480. var result = new Matrix();
  1481. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1482. return result;
  1483. };
  1484. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1485. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1486. this._tempQuaternion.toRotationMatrix(result);
  1487. };
  1488. Matrix.Scaling = function (x, y, z) {
  1489. var result = Matrix.Zero();
  1490. Matrix.ScalingToRef(x, y, z, result);
  1491. return result;
  1492. };
  1493. Matrix.ScalingToRef = function (x, y, z, result) {
  1494. result.m[0] = x;
  1495. result.m[1] = 0;
  1496. result.m[2] = 0;
  1497. result.m[3] = 0;
  1498. result.m[4] = 0;
  1499. result.m[5] = y;
  1500. result.m[6] = 0;
  1501. result.m[7] = 0;
  1502. result.m[8] = 0;
  1503. result.m[9] = 0;
  1504. result.m[10] = z;
  1505. result.m[11] = 0;
  1506. result.m[12] = 0;
  1507. result.m[13] = 0;
  1508. result.m[14] = 0;
  1509. result.m[15] = 1.0;
  1510. };
  1511. Matrix.Translation = function (x, y, z) {
  1512. var result = Matrix.Identity();
  1513. Matrix.TranslationToRef(x, y, z, result);
  1514. return result;
  1515. };
  1516. Matrix.TranslationToRef = function (x, y, z, result) {
  1517. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1518. };
  1519. Matrix.LookAtLH = function (eye, target, up) {
  1520. var result = Matrix.Zero();
  1521. Matrix.LookAtLHToRef(eye, target, up, result);
  1522. return result;
  1523. };
  1524. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1525. target.subtractToRef(eye, this._zAxis);
  1526. this._zAxis.normalize();
  1527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1528. this._xAxis.normalize();
  1529. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1530. this._yAxis.normalize();
  1531. var ex = -Vector3.Dot(this._xAxis, eye);
  1532. var ey = -Vector3.Dot(this._yAxis, eye);
  1533. var ez = -Vector3.Dot(this._zAxis, eye);
  1534. 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);
  1535. };
  1536. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1537. var hw = 2.0 / width;
  1538. var hh = 2.0 / height;
  1539. var id = 1.0 / (zfar - znear);
  1540. var nid = znear / (znear - zfar);
  1541. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1542. };
  1543. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1544. var matrix = Matrix.Zero();
  1545. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1546. return matrix;
  1547. };
  1548. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1549. result.m[0] = 2.0 / (right - left);
  1550. result.m[1] = result.m[2] = result.m[3] = 0;
  1551. result.m[5] = 2.0 / (top - bottom);
  1552. result.m[4] = result.m[6] = result.m[7] = 0;
  1553. result.m[10] = -1.0 / (znear - zfar);
  1554. result.m[8] = result.m[9] = result.m[11] = 0;
  1555. result.m[12] = (left + right) / (left - right);
  1556. result.m[13] = (top + bottom) / (bottom - top);
  1557. result.m[14] = znear / (znear - zfar);
  1558. result.m[15] = 1.0;
  1559. };
  1560. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1561. var matrix = Matrix.Zero();
  1562. matrix.m[0] = (2.0 * znear) / width;
  1563. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1564. matrix.m[5] = (2.0 * znear) / height;
  1565. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1566. matrix.m[10] = -zfar / (znear - zfar);
  1567. matrix.m[8] = matrix.m[9] = 0.0;
  1568. matrix.m[11] = 1.0;
  1569. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1570. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1571. return matrix;
  1572. };
  1573. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1574. var matrix = Matrix.Zero();
  1575. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1576. return matrix;
  1577. };
  1578. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1579. var tan = 1.0 / (Math.tan(fov * 0.5));
  1580. result.m[0] = tan / aspect;
  1581. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1582. result.m[5] = tan;
  1583. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1584. result.m[8] = result.m[9] = 0.0;
  1585. result.m[10] = -zfar / (znear - zfar);
  1586. result.m[11] = 1.0;
  1587. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1588. result.m[14] = (znear * zfar) / (znear - zfar);
  1589. };
  1590. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1591. var cw = viewport.width;
  1592. var ch = viewport.height;
  1593. var cx = viewport.x;
  1594. var cy = viewport.y;
  1595. 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);
  1596. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1597. };
  1598. Matrix.Transpose = function (matrix) {
  1599. var result = new Matrix();
  1600. result.m[0] = matrix.m[0];
  1601. result.m[1] = matrix.m[4];
  1602. result.m[2] = matrix.m[8];
  1603. result.m[3] = matrix.m[12];
  1604. result.m[4] = matrix.m[1];
  1605. result.m[5] = matrix.m[5];
  1606. result.m[6] = matrix.m[9];
  1607. result.m[7] = matrix.m[13];
  1608. result.m[8] = matrix.m[2];
  1609. result.m[9] = matrix.m[6];
  1610. result.m[10] = matrix.m[10];
  1611. result.m[11] = matrix.m[14];
  1612. result.m[12] = matrix.m[3];
  1613. result.m[13] = matrix.m[7];
  1614. result.m[14] = matrix.m[11];
  1615. result.m[15] = matrix.m[15];
  1616. return result;
  1617. };
  1618. Matrix.Reflection = function (plane) {
  1619. var matrix = new Matrix();
  1620. Matrix.ReflectionToRef(plane, matrix);
  1621. return matrix;
  1622. };
  1623. Matrix.ReflectionToRef = function (plane, result) {
  1624. plane.normalize();
  1625. var x = plane.normal.x;
  1626. var y = plane.normal.y;
  1627. var z = plane.normal.z;
  1628. var temp = -2 * x;
  1629. var temp2 = -2 * y;
  1630. var temp3 = -2 * z;
  1631. result.m[0] = (temp * x) + 1;
  1632. result.m[1] = temp2 * x;
  1633. result.m[2] = temp3 * x;
  1634. result.m[3] = 0.0;
  1635. result.m[4] = temp * y;
  1636. result.m[5] = (temp2 * y) + 1;
  1637. result.m[6] = temp3 * y;
  1638. result.m[7] = 0.0;
  1639. result.m[8] = temp * z;
  1640. result.m[9] = temp2 * z;
  1641. result.m[10] = (temp3 * z) + 1;
  1642. result.m[11] = 0.0;
  1643. result.m[12] = temp * plane.d;
  1644. result.m[13] = temp2 * plane.d;
  1645. result.m[14] = temp3 * plane.d;
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix._tempQuaternion = new Quaternion();
  1649. Matrix._xAxis = Vector3.Zero();
  1650. Matrix._yAxis = Vector3.Zero();
  1651. Matrix._zAxis = Vector3.Zero();
  1652. return Matrix;
  1653. })();
  1654. BABYLON.Matrix = Matrix;
  1655. var Plane = (function () {
  1656. function Plane(a, b, c, d) {
  1657. this.normal = new Vector3(a, b, c);
  1658. this.d = d;
  1659. }
  1660. Plane.prototype.asArray = function () {
  1661. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1662. };
  1663. Plane.prototype.clone = function () {
  1664. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1665. };
  1666. Plane.prototype.normalize = function () {
  1667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1668. var magnitude = 0;
  1669. if (norm != 0) {
  1670. magnitude = 1.0 / norm;
  1671. }
  1672. this.normal.x *= magnitude;
  1673. this.normal.y *= magnitude;
  1674. this.normal.z *= magnitude;
  1675. this.d *= magnitude;
  1676. };
  1677. Plane.prototype.transform = function (transformation) {
  1678. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1679. var x = this.normal.x;
  1680. var y = this.normal.y;
  1681. var z = this.normal.z;
  1682. var d = this.d;
  1683. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1684. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1685. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1686. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1687. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1688. };
  1689. Plane.prototype.dotCoordinate = function (point) {
  1690. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1691. };
  1692. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1693. var x1 = point2.x - point1.x;
  1694. var y1 = point2.y - point1.y;
  1695. var z1 = point2.z - point1.z;
  1696. var x2 = point3.x - point1.x;
  1697. var y2 = point3.y - point1.y;
  1698. var z2 = point3.z - point1.z;
  1699. var yz = (y1 * z2) - (z1 * y2);
  1700. var xz = (z1 * x2) - (x1 * z2);
  1701. var xy = (x1 * y2) - (y1 * x2);
  1702. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1703. var invPyth;
  1704. if (pyth != 0) {
  1705. invPyth = 1.0 / pyth;
  1706. } else {
  1707. invPyth = 0;
  1708. }
  1709. this.normal.x = yz * invPyth;
  1710. this.normal.y = xz * invPyth;
  1711. this.normal.z = xy * invPyth;
  1712. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1713. };
  1714. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1715. var dot = Vector3.Dot(this.normal, direction);
  1716. return (dot <= epsilon);
  1717. };
  1718. Plane.prototype.signedDistanceTo = function (point) {
  1719. return Vector3.Dot(point, this.normal) + this.d;
  1720. };
  1721. Plane.FromArray = function (array) {
  1722. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1723. };
  1724. Plane.FromPoints = function (point1, point2, point3) {
  1725. var result = new BABYLON.Plane(0, 0, 0, 0);
  1726. result.copyFromPoints(point1, point2, point3);
  1727. return result;
  1728. };
  1729. Plane.FromPositionAndNormal = function (origin, normal) {
  1730. var result = new BABYLON.Plane(0, 0, 0, 0);
  1731. normal.normalize();
  1732. result.normal = normal;
  1733. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1734. return result;
  1735. };
  1736. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1737. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1738. return Vector3.Dot(point, normal) + d;
  1739. };
  1740. return Plane;
  1741. })();
  1742. BABYLON.Plane = Plane;
  1743. var Viewport = (function () {
  1744. function Viewport(x, y, width, height) {
  1745. this.x = x;
  1746. this.y = y;
  1747. this.width = width;
  1748. this.height = height;
  1749. }
  1750. Viewport.prototype.toGlobal = function (engine) {
  1751. var width = engine.getRenderWidth();
  1752. var height = engine.getRenderHeight();
  1753. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1754. };
  1755. return Viewport;
  1756. })();
  1757. BABYLON.Viewport = Viewport;
  1758. var Frustum = (function () {
  1759. function Frustum() {
  1760. }
  1761. Frustum.GetPlanes = function (transform) {
  1762. var frustumPlanes = [];
  1763. for (var index = 0; index < 6; index++) {
  1764. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1765. }
  1766. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1767. return frustumPlanes;
  1768. };
  1769. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1770. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1771. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1772. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1773. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1774. frustumPlanes[0].normalize();
  1775. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1776. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1777. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1778. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1779. frustumPlanes[1].normalize();
  1780. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1781. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1782. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1783. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1784. frustumPlanes[2].normalize();
  1785. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1786. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1787. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1788. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1789. frustumPlanes[3].normalize();
  1790. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1791. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1792. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1793. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1794. frustumPlanes[4].normalize();
  1795. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1796. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1797. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1798. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1799. frustumPlanes[5].normalize();
  1800. };
  1801. return Frustum;
  1802. })();
  1803. BABYLON.Frustum = Frustum;
  1804. var Ray = (function () {
  1805. function Ray(origin, direction) {
  1806. this.origin = origin;
  1807. this.direction = direction;
  1808. }
  1809. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1810. var d = 0.0;
  1811. var maxValue = Number.MAX_VALUE;
  1812. if (Math.abs(this.direction.x) < 0.0000001) {
  1813. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1814. return false;
  1815. }
  1816. } else {
  1817. var inv = 1.0 / this.direction.x;
  1818. var min = (minimum.x - this.origin.x) * inv;
  1819. var max = (maximum.x - this.origin.x) * inv;
  1820. if (min > max) {
  1821. var temp = min;
  1822. min = max;
  1823. max = temp;
  1824. }
  1825. d = Math.max(min, d);
  1826. maxValue = Math.min(max, maxValue);
  1827. if (d > maxValue) {
  1828. return false;
  1829. }
  1830. }
  1831. if (Math.abs(this.direction.y) < 0.0000001) {
  1832. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1833. return false;
  1834. }
  1835. } else {
  1836. inv = 1.0 / this.direction.y;
  1837. min = (minimum.y - this.origin.y) * inv;
  1838. max = (maximum.y - this.origin.y) * inv;
  1839. if (min > max) {
  1840. temp = min;
  1841. min = max;
  1842. max = temp;
  1843. }
  1844. d = Math.max(min, d);
  1845. maxValue = Math.min(max, maxValue);
  1846. if (d > maxValue) {
  1847. return false;
  1848. }
  1849. }
  1850. if (Math.abs(this.direction.z) < 0.0000001) {
  1851. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1852. return false;
  1853. }
  1854. } else {
  1855. inv = 1.0 / this.direction.z;
  1856. min = (minimum.z - this.origin.z) * inv;
  1857. max = (maximum.z - this.origin.z) * inv;
  1858. if (min > max) {
  1859. temp = min;
  1860. min = max;
  1861. max = temp;
  1862. }
  1863. d = Math.max(min, d);
  1864. maxValue = Math.min(max, maxValue);
  1865. if (d > maxValue) {
  1866. return false;
  1867. }
  1868. }
  1869. return true;
  1870. };
  1871. Ray.prototype.intersectsBox = function (box) {
  1872. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1873. };
  1874. Ray.prototype.intersectsSphere = function (sphere) {
  1875. var x = sphere.center.x - this.origin.x;
  1876. var y = sphere.center.y - this.origin.y;
  1877. var z = sphere.center.z - this.origin.z;
  1878. var pyth = (x * x) + (y * y) + (z * z);
  1879. var rr = sphere.radius * sphere.radius;
  1880. if (pyth <= rr) {
  1881. return true;
  1882. }
  1883. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1884. if (dot < 0.0) {
  1885. return false;
  1886. }
  1887. var temp = pyth - (dot * dot);
  1888. return temp <= rr;
  1889. };
  1890. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1891. if (!this._edge1) {
  1892. this._edge1 = BABYLON.Vector3.Zero();
  1893. this._edge2 = BABYLON.Vector3.Zero();
  1894. this._pvec = BABYLON.Vector3.Zero();
  1895. this._tvec = BABYLON.Vector3.Zero();
  1896. this._qvec = BABYLON.Vector3.Zero();
  1897. }
  1898. vertex1.subtractToRef(vertex0, this._edge1);
  1899. vertex2.subtractToRef(vertex0, this._edge2);
  1900. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1901. var det = Vector3.Dot(this._edge1, this._pvec);
  1902. if (det === 0) {
  1903. return null;
  1904. }
  1905. var invdet = 1 / det;
  1906. this.origin.subtractToRef(vertex0, this._tvec);
  1907. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1908. if (bu < 0 || bu > 1.0) {
  1909. return null;
  1910. }
  1911. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1912. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1913. if (bv < 0 || bu + bv > 1.0) {
  1914. return null;
  1915. }
  1916. return new BABYLON.IntersectionInfo(bu, bv, Vector3.Dot(this._edge2, this._qvec) * invdet);
  1917. };
  1918. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1919. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1920. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1921. var direction = end.subtract(start);
  1922. direction.normalize();
  1923. return new Ray(start, direction);
  1924. };
  1925. Ray.Transform = function (ray, matrix) {
  1926. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1927. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1928. return new Ray(newOrigin, newDirection);
  1929. };
  1930. return Ray;
  1931. })();
  1932. BABYLON.Ray = Ray;
  1933. (function (Space) {
  1934. Space[Space["LOCAL"] = 0] = "LOCAL";
  1935. Space[Space["WORLD"] = 1] = "WORLD";
  1936. })(BABYLON.Space || (BABYLON.Space = {}));
  1937. var Space = BABYLON.Space;
  1938. var Axis = (function () {
  1939. function Axis() {
  1940. }
  1941. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1942. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1943. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1944. return Axis;
  1945. })();
  1946. BABYLON.Axis = Axis;
  1947. ;
  1948. })(BABYLON || (BABYLON = {}));
  1949. var BABYLON;
  1950. (function (BABYLON) {
  1951. var screenshotCanvas;
  1952. var fpsRange = 60;
  1953. var previousFramesDuration = [];
  1954. var fps = 60;
  1955. var deltaTime = 0;
  1956. var cloneValue = function (source, destinationObject) {
  1957. if (!source)
  1958. return null;
  1959. if (source instanceof BABYLON.Mesh) {
  1960. return null;
  1961. }
  1962. if (source instanceof BABYLON.SubMesh) {
  1963. return source.clone(destinationObject);
  1964. } else if (source.clone) {
  1965. return source.clone();
  1966. }
  1967. return null;
  1968. };
  1969. var Tools = (function () {
  1970. function Tools() {
  1971. }
  1972. Tools.GetFilename = function (path) {
  1973. var index = path.lastIndexOf("/");
  1974. if (index < 0)
  1975. return path;
  1976. return path.substring(index + 1);
  1977. };
  1978. Tools.GetDOMTextContent = function (element) {
  1979. var result = "";
  1980. var child = element.firstChild;
  1981. while (child) {
  1982. if (child.nodeType == 3) {
  1983. result += child.textContent;
  1984. }
  1985. child = child.nextSibling;
  1986. }
  1987. return result;
  1988. };
  1989. Tools.ToDegrees = function (angle) {
  1990. return angle * 180 / Math.PI;
  1991. };
  1992. Tools.ToRadians = function (angle) {
  1993. return angle * Math.PI / 180;
  1994. };
  1995. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  1996. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1997. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1998. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1999. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2000. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2001. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2002. }
  2003. return {
  2004. minimum: minimum,
  2005. maximum: maximum
  2006. };
  2007. };
  2008. Tools.ExtractMinAndMax = function (positions, start, count) {
  2009. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2010. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2011. for (var index = start; index < start + count; index++) {
  2012. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2013. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2014. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2015. }
  2016. return {
  2017. minimum: minimum,
  2018. maximum: maximum
  2019. };
  2020. };
  2021. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2022. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2023. return undefined;
  2024. return Array.isArray(obj) ? obj : [obj];
  2025. };
  2026. Tools.GetPointerPrefix = function () {
  2027. var eventPrefix = "pointer";
  2028. if (!navigator.pointerEnabled) {
  2029. eventPrefix = "mouse";
  2030. }
  2031. return eventPrefix;
  2032. };
  2033. Tools.QueueNewFrame = function (func) {
  2034. if (window.requestAnimationFrame)
  2035. window.requestAnimationFrame(func);
  2036. else if (window.msRequestAnimationFrame)
  2037. window.msRequestAnimationFrame(func);
  2038. else if (window.webkitRequestAnimationFrame)
  2039. window.webkitRequestAnimationFrame(func);
  2040. else if (window.mozRequestAnimationFrame)
  2041. window.mozRequestAnimationFrame(func);
  2042. else if (window.oRequestAnimationFrame)
  2043. window.oRequestAnimationFrame(func);
  2044. else {
  2045. window.setTimeout(func, 16);
  2046. }
  2047. };
  2048. Tools.RequestFullscreen = function (element) {
  2049. if (element.requestFullscreen)
  2050. element.requestFullscreen();
  2051. else if (element.msRequestFullscreen)
  2052. element.msRequestFullscreen();
  2053. else if (element.webkitRequestFullscreen)
  2054. element.webkitRequestFullscreen();
  2055. else if (element.mozRequestFullScreen)
  2056. element.mozRequestFullScreen();
  2057. };
  2058. Tools.ExitFullscreen = function () {
  2059. if (document.exitFullscreen) {
  2060. document.exitFullscreen();
  2061. } else if (document.mozCancelFullScreen) {
  2062. document.mozCancelFullScreen();
  2063. } else if (document.webkitCancelFullScreen) {
  2064. document.webkitCancelFullScreen();
  2065. } else if (document.msCancelFullScreen) {
  2066. document.msCancelFullScreen();
  2067. }
  2068. };
  2069. Tools.CleanUrl = function (url) {
  2070. url = url.replace(/#/mg, "%23");
  2071. return url;
  2072. };
  2073. Tools.LoadImage = function (url, onload, onerror, database) {
  2074. url = Tools.CleanUrl(url);
  2075. var img = new Image();
  2076. if (url.substr(0, 5) != "data:")
  2077. img.crossOrigin = 'anonymous';
  2078. img.onload = function () {
  2079. onload(img);
  2080. };
  2081. img.onerror = function (err) {
  2082. onerror(img, err);
  2083. };
  2084. var noIndexedDB = function () {
  2085. img.src = url;
  2086. };
  2087. var loadFromIndexedDB = function () {
  2088. database.loadImageFromDB(url, img);
  2089. };
  2090. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2091. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2092. } else {
  2093. if (url.indexOf("file:") === -1) {
  2094. noIndexedDB();
  2095. } else {
  2096. try {
  2097. var textureName = url.substring(5);
  2098. var blobURL;
  2099. try {
  2100. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2101. } catch (ex) {
  2102. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2103. }
  2104. img.src = blobURL;
  2105. } catch (e) {
  2106. Tools.Log("Error while trying to load texture: " + textureName);
  2107. img.src = null;
  2108. }
  2109. }
  2110. }
  2111. return img;
  2112. };
  2113. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2114. url = Tools.CleanUrl(url);
  2115. var noIndexedDB = function () {
  2116. var request = new XMLHttpRequest();
  2117. var loadUrl = Tools.BaseUrl + url;
  2118. request.open('GET', loadUrl, true);
  2119. if (useArrayBuffer) {
  2120. request.responseType = "arraybuffer";
  2121. }
  2122. request.onprogress = progressCallBack;
  2123. request.onreadystatechange = function () {
  2124. if (request.readyState == 4) {
  2125. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2126. callback(!useArrayBuffer ? request.responseText : request.response);
  2127. } else {
  2128. if (onError) {
  2129. onError();
  2130. } else {
  2131. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2132. }
  2133. }
  2134. }
  2135. };
  2136. request.send(null);
  2137. };
  2138. var loadFromIndexedDB = function () {
  2139. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2140. };
  2141. if (url.indexOf("file:") !== -1) {
  2142. var fileName = url.substring(5);
  2143. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2144. } else {
  2145. if (database && database.enableSceneOffline) {
  2146. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2147. } else {
  2148. noIndexedDB();
  2149. }
  2150. }
  2151. };
  2152. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2153. var reader = new FileReader();
  2154. reader.onload = function (e) {
  2155. callback(e.target.result);
  2156. };
  2157. reader.onprogress = progressCallback;
  2158. reader.readAsDataURL(fileToLoad);
  2159. };
  2160. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2161. var reader = new FileReader();
  2162. reader.onload = function (e) {
  2163. callback(e.target.result);
  2164. };
  2165. reader.onprogress = progressCallBack;
  2166. if (!useArrayBuffer) {
  2167. reader.readAsText(fileToLoad);
  2168. } else {
  2169. reader.readAsArrayBuffer(fileToLoad);
  2170. }
  2171. };
  2172. Tools.CheckExtends = function (v, min, max) {
  2173. if (v.x < min.x)
  2174. min.x = v.x;
  2175. if (v.y < min.y)
  2176. min.y = v.y;
  2177. if (v.z < min.z)
  2178. min.z = v.z;
  2179. if (v.x > max.x)
  2180. max.x = v.x;
  2181. if (v.y > max.y)
  2182. max.y = v.y;
  2183. if (v.z > max.z)
  2184. max.z = v.z;
  2185. };
  2186. Tools.WithinEpsilon = function (a, b) {
  2187. var num = a - b;
  2188. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2189. };
  2190. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2191. for (var prop in source) {
  2192. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2193. continue;
  2194. }
  2195. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2196. continue;
  2197. }
  2198. var sourceValue = source[prop];
  2199. var typeOfSourceValue = typeof sourceValue;
  2200. if (typeOfSourceValue == "function") {
  2201. continue;
  2202. }
  2203. if (typeOfSourceValue == "object") {
  2204. if (sourceValue instanceof Array) {
  2205. destination[prop] = [];
  2206. if (sourceValue.length > 0) {
  2207. if (typeof sourceValue[0] == "object") {
  2208. for (var index = 0; index < sourceValue.length; index++) {
  2209. var clonedValue = cloneValue(sourceValue[index], destination);
  2210. if (destination[prop].indexOf(clonedValue) === -1) {
  2211. destination[prop].push(clonedValue);
  2212. }
  2213. }
  2214. } else {
  2215. destination[prop] = sourceValue.slice(0);
  2216. }
  2217. }
  2218. } else {
  2219. destination[prop] = cloneValue(sourceValue, destination);
  2220. }
  2221. } else {
  2222. destination[prop] = sourceValue;
  2223. }
  2224. }
  2225. };
  2226. Tools.IsEmpty = function (obj) {
  2227. for (var i in obj) {
  2228. return false;
  2229. }
  2230. return true;
  2231. };
  2232. Tools.RegisterTopRootEvents = function (events) {
  2233. for (var index = 0; index < events.length; index++) {
  2234. var event = events[index];
  2235. window.addEventListener(event.name, event.handler, false);
  2236. try {
  2237. if (window.parent) {
  2238. window.parent.addEventListener(event.name, event.handler, false);
  2239. }
  2240. } catch (e) {
  2241. }
  2242. }
  2243. };
  2244. Tools.UnregisterTopRootEvents = function (events) {
  2245. for (var index = 0; index < events.length; index++) {
  2246. var event = events[index];
  2247. window.removeEventListener(event.name, event.handler);
  2248. try {
  2249. if (window.parent) {
  2250. window.parent.removeEventListener(event.name, event.handler);
  2251. }
  2252. } catch (e) {
  2253. }
  2254. }
  2255. };
  2256. Tools.GetFps = function () {
  2257. return fps;
  2258. };
  2259. Tools.GetDeltaTime = function () {
  2260. return deltaTime;
  2261. };
  2262. Tools._MeasureFps = function () {
  2263. previousFramesDuration.push(Tools.Now);
  2264. var length = previousFramesDuration.length;
  2265. if (length >= 2) {
  2266. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2267. }
  2268. if (length >= fpsRange) {
  2269. if (length > fpsRange) {
  2270. previousFramesDuration.splice(0, 1);
  2271. length = previousFramesDuration.length;
  2272. }
  2273. var sum = 0;
  2274. for (var id = 0; id < length - 1; id++) {
  2275. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2276. }
  2277. fps = 1000.0 / (sum / (length - 1));
  2278. }
  2279. };
  2280. Tools.CreateScreenshot = function (engine, camera, size) {
  2281. var width;
  2282. var height;
  2283. var scene = camera.getScene();
  2284. var previousCamera = null;
  2285. if (scene.activeCamera !== camera) {
  2286. previousCamera = scene.activeCamera;
  2287. scene.activeCamera = camera;
  2288. }
  2289. if (size.precision) {
  2290. width = Math.round(engine.getRenderWidth() * size.precision);
  2291. height = Math.round(width / engine.getAspectRatio(camera));
  2292. size = { width: width, height: height };
  2293. } else if (size.width && size.height) {
  2294. width = size.width;
  2295. height = size.height;
  2296. } else if (size.width && !size.height) {
  2297. width = size.width;
  2298. height = Math.round(width / engine.getAspectRatio(camera));
  2299. size = { width: width, height: height };
  2300. } else if (size.height && !size.width) {
  2301. height = size.height;
  2302. width = Math.round(height * engine.getAspectRatio(camera));
  2303. size = { width: width, height: height };
  2304. } else if (!isNaN(size)) {
  2305. height = size;
  2306. width = size;
  2307. } else {
  2308. Tools.Error("Invalid 'size' parameter !");
  2309. return;
  2310. }
  2311. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2312. texture.renderList = engine.scenes[0].meshes;
  2313. texture.onAfterRender = function () {
  2314. var numberOfChannelsByLine = width * 4;
  2315. var halfHeight = height / 2;
  2316. var data = engine.readPixels(0, 0, width, height);
  2317. for (var i = 0; i < halfHeight; i++) {
  2318. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2319. var currentCell = j + i * numberOfChannelsByLine;
  2320. var targetLine = height - i - 1;
  2321. var targetCell = j + targetLine * numberOfChannelsByLine;
  2322. var temp = data[currentCell];
  2323. data[currentCell] = data[targetCell];
  2324. data[targetCell] = temp;
  2325. }
  2326. }
  2327. if (!screenshotCanvas) {
  2328. screenshotCanvas = document.createElement('canvas');
  2329. }
  2330. screenshotCanvas.width = width;
  2331. screenshotCanvas.height = height;
  2332. var context = screenshotCanvas.getContext('2d');
  2333. var imageData = context.createImageData(width, height);
  2334. imageData.data.set(data);
  2335. context.putImageData(imageData, 0, 0);
  2336. var base64Image = screenshotCanvas.toDataURL();
  2337. if (("download" in document.createElement("a"))) {
  2338. var a = window.document.createElement("a");
  2339. a.href = base64Image;
  2340. var date = new Date();
  2341. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2342. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2343. window.document.body.appendChild(a);
  2344. a.addEventListener("click", function () {
  2345. a.parentElement.removeChild(a);
  2346. });
  2347. a.click();
  2348. } else {
  2349. var newWindow = window.open("");
  2350. var img = newWindow.document.createElement("img");
  2351. img.src = base64Image;
  2352. newWindow.document.body.appendChild(img);
  2353. }
  2354. };
  2355. texture.render(true);
  2356. texture.dispose();
  2357. if (previousCamera) {
  2358. scene.activeCamera = previousCamera;
  2359. }
  2360. };
  2361. Tools.ValidateXHRData = function (xhr, dataType) {
  2362. if (typeof dataType === "undefined") { dataType = 7; }
  2363. try {
  2364. if (dataType & 1) {
  2365. if (xhr.responseText && xhr.responseText.length > 0) {
  2366. return true;
  2367. } else if (dataType === 1) {
  2368. return false;
  2369. }
  2370. }
  2371. if (dataType & 2) {
  2372. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2373. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2374. return true;
  2375. } else if (dataType === 2) {
  2376. return false;
  2377. }
  2378. }
  2379. if (dataType & 4) {
  2380. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2381. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2382. return true;
  2383. } else {
  2384. return false;
  2385. }
  2386. }
  2387. } catch (e) {
  2388. }
  2389. return false;
  2390. };
  2391. Object.defineProperty(Tools, "NoneLogLevel", {
  2392. get: function () {
  2393. return Tools._NoneLogLevel;
  2394. },
  2395. enumerable: true,
  2396. configurable: true
  2397. });
  2398. Object.defineProperty(Tools, "MessageLogLevel", {
  2399. get: function () {
  2400. return Tools._MessageLogLevel;
  2401. },
  2402. enumerable: true,
  2403. configurable: true
  2404. });
  2405. Object.defineProperty(Tools, "WarningLogLevel", {
  2406. get: function () {
  2407. return Tools._WarningLogLevel;
  2408. },
  2409. enumerable: true,
  2410. configurable: true
  2411. });
  2412. Object.defineProperty(Tools, "ErrorLogLevel", {
  2413. get: function () {
  2414. return Tools._ErrorLogLevel;
  2415. },
  2416. enumerable: true,
  2417. configurable: true
  2418. });
  2419. Object.defineProperty(Tools, "AllLogLevel", {
  2420. get: function () {
  2421. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2422. },
  2423. enumerable: true,
  2424. configurable: true
  2425. });
  2426. Tools._FormatMessage = function (message) {
  2427. var padStr = function (i) {
  2428. return (i < 10) ? "0" + i : "" + i;
  2429. };
  2430. var date = new Date();
  2431. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2432. };
  2433. Tools._LogDisabled = function (message) {
  2434. };
  2435. Tools._LogEnabled = function (message) {
  2436. console.log(Tools._FormatMessage(message));
  2437. };
  2438. Tools._WarnDisabled = function (message) {
  2439. };
  2440. Tools._WarnEnabled = function (message) {
  2441. console.warn(Tools._FormatMessage(message));
  2442. };
  2443. Tools._ErrorDisabled = function (message) {
  2444. };
  2445. Tools._ErrorEnabled = function (message) {
  2446. console.error(Tools._FormatMessage(message));
  2447. };
  2448. Object.defineProperty(Tools, "LogLevels", {
  2449. set: function (level) {
  2450. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2451. Tools.Log = Tools._LogEnabled;
  2452. } else {
  2453. Tools.Log = Tools._LogDisabled;
  2454. }
  2455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2456. Tools.Warn = Tools._WarnEnabled;
  2457. } else {
  2458. Tools.Warn = Tools._WarnDisabled;
  2459. }
  2460. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2461. Tools.Error = Tools._ErrorEnabled;
  2462. } else {
  2463. Tools.Error = Tools._ErrorDisabled;
  2464. }
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2470. get: function () {
  2471. return Tools._PerformanceNoneLogLevel;
  2472. },
  2473. enumerable: true,
  2474. configurable: true
  2475. });
  2476. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2477. get: function () {
  2478. return Tools._PerformanceUserMarkLogLevel;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2484. get: function () {
  2485. return Tools._PerformanceConsoleLogLevel;
  2486. },
  2487. enumerable: true,
  2488. configurable: true
  2489. });
  2490. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2491. set: function (level) {
  2492. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2493. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2494. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2495. return;
  2496. }
  2497. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2498. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2499. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2500. return;
  2501. }
  2502. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2503. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2504. },
  2505. enumerable: true,
  2506. configurable: true
  2507. });
  2508. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2509. };
  2510. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2511. };
  2512. Tools._StartUserMark = function (counterName, condition) {
  2513. if (typeof condition === "undefined") { condition = true; }
  2514. if (!condition || !Tools._performance.mark) {
  2515. return;
  2516. }
  2517. Tools._performance.mark(counterName + "-Begin");
  2518. };
  2519. Tools._EndUserMark = function (counterName, condition) {
  2520. if (typeof condition === "undefined") { condition = true; }
  2521. if (!condition || !Tools._performance.mark) {
  2522. return;
  2523. }
  2524. Tools._performance.mark(counterName + "-End");
  2525. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2526. };
  2527. Tools._StartPerformanceConsole = function (counterName, condition) {
  2528. if (typeof condition === "undefined") { condition = true; }
  2529. if (!condition) {
  2530. return;
  2531. }
  2532. Tools._StartUserMark(counterName, condition);
  2533. if (console.time) {
  2534. console.time(counterName);
  2535. }
  2536. };
  2537. Tools._EndPerformanceConsole = function (counterName, condition) {
  2538. if (typeof condition === "undefined") { condition = true; }
  2539. if (!condition) {
  2540. return;
  2541. }
  2542. Tools._EndUserMark(counterName, condition);
  2543. if (console.time) {
  2544. console.timeEnd(counterName);
  2545. }
  2546. };
  2547. Object.defineProperty(Tools, "Now", {
  2548. get: function () {
  2549. if (window.performance && window.performance.now) {
  2550. return window.performance.now();
  2551. }
  2552. return new Date().getTime();
  2553. },
  2554. enumerable: true,
  2555. configurable: true
  2556. });
  2557. Tools.BaseUrl = "";
  2558. Tools.GetExponantOfTwo = function (value, max) {
  2559. var count = 1;
  2560. do {
  2561. count *= 2;
  2562. } while(count < value);
  2563. if (count > max)
  2564. count = max;
  2565. return count;
  2566. };
  2567. Tools._NoneLogLevel = 0;
  2568. Tools._MessageLogLevel = 1;
  2569. Tools._WarningLogLevel = 2;
  2570. Tools._ErrorLogLevel = 4;
  2571. Tools.Log = Tools._LogEnabled;
  2572. Tools.Warn = Tools._WarnEnabled;
  2573. Tools.Error = Tools._ErrorEnabled;
  2574. Tools._PerformanceNoneLogLevel = 0;
  2575. Tools._PerformanceUserMarkLogLevel = 1;
  2576. Tools._PerformanceConsoleLogLevel = 2;
  2577. Tools._performance = window.performance;
  2578. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2579. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2580. return Tools;
  2581. })();
  2582. BABYLON.Tools = Tools;
  2583. })(BABYLON || (BABYLON = {}));
  2584. var BABYLON;
  2585. (function (BABYLON) {
  2586. var _DepthCullingState = (function () {
  2587. function _DepthCullingState() {
  2588. this._isDepthTestDirty = false;
  2589. this._isDepthMaskDirty = false;
  2590. this._isDepthFuncDirty = false;
  2591. this._isCullFaceDirty = false;
  2592. this._isCullDirty = false;
  2593. }
  2594. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2595. get: function () {
  2596. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2597. },
  2598. enumerable: true,
  2599. configurable: true
  2600. });
  2601. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2602. get: function () {
  2603. return this._cullFace;
  2604. },
  2605. set: function (value) {
  2606. if (this._cullFace === value) {
  2607. return;
  2608. }
  2609. this._cullFace = value;
  2610. this._isCullFaceDirty = true;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2616. get: function () {
  2617. return this._cull;
  2618. },
  2619. set: function (value) {
  2620. if (this._cull === value) {
  2621. return;
  2622. }
  2623. this._cull = value;
  2624. this._isCullDirty = true;
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2630. get: function () {
  2631. return this._depthFunc;
  2632. },
  2633. set: function (value) {
  2634. if (this._depthFunc === value) {
  2635. return;
  2636. }
  2637. this._depthFunc = value;
  2638. this._isDepthFuncDirty = true;
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2644. get: function () {
  2645. return this._depthMask;
  2646. },
  2647. set: function (value) {
  2648. if (this._depthMask === value) {
  2649. return;
  2650. }
  2651. this._depthMask = value;
  2652. this._isDepthMaskDirty = true;
  2653. },
  2654. enumerable: true,
  2655. configurable: true
  2656. });
  2657. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2658. get: function () {
  2659. return this._depthTest;
  2660. },
  2661. set: function (value) {
  2662. if (this._depthTest === value) {
  2663. return;
  2664. }
  2665. this._depthTest = value;
  2666. this._isDepthTestDirty = true;
  2667. },
  2668. enumerable: true,
  2669. configurable: true
  2670. });
  2671. _DepthCullingState.prototype.reset = function () {
  2672. this._depthMask = true;
  2673. this._depthTest = true;
  2674. this._depthFunc = null;
  2675. this._cull = null;
  2676. this._cullFace = null;
  2677. this._isDepthTestDirty = true;
  2678. this._isDepthMaskDirty = true;
  2679. this._isDepthFuncDirty = false;
  2680. this._isCullFaceDirty = false;
  2681. this._isCullDirty = false;
  2682. };
  2683. _DepthCullingState.prototype.apply = function (gl) {
  2684. if (!this.isDirty) {
  2685. return;
  2686. }
  2687. if (this._isCullDirty) {
  2688. if (this.cull === true) {
  2689. gl.enable(gl.CULL_FACE);
  2690. } else if (this.cull === false) {
  2691. gl.disable(gl.CULL_FACE);
  2692. }
  2693. this._isCullDirty = false;
  2694. }
  2695. if (this._isCullFaceDirty) {
  2696. gl.cullFace(this.cullFace);
  2697. this._isCullFaceDirty = false;
  2698. }
  2699. if (this._isDepthMaskDirty) {
  2700. gl.depthMask(this.depthMask);
  2701. this._isDepthMaskDirty = false;
  2702. }
  2703. if (this._isDepthTestDirty) {
  2704. if (this.depthTest === true) {
  2705. gl.enable(gl.DEPTH_TEST);
  2706. } else if (this.depthTest === false) {
  2707. gl.disable(gl.DEPTH_TEST);
  2708. }
  2709. this._isDepthTestDirty = false;
  2710. }
  2711. if (this._isDepthFuncDirty) {
  2712. gl.depthFunc(this.depthFunc);
  2713. this._isDepthFuncDirty = false;
  2714. }
  2715. };
  2716. return _DepthCullingState;
  2717. })();
  2718. BABYLON._DepthCullingState = _DepthCullingState;
  2719. var _AlphaState = (function () {
  2720. function _AlphaState() {
  2721. this._isAlphaBlendDirty = false;
  2722. this._isBlendFunctionParametersDirty = false;
  2723. this._alphaBlend = false;
  2724. this._blendFunctionParameters = new Array(4);
  2725. }
  2726. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2727. get: function () {
  2728. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2729. },
  2730. enumerable: true,
  2731. configurable: true
  2732. });
  2733. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2734. get: function () {
  2735. return this._alphaBlend;
  2736. },
  2737. set: function (value) {
  2738. if (this._alphaBlend === value) {
  2739. return;
  2740. }
  2741. this._alphaBlend = value;
  2742. this._isAlphaBlendDirty = true;
  2743. },
  2744. enumerable: true,
  2745. configurable: true
  2746. });
  2747. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2748. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2749. return;
  2750. }
  2751. this._blendFunctionParameters[0] = value0;
  2752. this._blendFunctionParameters[1] = value1;
  2753. this._blendFunctionParameters[2] = value2;
  2754. this._blendFunctionParameters[3] = value3;
  2755. this._isBlendFunctionParametersDirty = true;
  2756. };
  2757. _AlphaState.prototype.reset = function () {
  2758. this._alphaBlend = false;
  2759. this._blendFunctionParameters[0] = null;
  2760. this._blendFunctionParameters[1] = null;
  2761. this._blendFunctionParameters[2] = null;
  2762. this._blendFunctionParameters[3] = null;
  2763. this._isAlphaBlendDirty = true;
  2764. this._isBlendFunctionParametersDirty = false;
  2765. };
  2766. _AlphaState.prototype.apply = function (gl) {
  2767. if (!this.isDirty) {
  2768. return;
  2769. }
  2770. if (this._isAlphaBlendDirty) {
  2771. if (this._alphaBlend === true) {
  2772. gl.enable(gl.BLEND);
  2773. } else if (this._alphaBlend === false) {
  2774. gl.disable(gl.BLEND);
  2775. }
  2776. this._isAlphaBlendDirty = false;
  2777. }
  2778. if (this._isBlendFunctionParametersDirty) {
  2779. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2780. this._isBlendFunctionParametersDirty = false;
  2781. }
  2782. };
  2783. return _AlphaState;
  2784. })();
  2785. BABYLON._AlphaState = _AlphaState;
  2786. var compileShader = function (gl, source, type, defines) {
  2787. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2788. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2789. gl.compileShader(shader);
  2790. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2791. throw new Error(gl.getShaderInfoLog(shader));
  2792. }
  2793. return shader;
  2794. };
  2795. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2796. var magFilter = gl.NEAREST;
  2797. var minFilter = gl.NEAREST;
  2798. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2799. magFilter = gl.LINEAR;
  2800. if (generateMipMaps) {
  2801. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2802. } else {
  2803. minFilter = gl.LINEAR;
  2804. }
  2805. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2806. magFilter = gl.LINEAR;
  2807. if (generateMipMaps) {
  2808. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2809. } else {
  2810. minFilter = gl.LINEAR;
  2811. }
  2812. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2813. magFilter = gl.NEAREST;
  2814. if (generateMipMaps) {
  2815. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2816. } else {
  2817. minFilter = gl.NEAREST;
  2818. }
  2819. }
  2820. return {
  2821. min: minFilter,
  2822. mag: magFilter
  2823. };
  2824. };
  2825. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2826. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2827. var engine = scene.getEngine();
  2828. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2829. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2830. gl.bindTexture(gl.TEXTURE_2D, texture);
  2831. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2832. processFunction(potWidth, potHeight);
  2833. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2836. if (!noMipmap && !isCompressed) {
  2837. gl.generateMipmap(gl.TEXTURE_2D);
  2838. }
  2839. gl.bindTexture(gl.TEXTURE_2D, null);
  2840. engine._activeTexturesCache = [];
  2841. texture._baseWidth = width;
  2842. texture._baseHeight = height;
  2843. texture._width = potWidth;
  2844. texture._height = potHeight;
  2845. texture.isReady = true;
  2846. scene._removePendingData(texture);
  2847. };
  2848. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2849. var img;
  2850. var onload = function () {
  2851. loadedImages[index] = img;
  2852. loadedImages._internalCount++;
  2853. scene._removePendingData(img);
  2854. if (loadedImages._internalCount == 6) {
  2855. onfinish(loadedImages);
  2856. }
  2857. };
  2858. var onerror = function () {
  2859. scene._removePendingData(img);
  2860. };
  2861. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2862. scene._addPendingData(img);
  2863. };
  2864. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2865. var loadedImages = [];
  2866. loadedImages._internalCount = 0;
  2867. for (var index = 0; index < 6; index++) {
  2868. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2869. }
  2870. };
  2871. var EngineCapabilities = (function () {
  2872. function EngineCapabilities() {
  2873. }
  2874. return EngineCapabilities;
  2875. })();
  2876. BABYLON.EngineCapabilities = EngineCapabilities;
  2877. var Engine = (function () {
  2878. function Engine(canvas, antialias, options) {
  2879. var _this = this;
  2880. this.isFullscreen = false;
  2881. this.isPointerLock = false;
  2882. this.forceWireframe = false;
  2883. this.cullBackFaces = true;
  2884. this.renderEvenInBackground = true;
  2885. this.scenes = new Array();
  2886. this._windowIsBackground = false;
  2887. this._runningLoop = false;
  2888. this._loadingDivBackgroundColor = "black";
  2889. this._depthCullingState = new _DepthCullingState();
  2890. this._alphaState = new _AlphaState();
  2891. this._loadedTexturesCache = new Array();
  2892. this._activeTexturesCache = new Array();
  2893. this._compiledEffects = {};
  2894. this._renderingCanvas = canvas;
  2895. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2896. options = options || {};
  2897. options.antialias = antialias;
  2898. try {
  2899. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2900. } catch (e) {
  2901. throw new Error("WebGL not supported");
  2902. }
  2903. if (!this._gl) {
  2904. throw new Error("WebGL not supported");
  2905. }
  2906. this._onBlur = function () {
  2907. _this._windowIsBackground = true;
  2908. };
  2909. this._onFocus = function () {
  2910. _this._windowIsBackground = false;
  2911. };
  2912. window.addEventListener("blur", this._onBlur);
  2913. window.addEventListener("focus", this._onFocus);
  2914. this._workingCanvas = document.createElement("canvas");
  2915. this._workingContext = this._workingCanvas.getContext("2d");
  2916. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2917. this.resize();
  2918. this._caps = new EngineCapabilities();
  2919. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2920. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2921. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2922. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2923. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2924. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2925. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2926. 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');
  2927. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2928. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2929. this.setDepthBuffer(true);
  2930. this.setDepthFunctionToLessOrEqual();
  2931. this.setDepthWrite(true);
  2932. this._onFullscreenChange = function () {
  2933. if (document.fullscreen !== undefined) {
  2934. _this.isFullscreen = document.fullscreen;
  2935. } else if (document.mozFullScreen !== undefined) {
  2936. _this.isFullscreen = document.mozFullScreen;
  2937. } else if (document.webkitIsFullScreen !== undefined) {
  2938. _this.isFullscreen = document.webkitIsFullScreen;
  2939. } else if (document.msIsFullScreen !== undefined) {
  2940. _this.isFullscreen = document.msIsFullScreen;
  2941. }
  2942. if (_this.isFullscreen && _this._pointerLockRequested) {
  2943. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2944. if (canvas.requestPointerLock) {
  2945. canvas.requestPointerLock();
  2946. }
  2947. }
  2948. };
  2949. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2950. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2951. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2952. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2953. this._onPointerLockChange = function () {
  2954. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2955. };
  2956. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2957. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2958. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2959. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2960. }
  2961. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2962. get: function () {
  2963. return Engine._ALPHA_DISABLE;
  2964. },
  2965. enumerable: true,
  2966. configurable: true
  2967. });
  2968. Object.defineProperty(Engine, "ALPHA_ADD", {
  2969. get: function () {
  2970. return Engine._ALPHA_ADD;
  2971. },
  2972. enumerable: true,
  2973. configurable: true
  2974. });
  2975. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2976. get: function () {
  2977. return Engine._ALPHA_COMBINE;
  2978. },
  2979. enumerable: true,
  2980. configurable: true
  2981. });
  2982. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  2983. get: function () {
  2984. return Engine._DELAYLOADSTATE_NONE;
  2985. },
  2986. enumerable: true,
  2987. configurable: true
  2988. });
  2989. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  2990. get: function () {
  2991. return Engine._DELAYLOADSTATE_LOADED;
  2992. },
  2993. enumerable: true,
  2994. configurable: true
  2995. });
  2996. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  2997. get: function () {
  2998. return Engine._DELAYLOADSTATE_LOADING;
  2999. },
  3000. enumerable: true,
  3001. configurable: true
  3002. });
  3003. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3004. get: function () {
  3005. return Engine._DELAYLOADSTATE_NOTLOADED;
  3006. },
  3007. enumerable: true,
  3008. configurable: true
  3009. });
  3010. Object.defineProperty(Engine, "Version", {
  3011. get: function () {
  3012. return "2.0.0";
  3013. },
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. Engine.prototype.getAspectRatio = function (camera) {
  3018. var viewport = camera.viewport;
  3019. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3020. };
  3021. Engine.prototype.getRenderWidth = function () {
  3022. if (this._currentRenderTarget) {
  3023. return this._currentRenderTarget._width;
  3024. }
  3025. return this._renderingCanvas.width;
  3026. };
  3027. Engine.prototype.getRenderHeight = function () {
  3028. if (this._currentRenderTarget) {
  3029. return this._currentRenderTarget._height;
  3030. }
  3031. return this._renderingCanvas.height;
  3032. };
  3033. Engine.prototype.getRenderingCanvas = function () {
  3034. return this._renderingCanvas;
  3035. };
  3036. Engine.prototype.getRenderingCanvasClientRect = function () {
  3037. return this._renderingCanvas.getBoundingClientRect();
  3038. };
  3039. Engine.prototype.setHardwareScalingLevel = function (level) {
  3040. this._hardwareScalingLevel = level;
  3041. this.resize();
  3042. };
  3043. Engine.prototype.getHardwareScalingLevel = function () {
  3044. return this._hardwareScalingLevel;
  3045. };
  3046. Engine.prototype.getLoadedTexturesCache = function () {
  3047. return this._loadedTexturesCache;
  3048. };
  3049. Engine.prototype.getCaps = function () {
  3050. return this._caps;
  3051. };
  3052. Engine.prototype.setDepthFunctionToGreater = function () {
  3053. this._depthCullingState.depthFunc = this._gl.GREATER;
  3054. };
  3055. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3056. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3057. };
  3058. Engine.prototype.setDepthFunctionToLess = function () {
  3059. this._depthCullingState.depthFunc = this._gl.LESS;
  3060. };
  3061. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3062. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3063. };
  3064. Engine.prototype.stopRenderLoop = function () {
  3065. this._renderFunction = null;
  3066. this._runningLoop = false;
  3067. };
  3068. Engine.prototype._renderLoop = function () {
  3069. var _this = this;
  3070. var shouldRender = true;
  3071. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3072. shouldRender = false;
  3073. }
  3074. if (shouldRender) {
  3075. this.beginFrame();
  3076. if (this._renderFunction) {
  3077. this._renderFunction();
  3078. }
  3079. this.endFrame();
  3080. }
  3081. if (this._runningLoop) {
  3082. BABYLON.Tools.QueueNewFrame(function () {
  3083. _this._renderLoop();
  3084. });
  3085. }
  3086. };
  3087. Engine.prototype.runRenderLoop = function (renderFunction) {
  3088. var _this = this;
  3089. this._runningLoop = true;
  3090. this._renderFunction = renderFunction;
  3091. BABYLON.Tools.QueueNewFrame(function () {
  3092. _this._renderLoop();
  3093. });
  3094. };
  3095. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3096. if (this.isFullscreen) {
  3097. BABYLON.Tools.ExitFullscreen();
  3098. } else {
  3099. this._pointerLockRequested = requestPointerLock;
  3100. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3101. }
  3102. };
  3103. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3104. this.applyStates();
  3105. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3106. if (this._depthCullingState.depthMask) {
  3107. this._gl.clearDepth(1.0);
  3108. }
  3109. var mode = 0;
  3110. if (backBuffer)
  3111. mode |= this._gl.COLOR_BUFFER_BIT;
  3112. if (depthStencil && this._depthCullingState.depthMask)
  3113. mode |= this._gl.DEPTH_BUFFER_BIT;
  3114. this._gl.clear(mode);
  3115. };
  3116. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3117. var width = requiredWidth || this._renderingCanvas.width;
  3118. var height = requiredHeight || this._renderingCanvas.height;
  3119. var x = viewport.x || 0;
  3120. var y = viewport.y || 0;
  3121. this._cachedViewport = viewport;
  3122. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3123. };
  3124. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3125. this._cachedViewport = null;
  3126. this._gl.viewport(x, y, width, height);
  3127. };
  3128. Engine.prototype.beginFrame = function () {
  3129. BABYLON.Tools._MeasureFps();
  3130. };
  3131. Engine.prototype.endFrame = function () {
  3132. this.flushFramebuffer();
  3133. };
  3134. Engine.prototype.resize = function () {
  3135. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3136. };
  3137. Engine.prototype.setSize = function (width, height) {
  3138. this._renderingCanvas.width = width;
  3139. this._renderingCanvas.height = height;
  3140. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3141. };
  3142. Engine.prototype.bindFramebuffer = function (texture) {
  3143. this._currentRenderTarget = texture;
  3144. var gl = this._gl;
  3145. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3146. this._gl.viewport(0, 0, texture._width, texture._height);
  3147. this.wipeCaches();
  3148. };
  3149. Engine.prototype.unBindFramebuffer = function (texture) {
  3150. this._currentRenderTarget = null;
  3151. if (texture.generateMipMaps) {
  3152. var gl = this._gl;
  3153. gl.bindTexture(gl.TEXTURE_2D, texture);
  3154. gl.generateMipmap(gl.TEXTURE_2D);
  3155. gl.bindTexture(gl.TEXTURE_2D, null);
  3156. }
  3157. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3158. };
  3159. Engine.prototype.flushFramebuffer = function () {
  3160. this._gl.flush();
  3161. };
  3162. Engine.prototype.restoreDefaultFramebuffer = function () {
  3163. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3164. this.setViewport(this._cachedViewport);
  3165. this.wipeCaches();
  3166. };
  3167. Engine.prototype._resetVertexBufferBinding = function () {
  3168. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3169. this._cachedVertexBuffers = null;
  3170. };
  3171. Engine.prototype.createVertexBuffer = function (vertices) {
  3172. var vbo = this._gl.createBuffer();
  3173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3174. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3175. this._resetVertexBufferBinding();
  3176. vbo.references = 1;
  3177. return vbo;
  3178. };
  3179. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3180. var vbo = this._gl.createBuffer();
  3181. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3182. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3183. this._resetVertexBufferBinding();
  3184. vbo.references = 1;
  3185. return vbo;
  3186. };
  3187. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3188. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3189. if (vertices instanceof Float32Array) {
  3190. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3191. } else {
  3192. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3193. }
  3194. this._resetVertexBufferBinding();
  3195. };
  3196. Engine.prototype._resetIndexBufferBinding = function () {
  3197. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3198. this._cachedIndexBuffer = null;
  3199. };
  3200. Engine.prototype.createIndexBuffer = function (indices) {
  3201. var vbo = this._gl.createBuffer();
  3202. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3203. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), this._gl.STATIC_DRAW);
  3204. this._resetIndexBufferBinding();
  3205. vbo.references = 1;
  3206. return vbo;
  3207. };
  3208. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3209. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3210. this._cachedVertexBuffers = vertexBuffer;
  3211. this._cachedEffectForVertexBuffers = effect;
  3212. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3213. var offset = 0;
  3214. for (var index = 0; index < vertexDeclaration.length; index++) {
  3215. var order = effect.getAttributeLocation(index);
  3216. if (order >= 0) {
  3217. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3218. }
  3219. offset += vertexDeclaration[index] * 4;
  3220. }
  3221. }
  3222. if (this._cachedIndexBuffer !== indexBuffer) {
  3223. this._cachedIndexBuffer = indexBuffer;
  3224. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3225. }
  3226. };
  3227. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3228. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3229. this._cachedVertexBuffers = vertexBuffers;
  3230. this._cachedEffectForVertexBuffers = effect;
  3231. var attributes = effect.getAttributesNames();
  3232. for (var index = 0; index < attributes.length; index++) {
  3233. var order = effect.getAttributeLocation(index);
  3234. if (order >= 0) {
  3235. var vertexBuffer = vertexBuffers[attributes[index]];
  3236. if (!vertexBuffer) {
  3237. continue;
  3238. }
  3239. var stride = vertexBuffer.getStrideSize();
  3240. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3241. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3242. }
  3243. }
  3244. }
  3245. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3246. this._cachedIndexBuffer = indexBuffer;
  3247. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3248. }
  3249. };
  3250. Engine.prototype._releaseBuffer = function (buffer) {
  3251. buffer.references--;
  3252. if (buffer.references === 0) {
  3253. this._gl.deleteBuffer(buffer);
  3254. return true;
  3255. }
  3256. return false;
  3257. };
  3258. Engine.prototype.createInstancesBuffer = function (capacity) {
  3259. var buffer = this._gl.createBuffer();
  3260. buffer.capacity = capacity;
  3261. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3262. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3263. return buffer;
  3264. };
  3265. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3266. this._gl.deleteBuffer(buffer);
  3267. };
  3268. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3269. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3270. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3271. for (var index = 0; index < 4; index++) {
  3272. var offsetLocation = offsetLocations[index];
  3273. this._gl.enableVertexAttribArray(offsetLocation);
  3274. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3275. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3276. }
  3277. };
  3278. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3279. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3280. for (var index = 0; index < 4; index++) {
  3281. var offsetLocation = offsetLocations[index];
  3282. this._gl.disableVertexAttribArray(offsetLocation);
  3283. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3284. }
  3285. };
  3286. Engine.prototype.applyStates = function () {
  3287. this._depthCullingState.apply(this._gl);
  3288. this._alphaState.apply(this._gl);
  3289. };
  3290. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3291. this.applyStates();
  3292. if (instancesCount) {
  3293. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2, instancesCount);
  3294. return;
  3295. }
  3296. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, this._gl.UNSIGNED_SHORT, indexStart * 2);
  3297. };
  3298. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3299. this.applyStates();
  3300. if (instancesCount) {
  3301. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3302. return;
  3303. }
  3304. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3305. };
  3306. Engine.prototype._releaseEffect = function (effect) {
  3307. if (this._compiledEffects[effect._key]) {
  3308. delete this._compiledEffects[effect._key];
  3309. if (effect.getProgram()) {
  3310. this._gl.deleteProgram(effect.getProgram());
  3311. }
  3312. }
  3313. };
  3314. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3315. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3316. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3317. var name = vertex + "+" + fragment + "@" + defines;
  3318. if (this._compiledEffects[name]) {
  3319. return this._compiledEffects[name];
  3320. }
  3321. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3322. effect._key = name;
  3323. this._compiledEffects[name] = effect;
  3324. return effect;
  3325. };
  3326. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3327. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3328. if (typeof samplers === "undefined") { samplers = []; }
  3329. if (typeof defines === "undefined") { defines = ""; }
  3330. return this.createEffect({
  3331. vertex: "particles",
  3332. fragmentElement: fragmentName
  3333. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3334. };
  3335. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3336. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3337. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3338. var shaderProgram = this._gl.createProgram();
  3339. this._gl.attachShader(shaderProgram, vertexShader);
  3340. this._gl.attachShader(shaderProgram, fragmentShader);
  3341. this._gl.linkProgram(shaderProgram);
  3342. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3343. if (!linked) {
  3344. var error = this._gl.getProgramInfoLog(shaderProgram);
  3345. if (error) {
  3346. throw new Error(error);
  3347. }
  3348. }
  3349. this._gl.deleteShader(vertexShader);
  3350. this._gl.deleteShader(fragmentShader);
  3351. return shaderProgram;
  3352. };
  3353. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3354. var results = [];
  3355. for (var index = 0; index < uniformsNames.length; index++) {
  3356. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3357. }
  3358. return results;
  3359. };
  3360. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3361. var results = [];
  3362. for (var index = 0; index < attributesNames.length; index++) {
  3363. try {
  3364. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3365. } catch (e) {
  3366. results.push(-1);
  3367. }
  3368. }
  3369. return results;
  3370. };
  3371. Engine.prototype.enableEffect = function (effect) {
  3372. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3373. if (effect && effect.onBind) {
  3374. effect.onBind(effect);
  3375. }
  3376. return;
  3377. }
  3378. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3379. this._gl.useProgram(effect.getProgram());
  3380. for (var i in this._vertexAttribArrays) {
  3381. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3382. continue;
  3383. }
  3384. this._vertexAttribArrays[i] = false;
  3385. this._gl.disableVertexAttribArray(i);
  3386. }
  3387. var attributesCount = effect.getAttributesCount();
  3388. for (var index = 0; index < attributesCount; index++) {
  3389. var order = effect.getAttributeLocation(index);
  3390. if (order >= 0) {
  3391. this._vertexAttribArrays[order] = true;
  3392. this._gl.enableVertexAttribArray(order);
  3393. }
  3394. }
  3395. this._currentEffect = effect;
  3396. if (effect.onBind) {
  3397. effect.onBind(effect);
  3398. }
  3399. };
  3400. Engine.prototype.setArray = function (uniform, array) {
  3401. if (!uniform)
  3402. return;
  3403. this._gl.uniform1fv(uniform, array);
  3404. };
  3405. Engine.prototype.setMatrices = function (uniform, matrices) {
  3406. if (!uniform)
  3407. return;
  3408. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3409. };
  3410. Engine.prototype.setMatrix = function (uniform, matrix) {
  3411. if (!uniform)
  3412. return;
  3413. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3414. };
  3415. Engine.prototype.setFloat = function (uniform, value) {
  3416. if (!uniform)
  3417. return;
  3418. this._gl.uniform1f(uniform, value);
  3419. };
  3420. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3421. if (!uniform)
  3422. return;
  3423. this._gl.uniform2f(uniform, x, y);
  3424. };
  3425. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3426. if (!uniform)
  3427. return;
  3428. this._gl.uniform3f(uniform, x, y, z);
  3429. };
  3430. Engine.prototype.setBool = function (uniform, bool) {
  3431. if (!uniform)
  3432. return;
  3433. this._gl.uniform1i(uniform, bool);
  3434. };
  3435. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3436. if (!uniform)
  3437. return;
  3438. this._gl.uniform4f(uniform, x, y, z, w);
  3439. };
  3440. Engine.prototype.setColor3 = function (uniform, color3) {
  3441. if (!uniform)
  3442. return;
  3443. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3444. };
  3445. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3446. if (!uniform)
  3447. return;
  3448. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3449. };
  3450. Engine.prototype.setState = function (culling, force) {
  3451. if (this._depthCullingState.cull !== culling || force) {
  3452. if (culling) {
  3453. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3454. this._depthCullingState.cull = true;
  3455. } else {
  3456. this._depthCullingState.cull = false;
  3457. }
  3458. }
  3459. };
  3460. Engine.prototype.setDepthBuffer = function (enable) {
  3461. this._depthCullingState.depthTest = enable;
  3462. };
  3463. Engine.prototype.getDepthWrite = function () {
  3464. return this._depthCullingState.depthMask;
  3465. };
  3466. Engine.prototype.setDepthWrite = function (enable) {
  3467. this._depthCullingState.depthMask = enable;
  3468. };
  3469. Engine.prototype.setColorWrite = function (enable) {
  3470. this._gl.colorMask(enable, enable, enable, enable);
  3471. };
  3472. Engine.prototype.setAlphaMode = function (mode) {
  3473. switch (mode) {
  3474. case BABYLON.Engine.ALPHA_DISABLE:
  3475. this.setDepthWrite(true);
  3476. this._alphaState.alphaBlend = false;
  3477. break;
  3478. case BABYLON.Engine.ALPHA_COMBINE:
  3479. this.setDepthWrite(false);
  3480. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3481. this._alphaState.alphaBlend = true;
  3482. break;
  3483. case BABYLON.Engine.ALPHA_ADD:
  3484. this.setDepthWrite(false);
  3485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3486. this._alphaState.alphaBlend = true;
  3487. break;
  3488. }
  3489. };
  3490. Engine.prototype.setAlphaTesting = function (enable) {
  3491. this._alphaTest = enable;
  3492. };
  3493. Engine.prototype.getAlphaTesting = function () {
  3494. return this._alphaTest;
  3495. };
  3496. Engine.prototype.wipeCaches = function () {
  3497. this._activeTexturesCache = [];
  3498. this._currentEffect = null;
  3499. this._depthCullingState.reset();
  3500. this._alphaState.reset();
  3501. this._cachedVertexBuffers = null;
  3502. this._cachedIndexBuffer = null;
  3503. this._cachedEffectForVertexBuffers = null;
  3504. };
  3505. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3506. var gl = this._gl;
  3507. gl.bindTexture(gl.TEXTURE_2D, texture);
  3508. var magFilter = gl.NEAREST;
  3509. var minFilter = gl.NEAREST;
  3510. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3511. magFilter = gl.LINEAR;
  3512. minFilter = gl.LINEAR;
  3513. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3514. magFilter = gl.LINEAR;
  3515. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3516. }
  3517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3519. gl.bindTexture(gl.TEXTURE_2D, null);
  3520. };
  3521. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3522. var _this = this;
  3523. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3524. if (typeof onLoad === "undefined") { onLoad = null; }
  3525. if (typeof onError === "undefined") { onError = null; }
  3526. if (typeof buffer === "undefined") { buffer = null; }
  3527. var texture = this._gl.createTexture();
  3528. var extension;
  3529. var fromData = false;
  3530. if (url.substr(0, 5) === "data:") {
  3531. fromData = true;
  3532. }
  3533. if (!fromData)
  3534. extension = url.substr(url.length - 4, 4).toLowerCase();
  3535. else {
  3536. var oldUrl = url;
  3537. fromData = oldUrl.split(':');
  3538. url = oldUrl;
  3539. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3540. }
  3541. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3542. var isTGA = (extension === ".tga");
  3543. scene._addPendingData(texture);
  3544. texture.url = url;
  3545. texture.noMipmap = noMipmap;
  3546. texture.references = 1;
  3547. this._loadedTexturesCache.push(texture);
  3548. var onerror = function () {
  3549. scene._removePendingData(texture);
  3550. if (onError) {
  3551. onError();
  3552. }
  3553. };
  3554. if (isTGA) {
  3555. var callback = function (arrayBuffer) {
  3556. var data = new Uint8Array(arrayBuffer);
  3557. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3558. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3559. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3560. if (onLoad) {
  3561. onLoad();
  3562. }
  3563. }, samplingMode);
  3564. };
  3565. if (!(fromData instanceof Array))
  3566. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3567. callback(arrayBuffer);
  3568. }, onerror, scene.database, true);
  3569. else
  3570. callback(buffer);
  3571. } else if (isDDS) {
  3572. callback = function (data) {
  3573. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3574. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3575. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3576. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3577. if (onLoad) {
  3578. onLoad();
  3579. }
  3580. }, samplingMode);
  3581. };
  3582. if (!(fromData instanceof Array))
  3583. BABYLON.Tools.LoadFile(url, function (data) {
  3584. callback(data);
  3585. }, onerror, scene.database, true);
  3586. else
  3587. callback(buffer);
  3588. } else {
  3589. var onload = function (img) {
  3590. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3591. var isPot = (img.width == potWidth && img.height == potHeight);
  3592. if (!isPot) {
  3593. _this._workingCanvas.width = potWidth;
  3594. _this._workingCanvas.height = potHeight;
  3595. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3596. }
  3597. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3598. if (onLoad) {
  3599. onLoad();
  3600. }
  3601. }, samplingMode);
  3602. };
  3603. if (!(fromData instanceof Array))
  3604. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3605. else
  3606. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3607. }
  3608. return texture;
  3609. };
  3610. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3611. var texture = this._gl.createTexture();
  3612. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3613. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3614. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3615. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3617. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3618. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3619. this._activeTexturesCache = [];
  3620. texture._baseWidth = width;
  3621. texture._baseHeight = height;
  3622. texture._width = width;
  3623. texture._height = height;
  3624. texture.isReady = false;
  3625. texture.generateMipMaps = generateMipMaps;
  3626. texture.references = 1;
  3627. this._loadedTexturesCache.push(texture);
  3628. return texture;
  3629. };
  3630. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3631. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3632. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3633. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3634. if (texture.generateMipMaps) {
  3635. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3636. }
  3637. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3638. this._activeTexturesCache = [];
  3639. texture.isReady = true;
  3640. };
  3641. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3642. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3643. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3644. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3645. if (!texture._workingCanvas) {
  3646. texture._workingCanvas = document.createElement("canvas");
  3647. texture._workingContext = texture._workingCanvas.getContext("2d");
  3648. texture._workingCanvas.width = texture._width;
  3649. texture._workingCanvas.height = texture._height;
  3650. }
  3651. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3653. } else {
  3654. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3655. }
  3656. if (texture.generateMipMaps) {
  3657. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3658. }
  3659. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3660. this._activeTexturesCache = [];
  3661. texture.isReady = true;
  3662. };
  3663. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3664. var generateMipMaps = false;
  3665. var generateDepthBuffer = true;
  3666. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3667. if (options !== undefined) {
  3668. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3669. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3670. if (options.samplingMode !== undefined) {
  3671. samplingMode = options.samplingMode;
  3672. }
  3673. }
  3674. var gl = this._gl;
  3675. var texture = gl.createTexture();
  3676. gl.bindTexture(gl.TEXTURE_2D, texture);
  3677. var width = size.width || size;
  3678. var height = size.height || size;
  3679. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3680. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3684. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3685. var depthBuffer;
  3686. if (generateDepthBuffer) {
  3687. depthBuffer = gl.createRenderbuffer();
  3688. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3689. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3690. }
  3691. var framebuffer = gl.createFramebuffer();
  3692. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3693. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3694. if (generateDepthBuffer) {
  3695. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3696. }
  3697. gl.bindTexture(gl.TEXTURE_2D, null);
  3698. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3699. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3700. texture._framebuffer = framebuffer;
  3701. if (generateDepthBuffer) {
  3702. texture._depthBuffer = depthBuffer;
  3703. }
  3704. texture._width = width;
  3705. texture._height = height;
  3706. texture.isReady = true;
  3707. texture.generateMipMaps = generateMipMaps;
  3708. texture.references = 1;
  3709. this._activeTexturesCache = [];
  3710. this._loadedTexturesCache.push(texture);
  3711. return texture;
  3712. };
  3713. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3714. var _this = this;
  3715. var gl = this._gl;
  3716. var texture = gl.createTexture();
  3717. texture.isCube = true;
  3718. texture.url = rootUrl;
  3719. texture.references = 1;
  3720. this._loadedTexturesCache.push(texture);
  3721. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3722. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3723. if (isDDS) {
  3724. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3725. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3726. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3727. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3728. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3729. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3730. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3731. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3732. }
  3733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3737. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3738. _this._activeTexturesCache = [];
  3739. texture._width = info.width;
  3740. texture._height = info.height;
  3741. texture.isReady = true;
  3742. }, null, null, true);
  3743. } else {
  3744. cascadeLoad(rootUrl, scene, function (imgs) {
  3745. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3746. var height = width;
  3747. _this._workingCanvas.width = width;
  3748. _this._workingCanvas.height = height;
  3749. var faces = [
  3750. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3751. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3752. ];
  3753. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3754. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3755. for (var index = 0; index < faces.length; index++) {
  3756. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3757. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3758. }
  3759. if (!noMipmap) {
  3760. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3761. }
  3762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3766. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3767. _this._activeTexturesCache = [];
  3768. texture._width = width;
  3769. texture._height = height;
  3770. texture.isReady = true;
  3771. }, extensions);
  3772. }
  3773. return texture;
  3774. };
  3775. Engine.prototype._releaseTexture = function (texture) {
  3776. var gl = this._gl;
  3777. if (texture._framebuffer) {
  3778. gl.deleteFramebuffer(texture._framebuffer);
  3779. }
  3780. if (texture._depthBuffer) {
  3781. gl.deleteRenderbuffer(texture._depthBuffer);
  3782. }
  3783. gl.deleteTexture(texture);
  3784. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3788. this._activeTexturesCache[channel] = null;
  3789. }
  3790. var index = this._loadedTexturesCache.indexOf(texture);
  3791. if (index !== -1) {
  3792. this._loadedTexturesCache.splice(index, 1);
  3793. }
  3794. };
  3795. Engine.prototype.bindSamplers = function (effect) {
  3796. this._gl.useProgram(effect.getProgram());
  3797. var samplers = effect.getSamplers();
  3798. for (var index = 0; index < samplers.length; index++) {
  3799. var uniform = effect.getUniform(samplers[index]);
  3800. this._gl.uniform1i(uniform, index);
  3801. }
  3802. this._currentEffect = null;
  3803. };
  3804. Engine.prototype._bindTexture = function (channel, texture) {
  3805. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3806. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3807. this._activeTexturesCache[channel] = null;
  3808. };
  3809. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3810. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3811. };
  3812. Engine.prototype.setTexture = function (channel, texture) {
  3813. if (channel < 0) {
  3814. return;
  3815. }
  3816. if (!texture || !texture.isReady()) {
  3817. if (this._activeTexturesCache[channel] != null) {
  3818. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3819. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3820. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3821. this._activeTexturesCache[channel] = null;
  3822. }
  3823. return;
  3824. }
  3825. if (texture instanceof BABYLON.VideoTexture) {
  3826. if (texture.update()) {
  3827. this._activeTexturesCache[channel] = null;
  3828. }
  3829. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3830. texture.delayLoad();
  3831. return;
  3832. }
  3833. if (this._activeTexturesCache[channel] == texture) {
  3834. return;
  3835. }
  3836. this._activeTexturesCache[channel] = texture;
  3837. var internalTexture = texture.getInternalTexture();
  3838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3839. if (internalTexture.isCube) {
  3840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3841. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3842. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3843. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3844. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3845. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3846. }
  3847. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3848. } else {
  3849. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3850. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3851. internalTexture._cachedWrapU = texture.wrapU;
  3852. switch (texture.wrapU) {
  3853. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3855. break;
  3856. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3857. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3858. break;
  3859. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3860. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3861. break;
  3862. }
  3863. }
  3864. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3865. internalTexture._cachedWrapV = texture.wrapV;
  3866. switch (texture.wrapV) {
  3867. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3868. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3869. break;
  3870. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3871. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3872. break;
  3873. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3874. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3875. break;
  3876. }
  3877. }
  3878. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3879. }
  3880. };
  3881. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3882. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3883. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3884. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3885. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3886. }
  3887. };
  3888. Engine.prototype.readPixels = function (x, y, width, height) {
  3889. var data = new Uint8Array(height * width * 4);
  3890. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3891. return data;
  3892. };
  3893. Engine.prototype.dispose = function () {
  3894. this.hideLoadingUI();
  3895. this.stopRenderLoop();
  3896. while (this.scenes.length) {
  3897. this.scenes[0].dispose();
  3898. }
  3899. for (var name in this._compiledEffects) {
  3900. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3901. }
  3902. for (var i in this._vertexAttribArrays) {
  3903. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3904. continue;
  3905. }
  3906. this._gl.disableVertexAttribArray(i);
  3907. }
  3908. window.removeEventListener("blur", this._onBlur);
  3909. window.removeEventListener("focus", this._onFocus);
  3910. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3911. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3912. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3913. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3914. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3915. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3916. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3917. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3918. };
  3919. Engine.prototype.displayLoadingUI = function () {
  3920. var _this = this;
  3921. this._loadingDiv = document.createElement("div");
  3922. this._loadingDiv.style.opacity = "0";
  3923. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3924. this._loadingTextDiv = document.createElement("div");
  3925. this._loadingTextDiv.style.position = "absolute";
  3926. this._loadingTextDiv.style.left = "0";
  3927. this._loadingTextDiv.style.top = "50%";
  3928. this._loadingTextDiv.style.marginTop = "80px";
  3929. this._loadingTextDiv.style.width = "100%";
  3930. this._loadingTextDiv.style.height = "20px";
  3931. this._loadingTextDiv.style.fontFamily = "Arial";
  3932. this._loadingTextDiv.style.fontSize = "14px";
  3933. this._loadingTextDiv.style.color = "white";
  3934. this._loadingTextDiv.style.textAlign = "center";
  3935. this._loadingTextDiv.innerHTML = "Loading";
  3936. this._loadingDiv.appendChild(this._loadingTextDiv);
  3937. var imgBack = new Image();
  3938. 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==";
  3939. imgBack.style.position = "absolute";
  3940. imgBack.style.left = "50%";
  3941. imgBack.style.top = "50%";
  3942. imgBack.style.marginLeft = "-50px";
  3943. imgBack.style.marginTop = "-50px";
  3944. imgBack.style.transition = "transform 1.0s ease";
  3945. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3946. var deg = 360;
  3947. var onTransitionEnd = function () {
  3948. deg += 360;
  3949. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3950. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3951. };
  3952. imgBack.addEventListener("transitionend", onTransitionEnd);
  3953. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3954. this._loadingDiv.appendChild(imgBack);
  3955. var imgFront = new Image();
  3956. 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=";
  3957. imgFront.style.position = "absolute";
  3958. imgFront.style.left = "50%";
  3959. imgFront.style.top = "50%";
  3960. imgFront.style.marginLeft = "-50px";
  3961. imgFront.style.marginTop = "-50px";
  3962. this._loadingDiv.appendChild(imgFront);
  3963. this._resizeLoadingUI = function () {
  3964. var canvasRect = _this.getRenderingCanvasClientRect();
  3965. _this._loadingDiv.style.position = "absolute";
  3966. _this._loadingDiv.style.left = canvasRect.left + "px";
  3967. _this._loadingDiv.style.top = canvasRect.top + "px";
  3968. _this._loadingDiv.style.width = canvasRect.width + "px";
  3969. _this._loadingDiv.style.height = canvasRect.height + "px";
  3970. };
  3971. this._resizeLoadingUI();
  3972. window.addEventListener("resize", this._resizeLoadingUI);
  3973. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  3974. document.body.appendChild(this._loadingDiv);
  3975. setTimeout(function () {
  3976. _this._loadingDiv.style.opacity = "1";
  3977. imgBack.style.transform = "rotateZ(360deg)";
  3978. imgBack.style.webkitTransform = "rotateZ(360deg)";
  3979. }, 0);
  3980. };
  3981. Object.defineProperty(Engine.prototype, "loadingUIText", {
  3982. set: function (text) {
  3983. if (!this._loadingDiv) {
  3984. return;
  3985. }
  3986. this._loadingTextDiv.innerHTML = text;
  3987. },
  3988. enumerable: true,
  3989. configurable: true
  3990. });
  3991. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  3992. get: function () {
  3993. return this._loadingDivBackgroundColor;
  3994. },
  3995. set: function (color) {
  3996. this._loadingDivBackgroundColor = color;
  3997. if (!this._loadingDiv) {
  3998. return;
  3999. }
  4000. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4001. },
  4002. enumerable: true,
  4003. configurable: true
  4004. });
  4005. Engine.prototype.hideLoadingUI = function () {
  4006. var _this = this;
  4007. if (!this._loadingDiv) {
  4008. return;
  4009. }
  4010. var onTransitionEnd = function () {
  4011. if (!_this._loadingDiv) {
  4012. return;
  4013. }
  4014. document.body.removeChild(_this._loadingDiv);
  4015. window.removeEventListener("resize", _this._resizeLoadingUI);
  4016. _this._loadingDiv = null;
  4017. };
  4018. this._loadingDiv.style.opacity = "0";
  4019. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4020. };
  4021. Engine.isSupported = function () {
  4022. try {
  4023. if (navigator.isCocoonJS) {
  4024. return true;
  4025. }
  4026. var tempcanvas = document.createElement("canvas");
  4027. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4028. return gl != null && !!window.WebGLRenderingContext;
  4029. } catch (e) {
  4030. return false;
  4031. }
  4032. };
  4033. Engine._ALPHA_DISABLE = 0;
  4034. Engine._ALPHA_ADD = 1;
  4035. Engine._ALPHA_COMBINE = 2;
  4036. Engine._DELAYLOADSTATE_NONE = 0;
  4037. Engine._DELAYLOADSTATE_LOADED = 1;
  4038. Engine._DELAYLOADSTATE_LOADING = 2;
  4039. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4040. Engine.Epsilon = 0.001;
  4041. Engine.CollisionsEpsilon = 0.001;
  4042. Engine.ShadersRepository = "Babylon/Shaders/";
  4043. return Engine;
  4044. })();
  4045. BABYLON.Engine = Engine;
  4046. })(BABYLON || (BABYLON = {}));
  4047. var BABYLON;
  4048. (function (BABYLON) {
  4049. var Node = (function () {
  4050. function Node(name, scene) {
  4051. this.state = "";
  4052. this.animations = new Array();
  4053. this._childrenFlag = -1;
  4054. this._isEnabled = true;
  4055. this._isReady = true;
  4056. this._currentRenderId = -1;
  4057. this.name = name;
  4058. this.id = name;
  4059. this._scene = scene;
  4060. this._initCache();
  4061. }
  4062. Node.prototype.getScene = function () {
  4063. return this._scene;
  4064. };
  4065. Node.prototype.getEngine = function () {
  4066. return this._scene.getEngine();
  4067. };
  4068. Node.prototype.getWorldMatrix = function () {
  4069. return BABYLON.Matrix.Identity();
  4070. };
  4071. Node.prototype._initCache = function () {
  4072. this._cache = {};
  4073. this._cache.parent = undefined;
  4074. };
  4075. Node.prototype.updateCache = function (force) {
  4076. if (!force && this.isSynchronized())
  4077. return;
  4078. this._cache.parent = this.parent;
  4079. this._updateCache();
  4080. };
  4081. Node.prototype._updateCache = function (ignoreParentClass) {
  4082. };
  4083. Node.prototype._isSynchronized = function () {
  4084. return true;
  4085. };
  4086. Node.prototype.isSynchronizedWithParent = function () {
  4087. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4088. };
  4089. Node.prototype.isSynchronized = function (updateCache) {
  4090. var check = this.hasNewParent();
  4091. check = check || !this.isSynchronizedWithParent();
  4092. check = check || !this._isSynchronized();
  4093. if (updateCache)
  4094. this.updateCache(true);
  4095. return !check;
  4096. };
  4097. Node.prototype.hasNewParent = function (update) {
  4098. if (this._cache.parent === this.parent)
  4099. return false;
  4100. if (update)
  4101. this._cache.parent = this.parent;
  4102. return true;
  4103. };
  4104. Node.prototype.isReady = function () {
  4105. return this._isReady;
  4106. };
  4107. Node.prototype.isEnabled = function () {
  4108. if (!this._isEnabled) {
  4109. return false;
  4110. }
  4111. if (this.parent) {
  4112. return this.parent.isEnabled();
  4113. }
  4114. return true;
  4115. };
  4116. Node.prototype.setEnabled = function (value) {
  4117. this._isEnabled = value;
  4118. };
  4119. Node.prototype.isDescendantOf = function (ancestor) {
  4120. if (this.parent) {
  4121. if (this.parent === ancestor) {
  4122. return true;
  4123. }
  4124. return this.parent.isDescendantOf(ancestor);
  4125. }
  4126. return false;
  4127. };
  4128. Node.prototype._getDescendants = function (list, results) {
  4129. for (var index = 0; index < list.length; index++) {
  4130. var item = list[index];
  4131. if (item.isDescendantOf(this)) {
  4132. results.push(item);
  4133. }
  4134. }
  4135. };
  4136. Node.prototype.getDescendants = function () {
  4137. var results = [];
  4138. this._getDescendants(this._scene.meshes, results);
  4139. this._getDescendants(this._scene.lights, results);
  4140. this._getDescendants(this._scene.cameras, results);
  4141. return results;
  4142. };
  4143. Node.prototype._setReady = function (state) {
  4144. if (state == this._isReady) {
  4145. return;
  4146. }
  4147. if (!state) {
  4148. this._isReady = false;
  4149. return;
  4150. }
  4151. this._isReady = true;
  4152. if (this.onReady) {
  4153. this.onReady(this);
  4154. }
  4155. };
  4156. return Node;
  4157. })();
  4158. BABYLON.Node = Node;
  4159. })(BABYLON || (BABYLON = {}));
  4160. var BABYLON;
  4161. (function (BABYLON) {
  4162. var BoundingSphere = (function () {
  4163. function BoundingSphere(minimum, maximum) {
  4164. this.minimum = minimum;
  4165. this.maximum = maximum;
  4166. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4167. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4168. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4169. this.radius = distance * 0.5;
  4170. this.centerWorld = BABYLON.Vector3.Zero();
  4171. this._update(BABYLON.Matrix.Identity());
  4172. }
  4173. BoundingSphere.prototype._update = function (world) {
  4174. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4175. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4176. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4177. };
  4178. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4179. for (var i = 0; i < 6; i++) {
  4180. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4181. return false;
  4182. }
  4183. return true;
  4184. };
  4185. BoundingSphere.prototype.intersectsPoint = function (point) {
  4186. var x = this.centerWorld.x - point.x;
  4187. var y = this.centerWorld.y - point.y;
  4188. var z = this.centerWorld.z - point.z;
  4189. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4190. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4191. return false;
  4192. return true;
  4193. };
  4194. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4195. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4196. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4197. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4198. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4199. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4200. return false;
  4201. return true;
  4202. };
  4203. return BoundingSphere;
  4204. })();
  4205. BABYLON.BoundingSphere = BoundingSphere;
  4206. })(BABYLON || (BABYLON = {}));
  4207. var BABYLON;
  4208. (function (BABYLON) {
  4209. var BoundingBox = (function () {
  4210. function BoundingBox(minimum, maximum) {
  4211. this.minimum = minimum;
  4212. this.maximum = maximum;
  4213. this.vectors = new Array();
  4214. this.vectorsWorld = new Array();
  4215. this.vectors.push(this.minimum.clone());
  4216. this.vectors.push(this.maximum.clone());
  4217. this.vectors.push(this.minimum.clone());
  4218. this.vectors[2].x = this.maximum.x;
  4219. this.vectors.push(this.minimum.clone());
  4220. this.vectors[3].y = this.maximum.y;
  4221. this.vectors.push(this.minimum.clone());
  4222. this.vectors[4].z = this.maximum.z;
  4223. this.vectors.push(this.maximum.clone());
  4224. this.vectors[5].z = this.minimum.z;
  4225. this.vectors.push(this.maximum.clone());
  4226. this.vectors[6].x = this.minimum.x;
  4227. this.vectors.push(this.maximum.clone());
  4228. this.vectors[7].y = this.minimum.y;
  4229. this.center = this.maximum.add(this.minimum).scale(0.5);
  4230. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4231. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4232. for (var index = 0; index < this.vectors.length; index++) {
  4233. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4234. }
  4235. this.minimumWorld = BABYLON.Vector3.Zero();
  4236. this.maximumWorld = BABYLON.Vector3.Zero();
  4237. this._update(BABYLON.Matrix.Identity());
  4238. }
  4239. BoundingBox.prototype.getWorldMatrix = function () {
  4240. return this._worldMatrix;
  4241. };
  4242. BoundingBox.prototype._update = function (world) {
  4243. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4244. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4245. for (var index = 0; index < this.vectors.length; index++) {
  4246. var v = this.vectorsWorld[index];
  4247. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4248. if (v.x < this.minimumWorld.x)
  4249. this.minimumWorld.x = v.x;
  4250. if (v.y < this.minimumWorld.y)
  4251. this.minimumWorld.y = v.y;
  4252. if (v.z < this.minimumWorld.z)
  4253. this.minimumWorld.z = v.z;
  4254. if (v.x > this.maximumWorld.x)
  4255. this.maximumWorld.x = v.x;
  4256. if (v.y > this.maximumWorld.y)
  4257. this.maximumWorld.y = v.y;
  4258. if (v.z > this.maximumWorld.z)
  4259. this.maximumWorld.z = v.z;
  4260. }
  4261. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4262. this.center.scaleInPlace(0.5);
  4263. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4264. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4265. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4266. this._worldMatrix = world;
  4267. };
  4268. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4269. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4270. };
  4271. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4272. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4273. };
  4274. BoundingBox.prototype.intersectsPoint = function (point) {
  4275. var delta = BABYLON.Engine.Epsilon;
  4276. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4277. return false;
  4278. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4279. return false;
  4280. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4281. return false;
  4282. return true;
  4283. };
  4284. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4285. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4286. };
  4287. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4288. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4289. return false;
  4290. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4291. return false;
  4292. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4293. return false;
  4294. return true;
  4295. };
  4296. BoundingBox.Intersects = function (box0, box1) {
  4297. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4298. return false;
  4299. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4300. return false;
  4301. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4302. return false;
  4303. return true;
  4304. };
  4305. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4306. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4307. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4308. return (num <= (sphereRadius * sphereRadius));
  4309. };
  4310. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4311. for (var p = 0; p < 6; p++) {
  4312. for (var i = 0; i < 8; i++) {
  4313. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4314. return false;
  4315. }
  4316. }
  4317. }
  4318. return true;
  4319. };
  4320. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4321. for (var p = 0; p < 6; p++) {
  4322. var inCount = 8;
  4323. for (var i = 0; i < 8; i++) {
  4324. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4325. --inCount;
  4326. } else {
  4327. break;
  4328. }
  4329. }
  4330. if (inCount == 0)
  4331. return false;
  4332. }
  4333. return true;
  4334. };
  4335. return BoundingBox;
  4336. })();
  4337. BABYLON.BoundingBox = BoundingBox;
  4338. })(BABYLON || (BABYLON = {}));
  4339. var BABYLON;
  4340. (function (BABYLON) {
  4341. var computeBoxExtents = function (axis, box) {
  4342. var p = BABYLON.Vector3.Dot(box.center, axis);
  4343. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4344. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4345. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4346. var r = r0 + r1 + r2;
  4347. return {
  4348. min: p - r,
  4349. max: p + r
  4350. };
  4351. };
  4352. var extentsOverlap = function (min0, max0, min1, max1) {
  4353. return !(min0 > max1 || min1 > max0);
  4354. };
  4355. var axisOverlap = function (axis, box0, box1) {
  4356. var result0 = computeBoxExtents(axis, box0);
  4357. var result1 = computeBoxExtents(axis, box1);
  4358. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4359. };
  4360. var BoundingInfo = (function () {
  4361. function BoundingInfo(minimum, maximum) {
  4362. this.minimum = minimum;
  4363. this.maximum = maximum;
  4364. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4365. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4366. }
  4367. BoundingInfo.prototype._update = function (world) {
  4368. this.boundingBox._update(world);
  4369. this.boundingSphere._update(world);
  4370. };
  4371. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4372. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4373. return false;
  4374. return this.boundingBox.isInFrustum(frustumPlanes);
  4375. };
  4376. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4377. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4378. };
  4379. BoundingInfo.prototype._checkCollision = function (collider) {
  4380. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4381. };
  4382. BoundingInfo.prototype.intersectsPoint = function (point) {
  4383. if (!this.boundingSphere.centerWorld) {
  4384. return false;
  4385. }
  4386. if (!this.boundingSphere.intersectsPoint(point)) {
  4387. return false;
  4388. }
  4389. if (!this.boundingBox.intersectsPoint(point)) {
  4390. return false;
  4391. }
  4392. return true;
  4393. };
  4394. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4395. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4396. return false;
  4397. }
  4398. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4399. return false;
  4400. }
  4401. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4402. return false;
  4403. }
  4404. if (!precise) {
  4405. return true;
  4406. }
  4407. var box0 = this.boundingBox;
  4408. var box1 = boundingInfo.boundingBox;
  4409. if (!axisOverlap(box0.directions[0], box0, box1))
  4410. return false;
  4411. if (!axisOverlap(box0.directions[1], box0, box1))
  4412. return false;
  4413. if (!axisOverlap(box0.directions[2], box0, box1))
  4414. return false;
  4415. if (!axisOverlap(box1.directions[0], box0, box1))
  4416. return false;
  4417. if (!axisOverlap(box1.directions[1], box0, box1))
  4418. return false;
  4419. if (!axisOverlap(box1.directions[2], box0, box1))
  4420. return false;
  4421. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4422. return false;
  4423. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4424. return false;
  4425. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4426. return false;
  4427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4428. return false;
  4429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4430. return false;
  4431. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4432. return false;
  4433. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4434. return false;
  4435. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4436. return false;
  4437. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4438. return false;
  4439. return true;
  4440. };
  4441. return BoundingInfo;
  4442. })();
  4443. BABYLON.BoundingInfo = BoundingInfo;
  4444. })(BABYLON || (BABYLON = {}));
  4445. var __extends = this.__extends || function (d, b) {
  4446. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4447. function __() { this.constructor = d; }
  4448. __.prototype = b.prototype;
  4449. d.prototype = new __();
  4450. };
  4451. var BABYLON;
  4452. (function (BABYLON) {
  4453. var Light = (function (_super) {
  4454. __extends(Light, _super);
  4455. function Light(name, scene) {
  4456. _super.call(this, name, scene);
  4457. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4458. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4459. this.intensity = 1.0;
  4460. this.range = Number.MAX_VALUE;
  4461. this.includedOnlyMeshes = new Array();
  4462. this.excludedMeshes = new Array();
  4463. this._excludedMeshesIds = new Array();
  4464. this._includedOnlyMeshesIds = new Array();
  4465. scene.lights.push(this);
  4466. }
  4467. Light.prototype.getShadowGenerator = function () {
  4468. return this._shadowGenerator;
  4469. };
  4470. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4471. };
  4472. Light.prototype._getWorldMatrix = function () {
  4473. return BABYLON.Matrix.Identity();
  4474. };
  4475. Light.prototype.canAffectMesh = function (mesh) {
  4476. if (!mesh) {
  4477. return true;
  4478. }
  4479. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4480. return false;
  4481. }
  4482. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4483. return false;
  4484. }
  4485. return true;
  4486. };
  4487. Light.prototype.getWorldMatrix = function () {
  4488. this._currentRenderId = this.getScene().getRenderId();
  4489. var worldMatrix = this._getWorldMatrix();
  4490. if (this.parent && this.parent.getWorldMatrix) {
  4491. if (!this._parentedWorldMatrix) {
  4492. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4493. }
  4494. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4495. return this._parentedWorldMatrix;
  4496. }
  4497. return worldMatrix;
  4498. };
  4499. Light.prototype.dispose = function () {
  4500. if (this._shadowGenerator) {
  4501. this._shadowGenerator.dispose();
  4502. this._shadowGenerator = null;
  4503. }
  4504. var index = this.getScene().lights.indexOf(this);
  4505. this.getScene().lights.splice(index, 1);
  4506. };
  4507. return Light;
  4508. })(BABYLON.Node);
  4509. BABYLON.Light = Light;
  4510. })(BABYLON || (BABYLON = {}));
  4511. var __extends = this.__extends || function (d, b) {
  4512. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4513. function __() { this.constructor = d; }
  4514. __.prototype = b.prototype;
  4515. d.prototype = new __();
  4516. };
  4517. var BABYLON;
  4518. (function (BABYLON) {
  4519. var PointLight = (function (_super) {
  4520. __extends(PointLight, _super);
  4521. function PointLight(name, position, scene) {
  4522. _super.call(this, name, scene);
  4523. this.position = position;
  4524. }
  4525. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4526. if (this.parent && this.parent.getWorldMatrix) {
  4527. if (!this._transformedPosition) {
  4528. this._transformedPosition = BABYLON.Vector3.Zero();
  4529. }
  4530. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4531. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4532. return;
  4533. }
  4534. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4535. };
  4536. PointLight.prototype.getShadowGenerator = function () {
  4537. return null;
  4538. };
  4539. PointLight.prototype._getWorldMatrix = function () {
  4540. if (!this._worldMatrix) {
  4541. this._worldMatrix = BABYLON.Matrix.Identity();
  4542. }
  4543. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4544. return this._worldMatrix;
  4545. };
  4546. return PointLight;
  4547. })(BABYLON.Light);
  4548. BABYLON.PointLight = PointLight;
  4549. })(BABYLON || (BABYLON = {}));
  4550. var __extends = this.__extends || function (d, b) {
  4551. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4552. function __() { this.constructor = d; }
  4553. __.prototype = b.prototype;
  4554. d.prototype = new __();
  4555. };
  4556. var BABYLON;
  4557. (function (BABYLON) {
  4558. var SpotLight = (function (_super) {
  4559. __extends(SpotLight, _super);
  4560. function SpotLight(name, position, direction, angle, exponent, scene) {
  4561. _super.call(this, name, scene);
  4562. this.position = position;
  4563. this.direction = direction;
  4564. this.angle = angle;
  4565. this.exponent = exponent;
  4566. }
  4567. SpotLight.prototype.setDirectionToTarget = function (target) {
  4568. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4569. return this.direction;
  4570. };
  4571. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4572. var normalizeDirection;
  4573. if (this.parent && this.parent.getWorldMatrix) {
  4574. if (!this._transformedDirection) {
  4575. this._transformedDirection = BABYLON.Vector3.Zero();
  4576. }
  4577. if (!this._transformedPosition) {
  4578. this._transformedPosition = BABYLON.Vector3.Zero();
  4579. }
  4580. var parentWorldMatrix = this.parent.getWorldMatrix();
  4581. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4582. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4583. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4584. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4585. } else {
  4586. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4587. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4588. }
  4589. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4590. };
  4591. SpotLight.prototype._getWorldMatrix = function () {
  4592. if (!this._worldMatrix) {
  4593. this._worldMatrix = BABYLON.Matrix.Identity();
  4594. }
  4595. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4596. return this._worldMatrix;
  4597. };
  4598. return SpotLight;
  4599. })(BABYLON.Light);
  4600. BABYLON.SpotLight = SpotLight;
  4601. })(BABYLON || (BABYLON = {}));
  4602. var __extends = this.__extends || function (d, b) {
  4603. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4604. function __() { this.constructor = d; }
  4605. __.prototype = b.prototype;
  4606. d.prototype = new __();
  4607. };
  4608. var BABYLON;
  4609. (function (BABYLON) {
  4610. var DirectionalLight = (function (_super) {
  4611. __extends(DirectionalLight, _super);
  4612. function DirectionalLight(name, direction, scene) {
  4613. _super.call(this, name, scene);
  4614. this.direction = direction;
  4615. this.position = direction.scale(-1);
  4616. }
  4617. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4618. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4619. return this.direction;
  4620. };
  4621. DirectionalLight.prototype._computeTransformedPosition = function () {
  4622. if (this.parent && this.parent.getWorldMatrix) {
  4623. if (!this._transformedPosition) {
  4624. this._transformedPosition = BABYLON.Vector3.Zero();
  4625. }
  4626. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4627. return true;
  4628. }
  4629. return false;
  4630. };
  4631. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4632. if (this.parent && this.parent.getWorldMatrix) {
  4633. if (!this._transformedDirection) {
  4634. this._transformedDirection = BABYLON.Vector3.Zero();
  4635. }
  4636. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4637. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4638. return;
  4639. }
  4640. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4641. };
  4642. DirectionalLight.prototype._getWorldMatrix = function () {
  4643. if (!this._worldMatrix) {
  4644. this._worldMatrix = BABYLON.Matrix.Identity();
  4645. }
  4646. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4647. return this._worldMatrix;
  4648. };
  4649. return DirectionalLight;
  4650. })(BABYLON.Light);
  4651. BABYLON.DirectionalLight = DirectionalLight;
  4652. })(BABYLON || (BABYLON = {}));
  4653. var BABYLON;
  4654. (function (BABYLON) {
  4655. var ShadowGenerator = (function () {
  4656. function ShadowGenerator(mapSize, light) {
  4657. var _this = this;
  4658. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4659. this._darkness = 0;
  4660. this._transparencyShadow = false;
  4661. this._viewMatrix = BABYLON.Matrix.Zero();
  4662. this._projectionMatrix = BABYLON.Matrix.Zero();
  4663. this._transformMatrix = BABYLON.Matrix.Zero();
  4664. this._worldViewProjection = BABYLON.Matrix.Zero();
  4665. this._light = light;
  4666. this._scene = light.getScene();
  4667. light._shadowGenerator = this;
  4668. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4669. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4670. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4671. this._shadowMap.renderParticles = false;
  4672. var renderSubMesh = function (subMesh) {
  4673. var mesh = subMesh.getRenderingMesh();
  4674. var scene = _this._scene;
  4675. var engine = scene.getEngine();
  4676. engine.setState(subMesh.getMaterial().backFaceCulling);
  4677. var batch = mesh._getInstancesRenderList(subMesh._id);
  4678. if (batch.mustReturn) {
  4679. return;
  4680. }
  4681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4682. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4683. engine.enableEffect(_this._effect);
  4684. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4685. var material = subMesh.getMaterial();
  4686. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4687. if (material && material.needAlphaTesting()) {
  4688. var alphaTexture = material.getAlphaTestTexture();
  4689. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4690. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4691. }
  4692. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4693. if (useBones) {
  4694. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4695. }
  4696. if (hardwareInstancedRendering) {
  4697. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4698. } else {
  4699. if (batch.renderSelf[subMesh._id]) {
  4700. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4701. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4702. }
  4703. if (batch.visibleInstances[subMesh._id]) {
  4704. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4705. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4706. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4707. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4708. }
  4709. }
  4710. }
  4711. } else {
  4712. _this._shadowMap.resetRefreshCounter();
  4713. }
  4714. };
  4715. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4716. var index;
  4717. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4718. renderSubMesh(opaqueSubMeshes.data[index]);
  4719. }
  4720. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4721. renderSubMesh(alphaTestSubMeshes.data[index]);
  4722. }
  4723. if (_this._transparencyShadow) {
  4724. for (index = 0; index < transparentSubMeshes.length; index++) {
  4725. renderSubMesh(transparentSubMeshes.data[index]);
  4726. }
  4727. }
  4728. };
  4729. }
  4730. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4731. get: function () {
  4732. return ShadowGenerator._FILTER_NONE;
  4733. },
  4734. enumerable: true,
  4735. configurable: true
  4736. });
  4737. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4738. get: function () {
  4739. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4740. },
  4741. enumerable: true,
  4742. configurable: true
  4743. });
  4744. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4745. get: function () {
  4746. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4747. },
  4748. enumerable: true,
  4749. configurable: true
  4750. });
  4751. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4752. get: function () {
  4753. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4754. },
  4755. set: function (value) {
  4756. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4762. get: function () {
  4763. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4764. },
  4765. set: function (value) {
  4766. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4767. },
  4768. enumerable: true,
  4769. configurable: true
  4770. });
  4771. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4772. var defines = [];
  4773. if (this.useVarianceShadowMap) {
  4774. defines.push("#define VSM");
  4775. }
  4776. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4777. var mesh = subMesh.getMesh();
  4778. var material = subMesh.getMaterial();
  4779. if (material && material.needAlphaTesting()) {
  4780. defines.push("#define ALPHATEST");
  4781. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4782. attribs.push(BABYLON.VertexBuffer.UVKind);
  4783. defines.push("#define UV1");
  4784. }
  4785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4786. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4787. defines.push("#define UV2");
  4788. }
  4789. }
  4790. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4793. defines.push("#define BONES");
  4794. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4795. }
  4796. if (useInstances) {
  4797. defines.push("#define INSTANCES");
  4798. attribs.push("world0");
  4799. attribs.push("world1");
  4800. attribs.push("world2");
  4801. attribs.push("world3");
  4802. }
  4803. var join = defines.join("\n");
  4804. if (this._cachedDefines != join) {
  4805. this._cachedDefines = join;
  4806. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4807. }
  4808. return this._effect.isReady();
  4809. };
  4810. ShadowGenerator.prototype.getShadowMap = function () {
  4811. return this._shadowMap;
  4812. };
  4813. ShadowGenerator.prototype.getLight = function () {
  4814. return this._light;
  4815. };
  4816. ShadowGenerator.prototype.getTransformMatrix = function () {
  4817. var lightPosition = this._light.position;
  4818. var lightDirection = this._light.direction;
  4819. if (this._light._computeTransformedPosition()) {
  4820. lightPosition = this._light._transformedPosition;
  4821. }
  4822. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4823. this._cachedPosition = lightPosition.clone();
  4824. this._cachedDirection = lightDirection.clone();
  4825. var activeCamera = this._scene.activeCamera;
  4826. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4827. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4828. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4829. }
  4830. return this._transformMatrix;
  4831. };
  4832. ShadowGenerator.prototype.getDarkness = function () {
  4833. return this._darkness;
  4834. };
  4835. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4836. if (darkness >= 1.0)
  4837. this._darkness = 1.0;
  4838. else if (darkness <= 0.0)
  4839. this._darkness = 0.0;
  4840. else
  4841. this._darkness = darkness;
  4842. };
  4843. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4844. this._transparencyShadow = hasShadow;
  4845. };
  4846. ShadowGenerator.prototype.dispose = function () {
  4847. this._shadowMap.dispose();
  4848. };
  4849. ShadowGenerator._FILTER_NONE = 0;
  4850. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4851. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4852. return ShadowGenerator;
  4853. })();
  4854. BABYLON.ShadowGenerator = ShadowGenerator;
  4855. })(BABYLON || (BABYLON = {}));
  4856. var __extends = this.__extends || function (d, b) {
  4857. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4858. function __() { this.constructor = d; }
  4859. __.prototype = b.prototype;
  4860. d.prototype = new __();
  4861. };
  4862. var BABYLON;
  4863. (function (BABYLON) {
  4864. var HemisphericLight = (function (_super) {
  4865. __extends(HemisphericLight, _super);
  4866. function HemisphericLight(name, direction, scene) {
  4867. _super.call(this, name, scene);
  4868. this.direction = direction;
  4869. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4870. }
  4871. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4872. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4873. return this.direction;
  4874. };
  4875. HemisphericLight.prototype.getShadowGenerator = function () {
  4876. return null;
  4877. };
  4878. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4879. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4880. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4881. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4882. };
  4883. HemisphericLight.prototype._getWorldMatrix = function () {
  4884. if (!this._worldMatrix) {
  4885. this._worldMatrix = BABYLON.Matrix.Identity();
  4886. }
  4887. return this._worldMatrix;
  4888. };
  4889. return HemisphericLight;
  4890. })(BABYLON.Light);
  4891. BABYLON.HemisphericLight = HemisphericLight;
  4892. })(BABYLON || (BABYLON = {}));
  4893. var BABYLON;
  4894. (function (BABYLON) {
  4895. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4896. if (boxMin.x > sphereCenter.x + sphereRadius)
  4897. return false;
  4898. if (sphereCenter.x - sphereRadius > boxMax.x)
  4899. return false;
  4900. if (boxMin.y > sphereCenter.y + sphereRadius)
  4901. return false;
  4902. if (sphereCenter.y - sphereRadius > boxMax.y)
  4903. return false;
  4904. if (boxMin.z > sphereCenter.z + sphereRadius)
  4905. return false;
  4906. if (sphereCenter.z - sphereRadius > boxMax.z)
  4907. return false;
  4908. return true;
  4909. };
  4910. var getLowestRoot = function (a, b, c, maxR) {
  4911. var determinant = b * b - 4.0 * a * c;
  4912. var result = { root: 0, found: false };
  4913. if (determinant < 0)
  4914. return result;
  4915. var sqrtD = Math.sqrt(determinant);
  4916. var r1 = (-b - sqrtD) / (2.0 * a);
  4917. var r2 = (-b + sqrtD) / (2.0 * a);
  4918. if (r1 > r2) {
  4919. var temp = r2;
  4920. r2 = r1;
  4921. r1 = temp;
  4922. }
  4923. if (r1 > 0 && r1 < maxR) {
  4924. result.root = r1;
  4925. result.found = true;
  4926. return result;
  4927. }
  4928. if (r2 > 0 && r2 < maxR) {
  4929. result.root = r2;
  4930. result.found = true;
  4931. return result;
  4932. }
  4933. return result;
  4934. };
  4935. var Collider = (function () {
  4936. function Collider() {
  4937. this.radius = new BABYLON.Vector3(1, 1, 1);
  4938. this.retry = 0;
  4939. this.basePointWorld = BABYLON.Vector3.Zero();
  4940. this.velocityWorld = BABYLON.Vector3.Zero();
  4941. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4942. this._collisionPoint = BABYLON.Vector3.Zero();
  4943. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4944. this._tempVector = BABYLON.Vector3.Zero();
  4945. this._tempVector2 = BABYLON.Vector3.Zero();
  4946. this._tempVector3 = BABYLON.Vector3.Zero();
  4947. this._tempVector4 = BABYLON.Vector3.Zero();
  4948. this._edge = BABYLON.Vector3.Zero();
  4949. this._baseToVertex = BABYLON.Vector3.Zero();
  4950. this._destinationPoint = BABYLON.Vector3.Zero();
  4951. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4952. this._displacementVector = BABYLON.Vector3.Zero();
  4953. }
  4954. Collider.prototype._initialize = function (source, dir, e) {
  4955. this.velocity = dir;
  4956. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4957. this.basePoint = source;
  4958. source.multiplyToRef(this.radius, this.basePointWorld);
  4959. dir.multiplyToRef(this.radius, this.velocityWorld);
  4960. this.velocityWorldLength = this.velocityWorld.length();
  4961. this.epsilon = e;
  4962. this.collisionFound = false;
  4963. };
  4964. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  4965. pa.subtractToRef(point, this._tempVector);
  4966. pb.subtractToRef(point, this._tempVector2);
  4967. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  4968. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4969. if (d < 0)
  4970. return false;
  4971. pc.subtractToRef(point, this._tempVector3);
  4972. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  4973. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4974. if (d < 0)
  4975. return false;
  4976. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  4977. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  4978. return d >= 0;
  4979. };
  4980. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  4981. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  4982. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  4983. if (distance > this.velocityWorldLength + max + sphereRadius) {
  4984. return false;
  4985. }
  4986. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  4987. return false;
  4988. return true;
  4989. };
  4990. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  4991. var t0;
  4992. var embeddedInPlane = false;
  4993. if (!subMesh._trianglePlanes) {
  4994. subMesh._trianglePlanes = [];
  4995. }
  4996. if (!subMesh._trianglePlanes[faceIndex]) {
  4997. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  4998. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  4999. }
  5000. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5001. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5002. return;
  5003. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5004. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5005. if (normalDotVelocity == 0) {
  5006. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5007. return;
  5008. embeddedInPlane = true;
  5009. t0 = 0;
  5010. } else {
  5011. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5012. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5013. if (t0 > t1) {
  5014. var temp = t1;
  5015. t1 = t0;
  5016. t0 = temp;
  5017. }
  5018. if (t0 > 1.0 || t1 < 0.0)
  5019. return;
  5020. if (t0 < 0)
  5021. t0 = 0;
  5022. if (t0 > 1.0)
  5023. t0 = 1.0;
  5024. }
  5025. this._collisionPoint.copyFromFloats(0, 0, 0);
  5026. var found = false;
  5027. var t = 1.0;
  5028. if (!embeddedInPlane) {
  5029. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5030. this.velocity.scaleToRef(t0, this._tempVector);
  5031. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5032. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5033. found = true;
  5034. t = t0;
  5035. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5036. }
  5037. }
  5038. if (!found) {
  5039. var velocitySquaredLength = this.velocity.lengthSquared();
  5040. var a = velocitySquaredLength;
  5041. this.basePoint.subtractToRef(p1, this._tempVector);
  5042. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5043. var c = this._tempVector.lengthSquared() - 1.0;
  5044. var lowestRoot = getLowestRoot(a, b, c, t);
  5045. if (lowestRoot.found) {
  5046. t = lowestRoot.root;
  5047. found = true;
  5048. this._collisionPoint.copyFrom(p1);
  5049. }
  5050. this.basePoint.subtractToRef(p2, this._tempVector);
  5051. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5052. c = this._tempVector.lengthSquared() - 1.0;
  5053. lowestRoot = getLowestRoot(a, b, c, t);
  5054. if (lowestRoot.found) {
  5055. t = lowestRoot.root;
  5056. found = true;
  5057. this._collisionPoint.copyFrom(p2);
  5058. }
  5059. this.basePoint.subtractToRef(p3, this._tempVector);
  5060. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5061. c = this._tempVector.lengthSquared() - 1.0;
  5062. lowestRoot = getLowestRoot(a, b, c, t);
  5063. if (lowestRoot.found) {
  5064. t = lowestRoot.root;
  5065. found = true;
  5066. this._collisionPoint.copyFrom(p3);
  5067. }
  5068. p2.subtractToRef(p1, this._edge);
  5069. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5070. var edgeSquaredLength = this._edge.lengthSquared();
  5071. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5072. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5073. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5074. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5075. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5076. lowestRoot = getLowestRoot(a, b, c, t);
  5077. if (lowestRoot.found) {
  5078. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5079. if (f >= 0.0 && f <= 1.0) {
  5080. t = lowestRoot.root;
  5081. found = true;
  5082. this._edge.scaleInPlace(f);
  5083. p1.addToRef(this._edge, this._collisionPoint);
  5084. }
  5085. }
  5086. p3.subtractToRef(p2, this._edge);
  5087. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5088. edgeSquaredLength = this._edge.lengthSquared();
  5089. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5090. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5091. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5092. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5093. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5094. lowestRoot = getLowestRoot(a, b, c, t);
  5095. if (lowestRoot.found) {
  5096. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5097. if (f >= 0.0 && f <= 1.0) {
  5098. t = lowestRoot.root;
  5099. found = true;
  5100. this._edge.scaleInPlace(f);
  5101. p2.addToRef(this._edge, this._collisionPoint);
  5102. }
  5103. }
  5104. p1.subtractToRef(p3, this._edge);
  5105. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5106. edgeSquaredLength = this._edge.lengthSquared();
  5107. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5108. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5109. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5110. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5111. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5112. lowestRoot = getLowestRoot(a, b, c, t);
  5113. if (lowestRoot.found) {
  5114. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5115. if (f >= 0.0 && f <= 1.0) {
  5116. t = lowestRoot.root;
  5117. found = true;
  5118. this._edge.scaleInPlace(f);
  5119. p3.addToRef(this._edge, this._collisionPoint);
  5120. }
  5121. }
  5122. }
  5123. if (found) {
  5124. var distToCollision = t * this.velocity.length();
  5125. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5126. if (!this.intersectionPoint) {
  5127. this.intersectionPoint = this._collisionPoint.clone();
  5128. } else {
  5129. this.intersectionPoint.copyFrom(this._collisionPoint);
  5130. }
  5131. this.nearestDistance = distToCollision;
  5132. this.collisionFound = true;
  5133. this.collidedMesh = subMesh.getMesh();
  5134. }
  5135. }
  5136. };
  5137. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5138. for (var i = indexStart; i < indexEnd; i += 3) {
  5139. var p1 = pts[indices[i] - decal];
  5140. var p2 = pts[indices[i + 1] - decal];
  5141. var p3 = pts[indices[i + 2] - decal];
  5142. this._testTriangle(i, subMesh, p3, p2, p1);
  5143. }
  5144. };
  5145. Collider.prototype._getResponse = function (pos, vel) {
  5146. pos.addToRef(vel, this._destinationPoint);
  5147. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5148. this.basePoint.addToRef(vel, pos);
  5149. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5150. this._slidePlaneNormal.normalize();
  5151. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5152. pos.addInPlace(this._displacementVector);
  5153. this.intersectionPoint.addInPlace(this._displacementVector);
  5154. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5155. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5156. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5157. };
  5158. return Collider;
  5159. })();
  5160. BABYLON.Collider = Collider;
  5161. })(BABYLON || (BABYLON = {}));
  5162. var __extends = this.__extends || function (d, b) {
  5163. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5164. function __() { this.constructor = d; }
  5165. __.prototype = b.prototype;
  5166. d.prototype = new __();
  5167. };
  5168. var BABYLON;
  5169. (function (BABYLON) {
  5170. var Camera = (function (_super) {
  5171. __extends(Camera, _super);
  5172. function Camera(name, position, scene) {
  5173. _super.call(this, name, scene);
  5174. this.position = position;
  5175. this.upVector = BABYLON.Vector3.Up();
  5176. this.orthoLeft = null;
  5177. this.orthoRight = null;
  5178. this.orthoBottom = null;
  5179. this.orthoTop = null;
  5180. this.fov = 0.8;
  5181. this.minZ = 1.0;
  5182. this.maxZ = 10000.0;
  5183. this.inertia = 0.9;
  5184. this.mode = Camera.PERSPECTIVE_CAMERA;
  5185. this.isIntermediate = false;
  5186. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5187. this.subCameras = [];
  5188. this.layerMask = 0xFFFFFFFF;
  5189. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5190. this._projectionMatrix = new BABYLON.Matrix();
  5191. this._postProcesses = new Array();
  5192. this._postProcessesTakenIndices = [];
  5193. scene.cameras.push(this);
  5194. if (!scene.activeCamera) {
  5195. scene.activeCamera = this;
  5196. }
  5197. }
  5198. Camera.prototype._initCache = function () {
  5199. _super.prototype._initCache.call(this);
  5200. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5201. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5202. this._cache.mode = undefined;
  5203. this._cache.minZ = undefined;
  5204. this._cache.maxZ = undefined;
  5205. this._cache.fov = undefined;
  5206. this._cache.aspectRatio = undefined;
  5207. this._cache.orthoLeft = undefined;
  5208. this._cache.orthoRight = undefined;
  5209. this._cache.orthoBottom = undefined;
  5210. this._cache.orthoTop = undefined;
  5211. this._cache.renderWidth = undefined;
  5212. this._cache.renderHeight = undefined;
  5213. };
  5214. Camera.prototype._updateCache = function (ignoreParentClass) {
  5215. if (!ignoreParentClass) {
  5216. _super.prototype._updateCache.call(this);
  5217. }
  5218. var engine = this.getEngine();
  5219. this._cache.position.copyFrom(this.position);
  5220. this._cache.upVector.copyFrom(this.upVector);
  5221. this._cache.mode = this.mode;
  5222. this._cache.minZ = this.minZ;
  5223. this._cache.maxZ = this.maxZ;
  5224. this._cache.fov = this.fov;
  5225. this._cache.aspectRatio = engine.getAspectRatio(this);
  5226. this._cache.orthoLeft = this.orthoLeft;
  5227. this._cache.orthoRight = this.orthoRight;
  5228. this._cache.orthoBottom = this.orthoBottom;
  5229. this._cache.orthoTop = this.orthoTop;
  5230. this._cache.renderWidth = engine.getRenderWidth();
  5231. this._cache.renderHeight = engine.getRenderHeight();
  5232. };
  5233. Camera.prototype._updateFromScene = function () {
  5234. this.updateCache();
  5235. this._update();
  5236. };
  5237. Camera.prototype._isSynchronized = function () {
  5238. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5239. };
  5240. Camera.prototype._isSynchronizedViewMatrix = function () {
  5241. if (!_super.prototype._isSynchronized.call(this))
  5242. return false;
  5243. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5244. };
  5245. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5246. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5247. if (!check) {
  5248. return false;
  5249. }
  5250. var engine = this.getEngine();
  5251. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5252. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5253. } else {
  5254. 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();
  5255. }
  5256. return check;
  5257. };
  5258. Camera.prototype.attachControl = function (element) {
  5259. };
  5260. Camera.prototype.detachControl = function (element) {
  5261. };
  5262. Camera.prototype._update = function () {
  5263. };
  5264. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5265. if (typeof insertAt === "undefined") { insertAt = null; }
  5266. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5267. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5268. return 0;
  5269. }
  5270. if (insertAt == null || insertAt < 0) {
  5271. this._postProcesses.push(postProcess);
  5272. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5273. return this._postProcesses.length - 1;
  5274. }
  5275. var add = 0;
  5276. if (this._postProcesses[insertAt]) {
  5277. var start = this._postProcesses.length - 1;
  5278. for (var i = start; i >= insertAt + 1; --i) {
  5279. this._postProcesses[i + 1] = this._postProcesses[i];
  5280. }
  5281. add = 1;
  5282. }
  5283. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5284. if (this._postProcessesTakenIndices[i] < insertAt) {
  5285. continue;
  5286. }
  5287. start = this._postProcessesTakenIndices.length - 1;
  5288. for (var j = start; j >= i; --j) {
  5289. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5290. }
  5291. this._postProcessesTakenIndices[i] = insertAt;
  5292. break;
  5293. }
  5294. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5295. this._postProcessesTakenIndices.push(insertAt);
  5296. }
  5297. var result = insertAt + add;
  5298. this._postProcesses[result] = postProcess;
  5299. return result;
  5300. };
  5301. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5302. if (typeof atIndices === "undefined") { atIndices = null; }
  5303. var result = [];
  5304. if (!atIndices) {
  5305. var length = this._postProcesses.length;
  5306. for (var i = 0; i < length; i++) {
  5307. if (this._postProcesses[i] !== postProcess) {
  5308. continue;
  5309. }
  5310. delete this._postProcesses[i];
  5311. var index = this._postProcessesTakenIndices.indexOf(i);
  5312. this._postProcessesTakenIndices.splice(index, 1);
  5313. }
  5314. } else {
  5315. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5316. for (i = 0; i < atIndices.length; i++) {
  5317. var foundPostProcess = this._postProcesses[atIndices[i]];
  5318. if (foundPostProcess !== postProcess) {
  5319. result.push(i);
  5320. continue;
  5321. }
  5322. delete this._postProcesses[atIndices[i]];
  5323. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5324. this._postProcessesTakenIndices.splice(index, 1);
  5325. }
  5326. }
  5327. return result;
  5328. };
  5329. Camera.prototype.getWorldMatrix = function () {
  5330. if (!this._worldMatrix) {
  5331. this._worldMatrix = BABYLON.Matrix.Identity();
  5332. }
  5333. var viewMatrix = this.getViewMatrix();
  5334. viewMatrix.invertToRef(this._worldMatrix);
  5335. return this._worldMatrix;
  5336. };
  5337. Camera.prototype._getViewMatrix = function () {
  5338. return BABYLON.Matrix.Identity();
  5339. };
  5340. Camera.prototype.getViewMatrix = function () {
  5341. this._computedViewMatrix = this._computeViewMatrix();
  5342. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5343. return this._computedViewMatrix;
  5344. }
  5345. if (!this._worldMatrix) {
  5346. this._worldMatrix = BABYLON.Matrix.Identity();
  5347. }
  5348. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5349. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5350. this._computedViewMatrix.invert();
  5351. this._currentRenderId = this.getScene().getRenderId();
  5352. return this._computedViewMatrix;
  5353. };
  5354. Camera.prototype._computeViewMatrix = function (force) {
  5355. if (!force && this._isSynchronizedViewMatrix()) {
  5356. return this._computedViewMatrix;
  5357. }
  5358. this._computedViewMatrix = this._getViewMatrix();
  5359. if (!this.parent || !this.parent.getWorldMatrix) {
  5360. this._currentRenderId = this.getScene().getRenderId();
  5361. }
  5362. return this._computedViewMatrix;
  5363. };
  5364. Camera.prototype.getProjectionMatrix = function (force) {
  5365. if (!force && this._isSynchronizedProjectionMatrix()) {
  5366. return this._projectionMatrix;
  5367. }
  5368. var engine = this.getEngine();
  5369. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5370. if (this.minZ <= 0) {
  5371. this.minZ = 0.1;
  5372. }
  5373. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5374. return this._projectionMatrix;
  5375. }
  5376. var halfWidth = engine.getRenderWidth() / 2.0;
  5377. var halfHeight = engine.getRenderHeight() / 2.0;
  5378. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5379. return this._projectionMatrix;
  5380. };
  5381. Camera.prototype.dispose = function () {
  5382. var index = this.getScene().cameras.indexOf(this);
  5383. this.getScene().cameras.splice(index, 1);
  5384. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5385. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5386. }
  5387. };
  5388. Camera.PERSPECTIVE_CAMERA = 0;
  5389. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5390. return Camera;
  5391. })(BABYLON.Node);
  5392. BABYLON.Camera = Camera;
  5393. })(BABYLON || (BABYLON = {}));
  5394. var __extends = this.__extends || function (d, b) {
  5395. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5396. function __() { this.constructor = d; }
  5397. __.prototype = b.prototype;
  5398. d.prototype = new __();
  5399. };
  5400. var BABYLON;
  5401. (function (BABYLON) {
  5402. var TargetCamera = (function (_super) {
  5403. __extends(TargetCamera, _super);
  5404. function TargetCamera(name, position, scene) {
  5405. _super.call(this, name, position, scene);
  5406. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5407. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5408. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5409. this.speed = 2.0;
  5410. this.noRotationConstraint = false;
  5411. this.lockedTarget = null;
  5412. this._currentTarget = BABYLON.Vector3.Zero();
  5413. this._viewMatrix = BABYLON.Matrix.Zero();
  5414. this._camMatrix = BABYLON.Matrix.Zero();
  5415. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5416. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5417. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5418. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5419. this._lookAtTemp = BABYLON.Matrix.Zero();
  5420. this._tempMatrix = BABYLON.Matrix.Zero();
  5421. }
  5422. TargetCamera.prototype._getLockedTargetPosition = function () {
  5423. if (!this.lockedTarget) {
  5424. return null;
  5425. }
  5426. return this.lockedTarget.position || this.lockedTarget;
  5427. };
  5428. TargetCamera.prototype._initCache = function () {
  5429. _super.prototype._initCache.call(this);
  5430. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5431. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5432. };
  5433. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5434. if (!ignoreParentClass) {
  5435. _super.prototype._updateCache.call(this);
  5436. }
  5437. var lockedTargetPosition = this._getLockedTargetPosition();
  5438. if (!lockedTargetPosition) {
  5439. this._cache.lockedTarget = null;
  5440. } else {
  5441. if (!this._cache.lockedTarget) {
  5442. this._cache.lockedTarget = lockedTargetPosition.clone();
  5443. } else {
  5444. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5445. }
  5446. }
  5447. this._cache.rotation.copyFrom(this.rotation);
  5448. };
  5449. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5450. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5451. return false;
  5452. }
  5453. var lockedTargetPosition = this._getLockedTargetPosition();
  5454. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5455. };
  5456. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5457. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5458. };
  5459. TargetCamera.prototype.setTarget = function (target) {
  5460. this.upVector.normalize();
  5461. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5462. this._camMatrix.invert();
  5463. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5464. var vDir = target.subtract(this.position);
  5465. if (vDir.x >= 0.0) {
  5466. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5467. } else {
  5468. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5469. }
  5470. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5471. if (isNaN(this.rotation.x)) {
  5472. this.rotation.x = 0;
  5473. }
  5474. if (isNaN(this.rotation.y)) {
  5475. this.rotation.y = 0;
  5476. }
  5477. if (isNaN(this.rotation.z)) {
  5478. this.rotation.z = 0;
  5479. }
  5480. };
  5481. TargetCamera.prototype.getTarget = function () {
  5482. return this._currentTarget;
  5483. };
  5484. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5485. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5486. };
  5487. TargetCamera.prototype._updatePosition = function () {
  5488. this.position.addInPlace(this.cameraDirection);
  5489. };
  5490. TargetCamera.prototype._update = function () {
  5491. var needToMove = this._decideIfNeedsToMove();
  5492. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5493. if (needToMove) {
  5494. this._updatePosition();
  5495. }
  5496. if (needToRotate) {
  5497. this.rotation.x += this.cameraRotation.x;
  5498. this.rotation.y += this.cameraRotation.y;
  5499. if (!this.noRotationConstraint) {
  5500. var limit = (Math.PI / 2) * 0.95;
  5501. if (this.rotation.x > limit)
  5502. this.rotation.x = limit;
  5503. if (this.rotation.x < -limit)
  5504. this.rotation.x = -limit;
  5505. }
  5506. }
  5507. if (needToMove) {
  5508. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5509. this.cameraDirection.x = 0;
  5510. }
  5511. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5512. this.cameraDirection.y = 0;
  5513. }
  5514. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5515. this.cameraDirection.z = 0;
  5516. }
  5517. this.cameraDirection.scaleInPlace(this.inertia);
  5518. }
  5519. if (needToRotate) {
  5520. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5521. this.cameraRotation.x = 0;
  5522. }
  5523. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5524. this.cameraRotation.y = 0;
  5525. }
  5526. this.cameraRotation.scaleInPlace(this.inertia);
  5527. }
  5528. };
  5529. TargetCamera.prototype._getViewMatrix = function () {
  5530. if (!this.lockedTarget) {
  5531. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5532. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5533. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5534. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5535. this._lookAtTemp.invert();
  5536. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5537. } else {
  5538. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5539. }
  5540. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5541. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5542. } else {
  5543. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5544. }
  5545. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5546. return this._viewMatrix;
  5547. };
  5548. return TargetCamera;
  5549. })(BABYLON.Camera);
  5550. BABYLON.TargetCamera = TargetCamera;
  5551. })(BABYLON || (BABYLON = {}));
  5552. var __extends = this.__extends || function (d, b) {
  5553. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5554. function __() { this.constructor = d; }
  5555. __.prototype = b.prototype;
  5556. d.prototype = new __();
  5557. };
  5558. var BABYLON;
  5559. (function (BABYLON) {
  5560. var FollowCamera = (function (_super) {
  5561. __extends(FollowCamera, _super);
  5562. function FollowCamera(name, position, scene) {
  5563. _super.call(this, name, position, scene);
  5564. this.radius = 12;
  5565. this.rotationOffset = 0;
  5566. this.heightOffset = 4;
  5567. this.cameraAcceleration = 0.05;
  5568. this.maxCameraSpeed = 20;
  5569. }
  5570. FollowCamera.prototype.getRadians = function (degrees) {
  5571. return degrees * Math.PI / 180;
  5572. };
  5573. FollowCamera.prototype.follow = function (cameraTarget) {
  5574. if (!cameraTarget)
  5575. return;
  5576. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5577. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5578. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5579. var dx = targetX - this.position.x;
  5580. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5581. var dz = (targetZ) - this.position.z;
  5582. var vx = dx * this.cameraAcceleration * 2;
  5583. var vy = dy * this.cameraAcceleration;
  5584. var vz = dz * this.cameraAcceleration * 2;
  5585. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5586. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5587. }
  5588. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5589. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5590. }
  5591. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5592. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5593. }
  5594. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5595. this.setTarget(cameraTarget.position);
  5596. };
  5597. FollowCamera.prototype._update = function () {
  5598. _super.prototype._update.call(this);
  5599. this.follow(this.target);
  5600. };
  5601. return FollowCamera;
  5602. })(BABYLON.TargetCamera);
  5603. BABYLON.FollowCamera = FollowCamera;
  5604. })(BABYLON || (BABYLON = {}));
  5605. var __extends = this.__extends || function (d, b) {
  5606. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5607. function __() { this.constructor = d; }
  5608. __.prototype = b.prototype;
  5609. d.prototype = new __();
  5610. };
  5611. var BABYLON;
  5612. (function (BABYLON) {
  5613. var FreeCamera = (function (_super) {
  5614. __extends(FreeCamera, _super);
  5615. function FreeCamera(name, position, scene) {
  5616. _super.call(this, name, position, scene);
  5617. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5618. this.keysUp = [38];
  5619. this.keysDown = [40];
  5620. this.keysLeft = [37];
  5621. this.keysRight = [39];
  5622. this.checkCollisions = false;
  5623. this.applyGravity = false;
  5624. this.angularSensibility = 2000.0;
  5625. this._keys = [];
  5626. this._collider = new BABYLON.Collider();
  5627. this._needMoveForGravity = true;
  5628. this._oldPosition = BABYLON.Vector3.Zero();
  5629. this._diffPosition = BABYLON.Vector3.Zero();
  5630. this._newPosition = BABYLON.Vector3.Zero();
  5631. }
  5632. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5633. var _this = this;
  5634. var previousPosition;
  5635. var engine = this.getEngine();
  5636. if (this._attachedElement) {
  5637. return;
  5638. }
  5639. this._attachedElement = element;
  5640. if (this._onMouseDown === undefined) {
  5641. this._onMouseDown = function (evt) {
  5642. previousPosition = {
  5643. x: evt.clientX,
  5644. y: evt.clientY
  5645. };
  5646. if (!noPreventDefault) {
  5647. evt.preventDefault();
  5648. }
  5649. };
  5650. this._onMouseUp = function (evt) {
  5651. previousPosition = null;
  5652. if (!noPreventDefault) {
  5653. evt.preventDefault();
  5654. }
  5655. };
  5656. this._onMouseOut = function (evt) {
  5657. previousPosition = null;
  5658. _this._keys = [];
  5659. if (!noPreventDefault) {
  5660. evt.preventDefault();
  5661. }
  5662. };
  5663. this._onMouseMove = function (evt) {
  5664. if (!previousPosition && !engine.isPointerLock) {
  5665. return;
  5666. }
  5667. var offsetX;
  5668. var offsetY;
  5669. if (!engine.isPointerLock) {
  5670. offsetX = evt.clientX - previousPosition.x;
  5671. offsetY = evt.clientY - previousPosition.y;
  5672. } else {
  5673. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5674. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5675. }
  5676. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5677. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5678. previousPosition = {
  5679. x: evt.clientX,
  5680. y: evt.clientY
  5681. };
  5682. if (!noPreventDefault) {
  5683. evt.preventDefault();
  5684. }
  5685. };
  5686. this._onKeyDown = function (evt) {
  5687. 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) {
  5688. var index = _this._keys.indexOf(evt.keyCode);
  5689. if (index === -1) {
  5690. _this._keys.push(evt.keyCode);
  5691. }
  5692. if (!noPreventDefault) {
  5693. evt.preventDefault();
  5694. }
  5695. }
  5696. };
  5697. this._onKeyUp = function (evt) {
  5698. 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) {
  5699. var index = _this._keys.indexOf(evt.keyCode);
  5700. if (index >= 0) {
  5701. _this._keys.splice(index, 1);
  5702. }
  5703. if (!noPreventDefault) {
  5704. evt.preventDefault();
  5705. }
  5706. }
  5707. };
  5708. this._onLostFocus = function () {
  5709. _this._keys = [];
  5710. };
  5711. this._reset = function () {
  5712. _this._keys = [];
  5713. previousPosition = null;
  5714. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5715. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5716. };
  5717. }
  5718. element.addEventListener("mousedown", this._onMouseDown, false);
  5719. element.addEventListener("mouseup", this._onMouseUp, false);
  5720. element.addEventListener("mouseout", this._onMouseOut, false);
  5721. element.addEventListener("mousemove", this._onMouseMove, false);
  5722. BABYLON.Tools.RegisterTopRootEvents([
  5723. { name: "keydown", handler: this._onKeyDown },
  5724. { name: "keyup", handler: this._onKeyUp },
  5725. { name: "blur", handler: this._onLostFocus }
  5726. ]);
  5727. };
  5728. FreeCamera.prototype.detachControl = function (element) {
  5729. if (this._attachedElement != element) {
  5730. return;
  5731. }
  5732. element.removeEventListener("mousedown", this._onMouseDown);
  5733. element.removeEventListener("mouseup", this._onMouseUp);
  5734. element.removeEventListener("mouseout", this._onMouseOut);
  5735. element.removeEventListener("mousemove", this._onMouseMove);
  5736. BABYLON.Tools.UnregisterTopRootEvents([
  5737. { name: "keydown", handler: this._onKeyDown },
  5738. { name: "keyup", handler: this._onKeyUp },
  5739. { name: "blur", handler: this._onLostFocus }
  5740. ]);
  5741. this._attachedElement = null;
  5742. if (this._reset) {
  5743. this._reset();
  5744. }
  5745. };
  5746. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5747. var globalPosition;
  5748. if (this.parent) {
  5749. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5750. } else {
  5751. globalPosition = this.position;
  5752. }
  5753. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5754. this._collider.radius = this.ellipsoid;
  5755. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5756. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5757. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5758. this.position.addInPlace(this._diffPosition);
  5759. if (this.onCollide) {
  5760. this.onCollide(this._collider.collidedMesh);
  5761. }
  5762. }
  5763. };
  5764. FreeCamera.prototype._checkInputs = function () {
  5765. if (!this._localDirection) {
  5766. this._localDirection = BABYLON.Vector3.Zero();
  5767. this._transformedDirection = BABYLON.Vector3.Zero();
  5768. }
  5769. for (var index = 0; index < this._keys.length; index++) {
  5770. var keyCode = this._keys[index];
  5771. var speed = this._computeLocalCameraSpeed();
  5772. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5773. this._localDirection.copyFromFloats(-speed, 0, 0);
  5774. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5775. this._localDirection.copyFromFloats(0, 0, speed);
  5776. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5777. this._localDirection.copyFromFloats(speed, 0, 0);
  5778. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5779. this._localDirection.copyFromFloats(0, 0, -speed);
  5780. }
  5781. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5782. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5783. this.cameraDirection.addInPlace(this._transformedDirection);
  5784. }
  5785. };
  5786. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5787. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5788. };
  5789. FreeCamera.prototype._updatePosition = function () {
  5790. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5791. this._collideWithWorld(this.cameraDirection);
  5792. if (this.applyGravity) {
  5793. var oldPosition = this.position;
  5794. this._collideWithWorld(this.getScene().gravity);
  5795. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5796. }
  5797. } else {
  5798. this.position.addInPlace(this.cameraDirection);
  5799. }
  5800. };
  5801. FreeCamera.prototype._update = function () {
  5802. this._checkInputs();
  5803. _super.prototype._update.call(this);
  5804. };
  5805. return FreeCamera;
  5806. })(BABYLON.TargetCamera);
  5807. BABYLON.FreeCamera = FreeCamera;
  5808. })(BABYLON || (BABYLON = {}));
  5809. var __extends = this.__extends || function (d, b) {
  5810. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5811. function __() { this.constructor = d; }
  5812. __.prototype = b.prototype;
  5813. d.prototype = new __();
  5814. };
  5815. var BABYLON;
  5816. (function (BABYLON) {
  5817. var TouchCamera = (function (_super) {
  5818. __extends(TouchCamera, _super);
  5819. function TouchCamera(name, position, scene) {
  5820. _super.call(this, name, position, scene);
  5821. this._offsetX = null;
  5822. this._offsetY = null;
  5823. this._pointerCount = 0;
  5824. this._pointerPressed = [];
  5825. this.angularSensibility = 200000.0;
  5826. this.moveSensibility = 500.0;
  5827. }
  5828. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5829. var _this = this;
  5830. var previousPosition;
  5831. if (this._attachedCanvas) {
  5832. return;
  5833. }
  5834. this._attachedCanvas = canvas;
  5835. if (this._onPointerDown === undefined) {
  5836. this._onPointerDown = function (evt) {
  5837. if (!noPreventDefault) {
  5838. evt.preventDefault();
  5839. }
  5840. _this._pointerPressed.push(evt.pointerId);
  5841. if (_this._pointerPressed.length !== 1) {
  5842. return;
  5843. }
  5844. previousPosition = {
  5845. x: evt.clientX,
  5846. y: evt.clientY
  5847. };
  5848. };
  5849. this._onPointerUp = function (evt) {
  5850. if (!noPreventDefault) {
  5851. evt.preventDefault();
  5852. }
  5853. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5854. if (index === -1) {
  5855. return;
  5856. }
  5857. _this._pointerPressed.splice(index, 1);
  5858. if (index != 0) {
  5859. return;
  5860. }
  5861. previousPosition = null;
  5862. _this._offsetX = null;
  5863. _this._offsetY = null;
  5864. };
  5865. this._onPointerMove = function (evt) {
  5866. if (!noPreventDefault) {
  5867. evt.preventDefault();
  5868. }
  5869. if (!previousPosition) {
  5870. return;
  5871. }
  5872. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5873. if (index != 0) {
  5874. return;
  5875. }
  5876. _this._offsetX = evt.clientX - previousPosition.x;
  5877. _this._offsetY = -(evt.clientY - previousPosition.y);
  5878. };
  5879. this._onLostFocus = function () {
  5880. _this._offsetX = null;
  5881. _this._offsetY = null;
  5882. };
  5883. }
  5884. canvas.addEventListener("pointerdown", this._onPointerDown);
  5885. canvas.addEventListener("pointerup", this._onPointerUp);
  5886. canvas.addEventListener("pointerout", this._onPointerUp);
  5887. canvas.addEventListener("pointermove", this._onPointerMove);
  5888. BABYLON.Tools.RegisterTopRootEvents([
  5889. { name: "blur", handler: this._onLostFocus }
  5890. ]);
  5891. };
  5892. TouchCamera.prototype.detachControl = function (canvas) {
  5893. if (this._attachedCanvas != canvas) {
  5894. return;
  5895. }
  5896. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5897. canvas.removeEventListener("pointerup", this._onPointerUp);
  5898. canvas.removeEventListener("pointerout", this._onPointerUp);
  5899. canvas.removeEventListener("pointermove", this._onPointerMove);
  5900. BABYLON.Tools.UnregisterTopRootEvents([
  5901. { name: "blur", handler: this._onLostFocus }
  5902. ]);
  5903. this._attachedCanvas = null;
  5904. };
  5905. TouchCamera.prototype._checkInputs = function () {
  5906. if (!this._offsetX) {
  5907. return;
  5908. }
  5909. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5910. if (this._pointerPressed.length > 1) {
  5911. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5912. } else {
  5913. var speed = this._computeLocalCameraSpeed();
  5914. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5915. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5916. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5917. }
  5918. };
  5919. return TouchCamera;
  5920. })(BABYLON.FreeCamera);
  5921. BABYLON.TouchCamera = TouchCamera;
  5922. })(BABYLON || (BABYLON = {}));
  5923. var __extends = this.__extends || function (d, b) {
  5924. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5925. function __() { this.constructor = d; }
  5926. __.prototype = b.prototype;
  5927. d.prototype = new __();
  5928. };
  5929. var BABYLON;
  5930. (function (BABYLON) {
  5931. var DeviceOrientationCamera = (function (_super) {
  5932. __extends(DeviceOrientationCamera, _super);
  5933. function DeviceOrientationCamera(name, position, scene) {
  5934. var _this = this;
  5935. _super.call(this, name, position, scene);
  5936. this._offsetX = null;
  5937. this._offsetY = null;
  5938. this._orientationGamma = 0;
  5939. this._orientationBeta = 0;
  5940. this._initialOrientationGamma = 0;
  5941. this._initialOrientationBeta = 0;
  5942. this.angularSensibility = 10000.0;
  5943. this.moveSensibility = 50.0;
  5944. window.addEventListener("resize", function () {
  5945. _this._initialOrientationGamma = null;
  5946. }, false);
  5947. }
  5948. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5949. var _this = this;
  5950. if (this._attachedCanvas) {
  5951. return;
  5952. }
  5953. this._attachedCanvas = canvas;
  5954. if (!this._orientationChanged) {
  5955. this._orientationChanged = function (evt) {
  5956. if (!_this._initialOrientationGamma) {
  5957. _this._initialOrientationGamma = evt.gamma;
  5958. _this._initialOrientationBeta = evt.beta;
  5959. }
  5960. _this._orientationGamma = evt.gamma;
  5961. _this._orientationBeta = evt.beta;
  5962. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  5963. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  5964. };
  5965. }
  5966. window.addEventListener("deviceorientation", this._orientationChanged);
  5967. };
  5968. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  5969. if (this._attachedCanvas != canvas) {
  5970. return;
  5971. }
  5972. window.removeEventListener("deviceorientation", this._orientationChanged);
  5973. this._attachedCanvas = null;
  5974. this._orientationGamma = 0;
  5975. this._orientationBeta = 0;
  5976. this._initialOrientationGamma = 0;
  5977. this._initialOrientationBeta = 0;
  5978. };
  5979. DeviceOrientationCamera.prototype._checkInputs = function () {
  5980. if (!this._offsetX) {
  5981. return;
  5982. }
  5983. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  5984. var speed = this._computeLocalCameraSpeed();
  5985. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5986. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5987. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5988. };
  5989. return DeviceOrientationCamera;
  5990. })(BABYLON.FreeCamera);
  5991. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  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 eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6002. var ArcRotateCamera = (function (_super) {
  6003. __extends(ArcRotateCamera, _super);
  6004. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6005. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6006. this.alpha = alpha;
  6007. this.beta = beta;
  6008. this.radius = radius;
  6009. this.target = target;
  6010. this.inertialAlphaOffset = 0;
  6011. this.inertialBetaOffset = 0;
  6012. this.inertialRadiusOffset = 0;
  6013. this.lowerAlphaLimit = null;
  6014. this.upperAlphaLimit = null;
  6015. this.lowerBetaLimit = 0.01;
  6016. this.upperBetaLimit = Math.PI;
  6017. this.lowerRadiusLimit = null;
  6018. this.upperRadiusLimit = null;
  6019. this.angularSensibility = 1000.0;
  6020. this.wheelPrecision = 3.0;
  6021. this.keysUp = [38];
  6022. this.keysDown = [40];
  6023. this.keysLeft = [37];
  6024. this.keysRight = [39];
  6025. this.zoomOnFactor = 1;
  6026. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6027. this._keys = [];
  6028. this._viewMatrix = new BABYLON.Matrix();
  6029. this.checkCollisions = false;
  6030. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6031. this._collider = new BABYLON.Collider();
  6032. this._previousPosition = BABYLON.Vector3.Zero();
  6033. this._collisionVelocity = BABYLON.Vector3.Zero();
  6034. this._newPosition = BABYLON.Vector3.Zero();
  6035. this.pinchPrecision = 20;
  6036. this.getViewMatrix();
  6037. }
  6038. ArcRotateCamera.prototype._getTargetPosition = function () {
  6039. return this.target.position || this.target;
  6040. };
  6041. ArcRotateCamera.prototype._initCache = function () {
  6042. _super.prototype._initCache.call(this);
  6043. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6044. this._cache.alpha = undefined;
  6045. this._cache.beta = undefined;
  6046. this._cache.radius = undefined;
  6047. this._cache.targetScreenOffset = undefined;
  6048. };
  6049. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6050. if (!ignoreParentClass) {
  6051. _super.prototype._updateCache.call(this);
  6052. }
  6053. this._cache.target.copyFrom(this._getTargetPosition());
  6054. this._cache.alpha = this.alpha;
  6055. this._cache.beta = this.beta;
  6056. this._cache.radius = this.radius;
  6057. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6058. };
  6059. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6060. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6061. return false;
  6062. 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);
  6063. };
  6064. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6065. var _this = this;
  6066. var previousPosition;
  6067. var pointerId;
  6068. var pinchStarted = false;
  6069. var pinchPointX1, pinchPointX2;
  6070. if (this._attachedElement) {
  6071. return;
  6072. }
  6073. this._attachedElement = element;
  6074. var engine = this.getEngine();
  6075. if (this._onPointerDown === undefined) {
  6076. this._onPointerDown = function (evt) {
  6077. if (pointerId) {
  6078. return;
  6079. }
  6080. pointerId = evt.pointerId;
  6081. previousPosition = {
  6082. x: evt.clientX,
  6083. y: evt.clientY
  6084. };
  6085. if (!noPreventDefault) {
  6086. evt.preventDefault();
  6087. }
  6088. };
  6089. this._onPointerUp = function (evt) {
  6090. previousPosition = null;
  6091. pointerId = null;
  6092. if (!noPreventDefault) {
  6093. evt.preventDefault();
  6094. }
  6095. };
  6096. this._onPointerMove = function (evt) {
  6097. if (!previousPosition) {
  6098. return;
  6099. }
  6100. if (pointerId !== evt.pointerId) {
  6101. return;
  6102. }
  6103. if (pinchStarted) {
  6104. return;
  6105. }
  6106. var offsetX = evt.clientX - previousPosition.x;
  6107. var offsetY = evt.clientY - previousPosition.y;
  6108. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6109. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6110. previousPosition = {
  6111. x: evt.clientX,
  6112. y: evt.clientY
  6113. };
  6114. if (!noPreventDefault) {
  6115. evt.preventDefault();
  6116. }
  6117. };
  6118. this._onMouseMove = function (evt) {
  6119. if (!engine.isPointerLock) {
  6120. return;
  6121. }
  6122. if (pinchStarted) {
  6123. return;
  6124. }
  6125. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6126. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6127. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6128. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6129. if (!noPreventDefault) {
  6130. evt.preventDefault();
  6131. }
  6132. };
  6133. this._wheel = function (event) {
  6134. var delta = 0;
  6135. if (event.wheelDelta) {
  6136. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6137. } else if (event.detail) {
  6138. delta = -event.detail / _this.wheelPrecision;
  6139. }
  6140. if (delta)
  6141. _this.inertialRadiusOffset += delta;
  6142. if (event.preventDefault) {
  6143. if (!noPreventDefault) {
  6144. event.preventDefault();
  6145. }
  6146. }
  6147. };
  6148. this._onKeyDown = function (evt) {
  6149. 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) {
  6150. var index = _this._keys.indexOf(evt.keyCode);
  6151. if (index === -1) {
  6152. _this._keys.push(evt.keyCode);
  6153. }
  6154. if (evt.preventDefault) {
  6155. if (!noPreventDefault) {
  6156. evt.preventDefault();
  6157. }
  6158. }
  6159. }
  6160. };
  6161. this._onKeyUp = function (evt) {
  6162. 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) {
  6163. var index = _this._keys.indexOf(evt.keyCode);
  6164. if (index >= 0) {
  6165. _this._keys.splice(index, 1);
  6166. }
  6167. if (evt.preventDefault) {
  6168. if (!noPreventDefault) {
  6169. evt.preventDefault();
  6170. }
  6171. }
  6172. }
  6173. };
  6174. this._onLostFocus = function () {
  6175. _this._keys = [];
  6176. pointerId = null;
  6177. };
  6178. this._onGestureStart = function (e) {
  6179. if (window.MSGesture === undefined) {
  6180. return;
  6181. }
  6182. if (!_this._MSGestureHandler) {
  6183. _this._MSGestureHandler = new MSGesture();
  6184. _this._MSGestureHandler.target = element;
  6185. }
  6186. _this._MSGestureHandler.addPointer(e.pointerId);
  6187. };
  6188. this._onGesture = function (e) {
  6189. _this.radius *= e.scale;
  6190. if (e.preventDefault) {
  6191. if (!noPreventDefault) {
  6192. e.stopPropagation();
  6193. e.preventDefault();
  6194. }
  6195. }
  6196. };
  6197. this._reset = function () {
  6198. _this._keys = [];
  6199. _this.inertialAlphaOffset = 0;
  6200. _this.inertialBetaOffset = 0;
  6201. _this.inertialRadiusOffset = 0;
  6202. previousPosition = null;
  6203. pointerId = null;
  6204. };
  6205. this._touchStart = function (event) {
  6206. if (event.touches.length == 2) {
  6207. pinchStarted = true;
  6208. _this._pinchStart(event);
  6209. }
  6210. };
  6211. this._touchMove = function (event) {
  6212. if (pinchStarted) {
  6213. _this._pinchMove(event);
  6214. }
  6215. };
  6216. this._touchEnd = function (event) {
  6217. if (pinchStarted) {
  6218. _this._pinchEnd(event);
  6219. }
  6220. };
  6221. this._pinchStart = function (event) {
  6222. pinchPointX1 = event.touches[0].clientX;
  6223. pinchPointX2 = event.touches[1].clientX;
  6224. pinchStarted = true;
  6225. };
  6226. this._pinchMove = function (event) {
  6227. var delta = 0;
  6228. var direction = 1;
  6229. var distanceXOrigine, distanceXNow;
  6230. if (event.touches.length != 2)
  6231. return;
  6232. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6233. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6234. if (distanceXNow < distanceXOrigine) {
  6235. direction = -1;
  6236. }
  6237. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6238. _this.inertialRadiusOffset += delta;
  6239. pinchPointX1 = event.touches[0].clientX;
  6240. pinchPointX2 = event.touches[1].clientX;
  6241. };
  6242. this._pinchEnd = function (event) {
  6243. pinchStarted = false;
  6244. };
  6245. }
  6246. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6247. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6248. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6249. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6250. element.addEventListener("mousemove", this._onMouseMove, false);
  6251. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6252. element.addEventListener("MSGestureChange", this._onGesture, false);
  6253. element.addEventListener('mousewheel', this._wheel, false);
  6254. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6255. element.addEventListener('touchstart', this._touchStart, false);
  6256. element.addEventListener('touchmove', this._touchMove, false);
  6257. element.addEventListener('touchend', this._touchEnd, false);
  6258. BABYLON.Tools.RegisterTopRootEvents([
  6259. { name: "keydown", handler: this._onKeyDown },
  6260. { name: "keyup", handler: this._onKeyUp },
  6261. { name: "blur", handler: this._onLostFocus }
  6262. ]);
  6263. };
  6264. ArcRotateCamera.prototype.detachControl = function (element) {
  6265. if (this._attachedElement != element) {
  6266. return;
  6267. }
  6268. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6269. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6270. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6271. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6272. element.removeEventListener("mousemove", this._onMouseMove);
  6273. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6274. element.removeEventListener("MSGestureChange", this._onGesture);
  6275. element.removeEventListener('mousewheel', this._wheel);
  6276. element.removeEventListener('DOMMouseScroll', this._wheel);
  6277. element.removeEventListener('touchstart', this._touchStart);
  6278. element.removeEventListener('touchmove', this._touchMove);
  6279. element.removeEventListener('touchend', this._touchEnd);
  6280. BABYLON.Tools.UnregisterTopRootEvents([
  6281. { name: "keydown", handler: this._onKeyDown },
  6282. { name: "keyup", handler: this._onKeyUp },
  6283. { name: "blur", handler: this._onLostFocus }
  6284. ]);
  6285. this._MSGestureHandler = null;
  6286. this._attachedElement = null;
  6287. if (this._reset) {
  6288. this._reset();
  6289. }
  6290. };
  6291. ArcRotateCamera.prototype._update = function () {
  6292. for (var index = 0; index < this._keys.length; index++) {
  6293. var keyCode = this._keys[index];
  6294. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6295. this.inertialAlphaOffset -= 0.01;
  6296. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6297. this.inertialBetaOffset -= 0.01;
  6298. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6299. this.inertialAlphaOffset += 0.01;
  6300. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6301. this.inertialBetaOffset += 0.01;
  6302. }
  6303. }
  6304. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6305. this.alpha += this.inertialAlphaOffset;
  6306. this.beta += this.inertialBetaOffset;
  6307. this.radius -= this.inertialRadiusOffset;
  6308. this.inertialAlphaOffset *= this.inertia;
  6309. this.inertialBetaOffset *= this.inertia;
  6310. this.inertialRadiusOffset *= this.inertia;
  6311. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6312. this.inertialAlphaOffset = 0;
  6313. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6314. this.inertialBetaOffset = 0;
  6315. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6316. this.inertialRadiusOffset = 0;
  6317. }
  6318. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6319. this.alpha = this.lowerAlphaLimit;
  6320. }
  6321. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6322. this.alpha = this.upperAlphaLimit;
  6323. }
  6324. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6325. this.beta = this.lowerBetaLimit;
  6326. }
  6327. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6328. this.beta = this.upperBetaLimit;
  6329. }
  6330. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6331. this.radius = this.lowerRadiusLimit;
  6332. }
  6333. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6334. this.radius = this.upperRadiusLimit;
  6335. }
  6336. };
  6337. ArcRotateCamera.prototype.setPosition = function (position) {
  6338. var radiusv3 = position.subtract(this._getTargetPosition());
  6339. this.radius = radiusv3.length();
  6340. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6341. if (radiusv3.z < 0) {
  6342. this.alpha = 2 * Math.PI - this.alpha;
  6343. }
  6344. this.beta = Math.acos(radiusv3.y / this.radius);
  6345. };
  6346. ArcRotateCamera.prototype._getViewMatrix = function () {
  6347. var cosa = Math.cos(this.alpha);
  6348. var sina = Math.sin(this.alpha);
  6349. var cosb = Math.cos(this.beta);
  6350. var sinb = Math.sin(this.beta);
  6351. var target = this._getTargetPosition();
  6352. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6353. if (this.checkCollisions) {
  6354. this._collider.radius = this.collisionRadius;
  6355. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6356. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6357. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6358. this.position.copyFrom(this._previousPosition);
  6359. this.alpha = this._previousAlpha;
  6360. this.beta = this._previousBeta;
  6361. this.radius = this._previousRadius;
  6362. if (this.onCollide) {
  6363. this.onCollide(this._collider.collidedMesh);
  6364. }
  6365. }
  6366. }
  6367. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6368. this._previousAlpha = this.alpha;
  6369. this._previousBeta = this.beta;
  6370. this._previousRadius = this.radius;
  6371. this._previousPosition.copyFrom(this.position);
  6372. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6373. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6374. return this._viewMatrix;
  6375. };
  6376. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6377. meshes = meshes || this.getScene().meshes;
  6378. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6379. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6380. this.radius = distance * this.zoomOnFactor;
  6381. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6382. };
  6383. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6384. var meshesOrMinMaxVector;
  6385. var distance;
  6386. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6387. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6388. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6389. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6390. } else {
  6391. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6392. distance = meshesOrMinMaxVectorAndDistance.distance;
  6393. }
  6394. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6395. this.maxZ = distance * 2;
  6396. };
  6397. return ArcRotateCamera;
  6398. })(BABYLON.Camera);
  6399. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6400. })(BABYLON || (BABYLON = {}));
  6401. var BABYLON;
  6402. (function (BABYLON) {
  6403. var Scene = (function () {
  6404. function Scene(engine) {
  6405. this.autoClear = true;
  6406. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6407. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6408. this.forceWireframe = false;
  6409. this.cameraToUseForPointers = null;
  6410. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6411. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6412. this.fogDensity = 0.1;
  6413. this.fogStart = 0;
  6414. this.fogEnd = 1000.0;
  6415. this.shadowsEnabled = true;
  6416. this.lightsEnabled = true;
  6417. this.lights = new Array();
  6418. this.cameras = new Array();
  6419. this.activeCameras = new Array();
  6420. this.meshes = new Array();
  6421. this._geometries = new Array();
  6422. this.materials = new Array();
  6423. this.multiMaterials = new Array();
  6424. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6425. this.texturesEnabled = true;
  6426. this.textures = new Array();
  6427. this.particlesEnabled = true;
  6428. this.particleSystems = new Array();
  6429. this.spriteManagers = new Array();
  6430. this.layers = new Array();
  6431. this.skeletons = new Array();
  6432. this.lensFlaresEnabled = true;
  6433. this.lensFlareSystems = new Array();
  6434. this.collisionsEnabled = true;
  6435. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6436. this.postProcessesEnabled = true;
  6437. this.renderTargetsEnabled = true;
  6438. this.customRenderTargets = new Array();
  6439. this.importedMeshesFiles = new Array();
  6440. this._actionManagers = new Array();
  6441. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6442. this.proceduralTexturesEnabled = true;
  6443. this._proceduralTextures = new Array();
  6444. this._totalVertices = 0;
  6445. this._activeVertices = 0;
  6446. this._activeParticles = 0;
  6447. this._lastFrameDuration = 0;
  6448. this._evaluateActiveMeshesDuration = 0;
  6449. this._renderTargetsDuration = 0;
  6450. this._particlesDuration = 0;
  6451. this._renderDuration = 0;
  6452. this._spritesDuration = 0;
  6453. this._animationRatio = 0;
  6454. this._renderId = 0;
  6455. this._executeWhenReadyTimeoutId = -1;
  6456. this._toBeDisposed = new BABYLON.SmartArray(256);
  6457. this._onReadyCallbacks = new Array();
  6458. this._pendingData = [];
  6459. this._onBeforeRenderCallbacks = new Array();
  6460. this._activeMeshes = new BABYLON.SmartArray(256);
  6461. this._processedMaterials = new BABYLON.SmartArray(256);
  6462. this._renderTargets = new BABYLON.SmartArray(256);
  6463. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6464. this._activeSkeletons = new BABYLON.SmartArray(32);
  6465. this._activeAnimatables = new Array();
  6466. this._transformMatrix = BABYLON.Matrix.Zero();
  6467. this._scaledPosition = BABYLON.Vector3.Zero();
  6468. this._scaledVelocity = BABYLON.Vector3.Zero();
  6469. this._engine = engine;
  6470. engine.scenes.push(this);
  6471. this._renderingManager = new BABYLON.RenderingManager(this);
  6472. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6473. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6474. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6475. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6476. this.attachControl();
  6477. }
  6478. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6479. get: function () {
  6480. return this._meshUnderPointer;
  6481. },
  6482. enumerable: true,
  6483. configurable: true
  6484. });
  6485. Object.defineProperty(Scene.prototype, "pointerX", {
  6486. get: function () {
  6487. return this._pointerX;
  6488. },
  6489. enumerable: true,
  6490. configurable: true
  6491. });
  6492. Object.defineProperty(Scene.prototype, "pointerY", {
  6493. get: function () {
  6494. return this._pointerY;
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Scene.prototype.getBoundingBoxRenderer = function () {
  6500. return this._boundingBoxRenderer;
  6501. };
  6502. Scene.prototype.getOutlineRenderer = function () {
  6503. return this._outlineRenderer;
  6504. };
  6505. Scene.prototype.getEngine = function () {
  6506. return this._engine;
  6507. };
  6508. Scene.prototype.getTotalVertices = function () {
  6509. return this._totalVertices;
  6510. };
  6511. Scene.prototype.getActiveVertices = function () {
  6512. return this._activeVertices;
  6513. };
  6514. Scene.prototype.getActiveParticles = function () {
  6515. return this._activeParticles;
  6516. };
  6517. Scene.prototype.getLastFrameDuration = function () {
  6518. return this._lastFrameDuration;
  6519. };
  6520. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6521. return this._evaluateActiveMeshesDuration;
  6522. };
  6523. Scene.prototype.getActiveMeshes = function () {
  6524. return this._activeMeshes;
  6525. };
  6526. Scene.prototype.getRenderTargetsDuration = function () {
  6527. return this._renderTargetsDuration;
  6528. };
  6529. Scene.prototype.getRenderDuration = function () {
  6530. return this._renderDuration;
  6531. };
  6532. Scene.prototype.getParticlesDuration = function () {
  6533. return this._particlesDuration;
  6534. };
  6535. Scene.prototype.getSpritesDuration = function () {
  6536. return this._spritesDuration;
  6537. };
  6538. Scene.prototype.getAnimationRatio = function () {
  6539. return this._animationRatio;
  6540. };
  6541. Scene.prototype.getRenderId = function () {
  6542. return this._renderId;
  6543. };
  6544. Scene.prototype._updatePointerPosition = function (evt) {
  6545. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6546. this._pointerX = evt.clientX - canvasRect.left;
  6547. this._pointerY = evt.clientY - canvasRect.top;
  6548. if (this.cameraToUseForPointers) {
  6549. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6550. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6551. }
  6552. };
  6553. Scene.prototype.attachControl = function () {
  6554. var _this = this;
  6555. this._onPointerMove = function (evt) {
  6556. var canvas = _this._engine.getRenderingCanvas();
  6557. _this._updatePointerPosition(evt);
  6558. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6559. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6560. }, false, _this.cameraToUseForPointers);
  6561. if (pickResult.hit) {
  6562. _this._meshUnderPointer = pickResult.pickedMesh;
  6563. _this.setPointerOverMesh(pickResult.pickedMesh);
  6564. canvas.style.cursor = "pointer";
  6565. } else {
  6566. _this.setPointerOverMesh(null);
  6567. canvas.style.cursor = "";
  6568. _this._meshUnderPointer = null;
  6569. }
  6570. };
  6571. this._onPointerDown = function (evt) {
  6572. var predicate = null;
  6573. if (!_this.onPointerDown) {
  6574. predicate = function (mesh) {
  6575. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6576. };
  6577. }
  6578. _this._updatePointerPosition(evt);
  6579. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6580. if (pickResult.hit) {
  6581. if (pickResult.pickedMesh.actionManager) {
  6582. switch (evt.button) {
  6583. case 0:
  6584. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6585. break;
  6586. case 1:
  6587. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6588. break;
  6589. case 2:
  6590. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6591. break;
  6592. }
  6593. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6594. }
  6595. }
  6596. if (_this.onPointerDown) {
  6597. _this.onPointerDown(evt, pickResult);
  6598. }
  6599. };
  6600. this._onKeyDown = function (evt) {
  6601. if (_this.actionManager) {
  6602. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6603. }
  6604. };
  6605. this._onKeyUp = function (evt) {
  6606. if (_this.actionManager) {
  6607. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6608. }
  6609. };
  6610. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6611. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6612. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6613. window.addEventListener("keydown", this._onKeyDown, false);
  6614. window.addEventListener("keyup", this._onKeyUp, false);
  6615. };
  6616. Scene.prototype.detachControl = function () {
  6617. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6618. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6619. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6620. window.removeEventListener("keydown", this._onKeyDown);
  6621. window.removeEventListener("keyup", this._onKeyUp);
  6622. };
  6623. Scene.prototype.isReady = function () {
  6624. if (this._pendingData.length > 0) {
  6625. return false;
  6626. }
  6627. for (var index = 0; index < this._geometries.length; index++) {
  6628. var geometry = this._geometries[index];
  6629. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6630. return false;
  6631. }
  6632. }
  6633. for (index = 0; index < this.meshes.length; index++) {
  6634. var mesh = this.meshes[index];
  6635. if (!mesh.isReady()) {
  6636. return false;
  6637. }
  6638. var mat = mesh.material;
  6639. if (mat) {
  6640. if (!mat.isReady(mesh)) {
  6641. return false;
  6642. }
  6643. }
  6644. }
  6645. return true;
  6646. };
  6647. Scene.prototype.registerBeforeRender = function (func) {
  6648. this._onBeforeRenderCallbacks.push(func);
  6649. };
  6650. Scene.prototype.unregisterBeforeRender = function (func) {
  6651. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6652. if (index > -1) {
  6653. this._onBeforeRenderCallbacks.splice(index, 1);
  6654. }
  6655. };
  6656. Scene.prototype._addPendingData = function (data) {
  6657. this._pendingData.push(data);
  6658. };
  6659. Scene.prototype._removePendingData = function (data) {
  6660. var index = this._pendingData.indexOf(data);
  6661. if (index !== -1) {
  6662. this._pendingData.splice(index, 1);
  6663. }
  6664. };
  6665. Scene.prototype.getWaitingItemsCount = function () {
  6666. return this._pendingData.length;
  6667. };
  6668. Scene.prototype.executeWhenReady = function (func) {
  6669. var _this = this;
  6670. this._onReadyCallbacks.push(func);
  6671. if (this._executeWhenReadyTimeoutId !== -1) {
  6672. return;
  6673. }
  6674. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6675. _this._checkIsReady();
  6676. }, 150);
  6677. };
  6678. Scene.prototype._checkIsReady = function () {
  6679. var _this = this;
  6680. if (this.isReady()) {
  6681. this._onReadyCallbacks.forEach(function (func) {
  6682. func();
  6683. });
  6684. this._onReadyCallbacks = [];
  6685. this._executeWhenReadyTimeoutId = -1;
  6686. return;
  6687. }
  6688. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6689. _this._checkIsReady();
  6690. }, 150);
  6691. };
  6692. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6693. if (speedRatio === undefined) {
  6694. speedRatio = 1.0;
  6695. }
  6696. this.stopAnimation(target);
  6697. if (!animatable) {
  6698. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6699. }
  6700. if (target.animations) {
  6701. animatable.appendAnimations(target, target.animations);
  6702. }
  6703. if (target.getAnimatables) {
  6704. var animatables = target.getAnimatables();
  6705. for (var index = 0; index < animatables.length; index++) {
  6706. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6707. }
  6708. }
  6709. return animatable;
  6710. };
  6711. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6712. if (speedRatio === undefined) {
  6713. speedRatio = 1.0;
  6714. }
  6715. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6716. return animatable;
  6717. };
  6718. Scene.prototype.getAnimatableByTarget = function (target) {
  6719. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6720. if (this._activeAnimatables[index].target === target) {
  6721. return this._activeAnimatables[index];
  6722. }
  6723. }
  6724. return null;
  6725. };
  6726. Scene.prototype.stopAnimation = function (target) {
  6727. var animatable = this.getAnimatableByTarget(target);
  6728. if (animatable) {
  6729. animatable.stop();
  6730. }
  6731. };
  6732. Scene.prototype._animate = function () {
  6733. if (!this._animationStartDate) {
  6734. this._animationStartDate = BABYLON.Tools.Now;
  6735. }
  6736. var now = BABYLON.Tools.Now;
  6737. var delay = now - this._animationStartDate;
  6738. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6739. if (!this._activeAnimatables[index]._animate(delay)) {
  6740. this._activeAnimatables.splice(index, 1);
  6741. index--;
  6742. }
  6743. }
  6744. };
  6745. Scene.prototype.getViewMatrix = function () {
  6746. return this._viewMatrix;
  6747. };
  6748. Scene.prototype.getProjectionMatrix = function () {
  6749. return this._projectionMatrix;
  6750. };
  6751. Scene.prototype.getTransformMatrix = function () {
  6752. return this._transformMatrix;
  6753. };
  6754. Scene.prototype.setTransformMatrix = function (view, projection) {
  6755. this._viewMatrix = view;
  6756. this._projectionMatrix = projection;
  6757. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6758. };
  6759. Scene.prototype.setActiveCameraByID = function (id) {
  6760. var camera = this.getCameraByID(id);
  6761. if (camera) {
  6762. this.activeCamera = camera;
  6763. return camera;
  6764. }
  6765. return null;
  6766. };
  6767. Scene.prototype.setActiveCameraByName = function (name) {
  6768. var camera = this.getCameraByName(name);
  6769. if (camera) {
  6770. this.activeCamera = camera;
  6771. return camera;
  6772. }
  6773. return null;
  6774. };
  6775. Scene.prototype.getMaterialByID = function (id) {
  6776. for (var index = 0; index < this.materials.length; index++) {
  6777. if (this.materials[index].id === id) {
  6778. return this.materials[index];
  6779. }
  6780. }
  6781. return null;
  6782. };
  6783. Scene.prototype.getMaterialByName = function (name) {
  6784. for (var index = 0; index < this.materials.length; index++) {
  6785. if (this.materials[index].name === name) {
  6786. return this.materials[index];
  6787. }
  6788. }
  6789. return null;
  6790. };
  6791. Scene.prototype.getCameraByID = function (id) {
  6792. for (var index = 0; index < this.cameras.length; index++) {
  6793. if (this.cameras[index].id === id) {
  6794. return this.cameras[index];
  6795. }
  6796. }
  6797. return null;
  6798. };
  6799. Scene.prototype.getCameraByName = function (name) {
  6800. for (var index = 0; index < this.cameras.length; index++) {
  6801. if (this.cameras[index].name === name) {
  6802. return this.cameras[index];
  6803. }
  6804. }
  6805. return null;
  6806. };
  6807. Scene.prototype.getLightByName = function (name) {
  6808. for (var index = 0; index < this.lights.length; index++) {
  6809. if (this.lights[index].name === name) {
  6810. return this.lights[index];
  6811. }
  6812. }
  6813. return null;
  6814. };
  6815. Scene.prototype.getLightByID = function (id) {
  6816. for (var index = 0; index < this.lights.length; index++) {
  6817. if (this.lights[index].id === id) {
  6818. return this.lights[index];
  6819. }
  6820. }
  6821. return null;
  6822. };
  6823. Scene.prototype.getGeometryByID = function (id) {
  6824. for (var index = 0; index < this._geometries.length; index++) {
  6825. if (this._geometries[index].id === id) {
  6826. return this._geometries[index];
  6827. }
  6828. }
  6829. return null;
  6830. };
  6831. Scene.prototype.pushGeometry = function (geometry, force) {
  6832. if (!force && this.getGeometryByID(geometry.id)) {
  6833. return false;
  6834. }
  6835. this._geometries.push(geometry);
  6836. return true;
  6837. };
  6838. Scene.prototype.getGeometries = function () {
  6839. return this._geometries;
  6840. };
  6841. Scene.prototype.getMeshByID = function (id) {
  6842. for (var index = 0; index < this.meshes.length; index++) {
  6843. if (this.meshes[index].id === id) {
  6844. return this.meshes[index];
  6845. }
  6846. }
  6847. return null;
  6848. };
  6849. Scene.prototype.getLastMeshByID = function (id) {
  6850. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6851. if (this.meshes[index].id === id) {
  6852. return this.meshes[index];
  6853. }
  6854. }
  6855. return null;
  6856. };
  6857. Scene.prototype.getLastEntryByID = function (id) {
  6858. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6859. if (this.meshes[index].id === id) {
  6860. return this.meshes[index];
  6861. }
  6862. }
  6863. for (index = this.cameras.length - 1; index >= 0; index--) {
  6864. if (this.cameras[index].id === id) {
  6865. return this.cameras[index];
  6866. }
  6867. }
  6868. for (index = this.lights.length - 1; index >= 0; index--) {
  6869. if (this.lights[index].id === id) {
  6870. return this.lights[index];
  6871. }
  6872. }
  6873. return null;
  6874. };
  6875. Scene.prototype.getMeshByName = function (name) {
  6876. for (var index = 0; index < this.meshes.length; index++) {
  6877. if (this.meshes[index].name === name) {
  6878. return this.meshes[index];
  6879. }
  6880. }
  6881. return null;
  6882. };
  6883. Scene.prototype.getLastSkeletonByID = function (id) {
  6884. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6885. if (this.skeletons[index].id === id) {
  6886. return this.skeletons[index];
  6887. }
  6888. }
  6889. return null;
  6890. };
  6891. Scene.prototype.getSkeletonById = function (id) {
  6892. for (var index = 0; index < this.skeletons.length; index++) {
  6893. if (this.skeletons[index].id === id) {
  6894. return this.skeletons[index];
  6895. }
  6896. }
  6897. return null;
  6898. };
  6899. Scene.prototype.getSkeletonByName = function (name) {
  6900. for (var index = 0; index < this.skeletons.length; index++) {
  6901. if (this.skeletons[index].name === name) {
  6902. return this.skeletons[index];
  6903. }
  6904. }
  6905. return null;
  6906. };
  6907. Scene.prototype.isActiveMesh = function (mesh) {
  6908. return (this._activeMeshes.indexOf(mesh) !== -1);
  6909. };
  6910. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6911. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6912. var material = subMesh.getMaterial();
  6913. if (mesh.showSubMeshesBoundingBox) {
  6914. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6915. }
  6916. if (material) {
  6917. if (material.getRenderTargetTextures) {
  6918. if (this._processedMaterials.indexOf(material) === -1) {
  6919. this._processedMaterials.push(material);
  6920. this._renderTargets.concat(material.getRenderTargetTextures());
  6921. }
  6922. }
  6923. this._activeVertices += subMesh.verticesCount;
  6924. this._renderingManager.dispatch(subMesh);
  6925. }
  6926. }
  6927. };
  6928. Scene.prototype._evaluateActiveMeshes = function () {
  6929. this._activeMeshes.reset();
  6930. this._renderingManager.reset();
  6931. this._processedMaterials.reset();
  6932. this._activeParticleSystems.reset();
  6933. this._activeSkeletons.reset();
  6934. this._boundingBoxRenderer.reset();
  6935. if (!this._frustumPlanes) {
  6936. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6937. } else {
  6938. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6939. }
  6940. var meshes;
  6941. var len;
  6942. if (this._selectionOctree) {
  6943. var selection = this._selectionOctree.select(this._frustumPlanes);
  6944. meshes = selection.data;
  6945. len = selection.length;
  6946. } else {
  6947. len = this.meshes.length;
  6948. meshes = this.meshes;
  6949. }
  6950. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6951. var mesh = meshes[meshIndex];
  6952. if (mesh.isBlocked) {
  6953. continue;
  6954. }
  6955. this._totalVertices += mesh.getTotalVertices();
  6956. if (!mesh.isReady()) {
  6957. continue;
  6958. }
  6959. mesh.computeWorldMatrix();
  6960. mesh._preActivate();
  6961. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  6962. this._meshesForIntersections.pushNoDuplicate(mesh);
  6963. }
  6964. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  6965. this._activeMeshes.push(mesh);
  6966. mesh._activate(this._renderId);
  6967. this._activeMesh(mesh);
  6968. }
  6969. }
  6970. var beforeParticlesDate = BABYLON.Tools.Now;
  6971. if (this.particlesEnabled) {
  6972. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  6973. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  6974. var particleSystem = this.particleSystems[particleIndex];
  6975. if (!particleSystem.isStarted()) {
  6976. continue;
  6977. }
  6978. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  6979. this._activeParticleSystems.push(particleSystem);
  6980. particleSystem.animate();
  6981. }
  6982. }
  6983. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  6984. }
  6985. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  6986. };
  6987. Scene.prototype._activeMesh = function (mesh) {
  6988. if (mesh.skeleton) {
  6989. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  6990. }
  6991. if (mesh.showBoundingBox) {
  6992. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  6993. }
  6994. var activeMesh = mesh.getLOD(this.activeCamera);
  6995. if (activeMesh && activeMesh.subMeshes) {
  6996. var len;
  6997. var subMeshes;
  6998. if (activeMesh._submeshesOctree && activeMesh.useOctreeForRenderingSelection) {
  6999. var intersections = activeMesh._submeshesOctree.select(this._frustumPlanes);
  7000. len = intersections.length;
  7001. subMeshes = intersections.data;
  7002. } else {
  7003. subMeshes = activeMesh.subMeshes;
  7004. len = subMeshes.length;
  7005. }
  7006. for (var subIndex = 0; subIndex < len; subIndex++) {
  7007. var subMesh = subMeshes[subIndex];
  7008. this._evaluateSubMesh(subMesh, activeMesh);
  7009. }
  7010. }
  7011. };
  7012. Scene.prototype.updateTransformMatrix = function (force) {
  7013. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7014. };
  7015. Scene.prototype._renderForCamera = function (camera) {
  7016. var engine = this._engine;
  7017. this.activeCamera = camera;
  7018. if (!this.activeCamera)
  7019. throw new Error("Active camera not set");
  7020. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7021. engine.setViewport(this.activeCamera.viewport);
  7022. this._renderId++;
  7023. this.updateTransformMatrix();
  7024. if (this.beforeCameraRender) {
  7025. this.beforeCameraRender(this.activeCamera);
  7026. }
  7027. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7028. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7029. this._evaluateActiveMeshes();
  7030. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7031. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7032. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7033. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7034. skeleton.prepare();
  7035. }
  7036. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7037. if (this.renderTargetsEnabled) {
  7038. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7039. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7040. var renderTarget = this._renderTargets.data[renderIndex];
  7041. if (renderTarget._shouldRender()) {
  7042. this._renderId++;
  7043. renderTarget.render();
  7044. }
  7045. }
  7046. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7047. this._renderId++;
  7048. }
  7049. if (this._renderTargets.length > 0) {
  7050. engine.restoreDefaultFramebuffer();
  7051. }
  7052. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7053. this.postProcessManager._prepareFrame();
  7054. var beforeRenderDate = BABYLON.Tools.Now;
  7055. if (this.layers.length) {
  7056. engine.setDepthBuffer(false);
  7057. var layerIndex;
  7058. var layer;
  7059. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7060. layer = this.layers[layerIndex];
  7061. if (layer.isBackground) {
  7062. layer.render();
  7063. }
  7064. }
  7065. engine.setDepthBuffer(true);
  7066. }
  7067. BABYLON.Tools.StartPerformanceCounter("Main render");
  7068. this._renderingManager.render(null, null, true, true);
  7069. BABYLON.Tools.EndPerformanceCounter("Main render");
  7070. this._boundingBoxRenderer.render();
  7071. if (this.lensFlaresEnabled) {
  7072. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7073. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7074. this.lensFlareSystems[lensFlareSystemIndex].render();
  7075. }
  7076. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7077. }
  7078. if (this.layers.length) {
  7079. engine.setDepthBuffer(false);
  7080. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7081. layer = this.layers[layerIndex];
  7082. if (!layer.isBackground) {
  7083. layer.render();
  7084. }
  7085. }
  7086. engine.setDepthBuffer(true);
  7087. }
  7088. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7089. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7090. this.activeCamera._updateFromScene();
  7091. this._renderTargets.reset();
  7092. if (this.afterCameraRender) {
  7093. this.afterCameraRender(this.activeCamera);
  7094. }
  7095. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7096. };
  7097. Scene.prototype._processSubCameras = function (camera) {
  7098. if (camera.subCameras.length == 0) {
  7099. this._renderForCamera(camera);
  7100. return;
  7101. }
  7102. for (var index = 0; index < camera.subCameras.length; index++) {
  7103. this._renderForCamera(camera.subCameras[index]);
  7104. }
  7105. this.activeCamera = camera;
  7106. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7107. this.activeCamera._updateFromScene();
  7108. };
  7109. Scene.prototype._checkIntersections = function () {
  7110. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7111. var sourceMesh = this._meshesForIntersections.data[index];
  7112. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7113. var action = sourceMesh.actionManager.actions[actionIndex];
  7114. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7115. var otherMesh = action.getTriggerParameter();
  7116. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7117. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7118. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7119. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7120. sourceMesh._intersectionsInProgress.push(otherMesh);
  7121. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7122. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7123. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7124. if (indexOfOther > -1) {
  7125. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7126. }
  7127. }
  7128. }
  7129. }
  7130. }
  7131. };
  7132. Scene.prototype.render = function () {
  7133. var startDate = BABYLON.Tools.Now;
  7134. this._particlesDuration = 0;
  7135. this._spritesDuration = 0;
  7136. this._activeParticles = 0;
  7137. this._renderDuration = 0;
  7138. this._evaluateActiveMeshesDuration = 0;
  7139. this._totalVertices = 0;
  7140. this._activeVertices = 0;
  7141. this._meshesForIntersections.reset();
  7142. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7143. if (this.actionManager) {
  7144. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7145. }
  7146. if (this.beforeRender) {
  7147. this.beforeRender();
  7148. }
  7149. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7150. this._onBeforeRenderCallbacks[callbackIndex]();
  7151. }
  7152. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7153. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7154. this._animate();
  7155. if (this._physicsEngine) {
  7156. BABYLON.Tools.StartPerformanceCounter("Physics");
  7157. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7158. BABYLON.Tools.EndPerformanceCounter("Physics");
  7159. }
  7160. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7161. var engine = this.getEngine();
  7162. if (this.renderTargetsEnabled) {
  7163. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7164. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7165. var renderTarget = this.customRenderTargets[customIndex];
  7166. if (renderTarget._shouldRender()) {
  7167. this._renderId++;
  7168. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7169. if (!this.activeCamera)
  7170. throw new Error("Active camera not set");
  7171. engine.setViewport(this.activeCamera.viewport);
  7172. this.updateTransformMatrix();
  7173. renderTarget.render();
  7174. }
  7175. }
  7176. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7177. this._renderId++;
  7178. }
  7179. if (this.customRenderTargets.length > 0) {
  7180. engine.restoreDefaultFramebuffer();
  7181. }
  7182. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7183. if (this.proceduralTexturesEnabled) {
  7184. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7185. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7186. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7187. if (proceduralTexture._shouldRender()) {
  7188. proceduralTexture.render();
  7189. }
  7190. }
  7191. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7192. }
  7193. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7194. if (this.shadowsEnabled) {
  7195. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7196. var light = this.lights[lightIndex];
  7197. var shadowGenerator = light.getShadowGenerator();
  7198. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7199. this._renderTargets.push(shadowGenerator.getShadowMap());
  7200. }
  7201. }
  7202. }
  7203. this.postProcessRenderPipelineManager.update();
  7204. if (this.activeCameras.length > 0) {
  7205. var currentRenderId = this._renderId;
  7206. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7207. this._renderId = currentRenderId;
  7208. this._processSubCameras(this.activeCameras[cameraIndex]);
  7209. }
  7210. } else {
  7211. if (!this.activeCamera) {
  7212. throw new Error("No camera defined");
  7213. }
  7214. this._processSubCameras(this.activeCamera);
  7215. }
  7216. this._checkIntersections();
  7217. if (this.afterRender) {
  7218. this.afterRender();
  7219. }
  7220. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7221. this._toBeDisposed.data[index].dispose();
  7222. this._toBeDisposed[index] = null;
  7223. }
  7224. this._toBeDisposed.reset();
  7225. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7226. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7227. };
  7228. Scene.prototype.dispose = function () {
  7229. this.beforeRender = null;
  7230. this.afterRender = null;
  7231. this.skeletons = [];
  7232. this._boundingBoxRenderer.dispose();
  7233. if (this.onDispose) {
  7234. this.onDispose();
  7235. }
  7236. this.detachControl();
  7237. var canvas = this._engine.getRenderingCanvas();
  7238. var index;
  7239. for (index = 0; index < this.cameras.length; index++) {
  7240. this.cameras[index].detachControl(canvas);
  7241. }
  7242. while (this.lights.length) {
  7243. this.lights[0].dispose();
  7244. }
  7245. while (this.meshes.length) {
  7246. this.meshes[0].dispose(true);
  7247. }
  7248. while (this.cameras.length) {
  7249. this.cameras[0].dispose();
  7250. }
  7251. while (this.materials.length) {
  7252. this.materials[0].dispose();
  7253. }
  7254. while (this.particleSystems.length) {
  7255. this.particleSystems[0].dispose();
  7256. }
  7257. while (this.spriteManagers.length) {
  7258. this.spriteManagers[0].dispose();
  7259. }
  7260. while (this.layers.length) {
  7261. this.layers[0].dispose();
  7262. }
  7263. while (this.textures.length) {
  7264. this.textures[0].dispose();
  7265. }
  7266. this.postProcessManager.dispose();
  7267. if (this._physicsEngine) {
  7268. this.disablePhysicsEngine();
  7269. }
  7270. index = this._engine.scenes.indexOf(this);
  7271. if (index > -1) {
  7272. this._engine.scenes.splice(index, 1);
  7273. }
  7274. this._engine.wipeCaches();
  7275. };
  7276. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7277. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7278. position.divideToRef(collider.radius, this._scaledPosition);
  7279. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7280. collider.retry = 0;
  7281. collider.initialVelocity = this._scaledVelocity;
  7282. collider.initialPosition = this._scaledPosition;
  7283. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7284. finalPosition.multiplyInPlace(collider.radius);
  7285. };
  7286. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7287. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7288. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7289. if (collider.retry >= maximumRetry) {
  7290. finalPosition.copyFrom(position);
  7291. return;
  7292. }
  7293. collider._initialize(position, velocity, closeDistance);
  7294. for (var index = 0; index < this.meshes.length; index++) {
  7295. var mesh = this.meshes[index];
  7296. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7297. mesh._checkCollision(collider);
  7298. }
  7299. }
  7300. if (!collider.collisionFound) {
  7301. position.addToRef(velocity, finalPosition);
  7302. return;
  7303. }
  7304. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7305. collider._getResponse(position, velocity);
  7306. }
  7307. if (velocity.length() <= closeDistance) {
  7308. finalPosition.copyFrom(position);
  7309. return;
  7310. }
  7311. collider.retry++;
  7312. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7313. };
  7314. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7315. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7316. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7317. if (!this._selectionOctree) {
  7318. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7319. }
  7320. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7321. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7322. for (var index = 0; index < this.meshes.length; index++) {
  7323. var mesh = this.meshes[index];
  7324. mesh.computeWorldMatrix(true);
  7325. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7326. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7327. BABYLON.Tools.CheckExtends(minBox, min, max);
  7328. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7329. }
  7330. this._selectionOctree.update(min, max, this.meshes);
  7331. return this._selectionOctree;
  7332. };
  7333. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7334. var engine = this._engine;
  7335. if (!camera) {
  7336. if (!this.activeCamera)
  7337. throw new Error("Active camera not set");
  7338. camera = this.activeCamera;
  7339. }
  7340. var cameraViewport = camera.viewport;
  7341. var viewport = cameraViewport.toGlobal(engine);
  7342. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7343. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7344. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7345. };
  7346. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7347. var pickingInfo = null;
  7348. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7349. var mesh = this.meshes[meshIndex];
  7350. if (predicate) {
  7351. if (!predicate(mesh)) {
  7352. continue;
  7353. }
  7354. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7355. continue;
  7356. }
  7357. var world = mesh.getWorldMatrix();
  7358. var ray = rayFunction(world);
  7359. var result = mesh.intersects(ray, fastCheck);
  7360. if (!result || !result.hit)
  7361. continue;
  7362. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7363. continue;
  7364. pickingInfo = result;
  7365. if (fastCheck) {
  7366. break;
  7367. }
  7368. }
  7369. return pickingInfo || new BABYLON.PickingInfo();
  7370. };
  7371. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7372. var _this = this;
  7373. return this._internalPick(function (world) {
  7374. return _this.createPickingRay(x, y, world, camera);
  7375. }, predicate, fastCheck);
  7376. };
  7377. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7378. var _this = this;
  7379. return this._internalPick(function (world) {
  7380. if (!_this._pickWithRayInverseMatrix) {
  7381. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7382. }
  7383. world.invertToRef(_this._pickWithRayInverseMatrix);
  7384. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7385. }, predicate, fastCheck);
  7386. };
  7387. Scene.prototype.setPointerOverMesh = function (mesh) {
  7388. if (this._pointerOverMesh === mesh) {
  7389. return;
  7390. }
  7391. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7392. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7393. }
  7394. this._pointerOverMesh = mesh;
  7395. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7396. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7397. }
  7398. };
  7399. Scene.prototype.getPointerOverMesh = function () {
  7400. return this._pointerOverMesh;
  7401. };
  7402. Scene.prototype.getPhysicsEngine = function () {
  7403. return this._physicsEngine;
  7404. };
  7405. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7406. if (this._physicsEngine) {
  7407. return true;
  7408. }
  7409. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7410. if (!this._physicsEngine.isSupported()) {
  7411. this._physicsEngine = null;
  7412. return false;
  7413. }
  7414. this._physicsEngine._initialize(gravity);
  7415. return true;
  7416. };
  7417. Scene.prototype.disablePhysicsEngine = function () {
  7418. if (!this._physicsEngine) {
  7419. return;
  7420. }
  7421. this._physicsEngine.dispose();
  7422. this._physicsEngine = undefined;
  7423. };
  7424. Scene.prototype.isPhysicsEnabled = function () {
  7425. return this._physicsEngine !== undefined;
  7426. };
  7427. Scene.prototype.setGravity = function (gravity) {
  7428. if (!this._physicsEngine) {
  7429. return;
  7430. }
  7431. this._physicsEngine._setGravity(gravity);
  7432. };
  7433. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7434. if (parts.parts) {
  7435. options = parts;
  7436. parts = parts.parts;
  7437. }
  7438. if (!this._physicsEngine) {
  7439. return null;
  7440. }
  7441. for (var index = 0; index < parts.length; index++) {
  7442. var mesh = parts[index].mesh;
  7443. mesh._physicImpostor = parts[index].impostor;
  7444. mesh._physicsMass = options.mass / parts.length;
  7445. mesh._physicsFriction = options.friction;
  7446. mesh._physicRestitution = options.restitution;
  7447. }
  7448. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7449. };
  7450. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7451. for (var index = 0; index < compound.parts.length; index++) {
  7452. var mesh = compound.parts[index].mesh;
  7453. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7454. this._physicsEngine._unregisterMesh(mesh);
  7455. }
  7456. };
  7457. Scene.prototype._getByTags = function (list, tagsQuery) {
  7458. if (tagsQuery === undefined) {
  7459. return list;
  7460. }
  7461. var listByTags = [];
  7462. for (var i in list) {
  7463. var item = list[i];
  7464. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7465. listByTags.push(item);
  7466. }
  7467. }
  7468. return listByTags;
  7469. };
  7470. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7471. return this._getByTags(this.meshes, tagsQuery);
  7472. };
  7473. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7474. return this._getByTags(this.cameras, tagsQuery);
  7475. };
  7476. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7477. return this._getByTags(this.lights, tagsQuery);
  7478. };
  7479. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7480. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7481. };
  7482. Scene.FOGMODE_NONE = 0;
  7483. Scene.FOGMODE_EXP = 1;
  7484. Scene.FOGMODE_EXP2 = 2;
  7485. Scene.FOGMODE_LINEAR = 3;
  7486. Scene.MinDeltaTime = 1.0;
  7487. Scene.MaxDeltaTime = 1000.0;
  7488. return Scene;
  7489. })();
  7490. BABYLON.Scene = Scene;
  7491. })(BABYLON || (BABYLON = {}));
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var VertexBuffer = (function () {
  7495. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation) {
  7496. if (engine instanceof BABYLON.Mesh) {
  7497. this._engine = engine.getScene().getEngine();
  7498. } else {
  7499. this._engine = engine;
  7500. }
  7501. this._updatable = updatable;
  7502. this._data = data;
  7503. if (!postponeInternalCreation) {
  7504. this.create();
  7505. }
  7506. this._kind = kind;
  7507. switch (kind) {
  7508. case VertexBuffer.PositionKind:
  7509. this._strideSize = 3;
  7510. break;
  7511. case VertexBuffer.NormalKind:
  7512. this._strideSize = 3;
  7513. break;
  7514. case VertexBuffer.UVKind:
  7515. this._strideSize = 2;
  7516. break;
  7517. case VertexBuffer.UV2Kind:
  7518. this._strideSize = 2;
  7519. break;
  7520. case VertexBuffer.ColorKind:
  7521. this._strideSize = 3;
  7522. break;
  7523. case VertexBuffer.MatricesIndicesKind:
  7524. this._strideSize = 4;
  7525. break;
  7526. case VertexBuffer.MatricesWeightsKind:
  7527. this._strideSize = 4;
  7528. break;
  7529. }
  7530. }
  7531. VertexBuffer.prototype.isUpdatable = function () {
  7532. return this._updatable;
  7533. };
  7534. VertexBuffer.prototype.getData = function () {
  7535. return this._data;
  7536. };
  7537. VertexBuffer.prototype.getBuffer = function () {
  7538. return this._buffer;
  7539. };
  7540. VertexBuffer.prototype.getStrideSize = function () {
  7541. return this._strideSize;
  7542. };
  7543. VertexBuffer.prototype.create = function (data) {
  7544. if (!data && this._buffer) {
  7545. return;
  7546. }
  7547. data = data || this._data;
  7548. if (!this._buffer) {
  7549. if (this._updatable) {
  7550. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7551. } else {
  7552. this._buffer = this._engine.createVertexBuffer(data);
  7553. }
  7554. }
  7555. if (this._updatable) {
  7556. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7557. this._data = data;
  7558. }
  7559. };
  7560. VertexBuffer.prototype.update = function (data) {
  7561. this.create(data);
  7562. };
  7563. VertexBuffer.prototype.updateDirectly = function (data) {
  7564. if (!this._buffer) {
  7565. return;
  7566. }
  7567. if (this._updatable) {
  7568. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7569. this._data = null;
  7570. }
  7571. };
  7572. VertexBuffer.prototype.dispose = function () {
  7573. if (!this._buffer) {
  7574. return;
  7575. }
  7576. if (this._engine._releaseBuffer(this._buffer)) {
  7577. this._buffer = null;
  7578. }
  7579. };
  7580. Object.defineProperty(VertexBuffer, "PositionKind", {
  7581. get: function () {
  7582. return VertexBuffer._PositionKind;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(VertexBuffer, "NormalKind", {
  7588. get: function () {
  7589. return VertexBuffer._NormalKind;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(VertexBuffer, "UVKind", {
  7595. get: function () {
  7596. return VertexBuffer._UVKind;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7602. get: function () {
  7603. return VertexBuffer._UV2Kind;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(VertexBuffer, "ColorKind", {
  7609. get: function () {
  7610. return VertexBuffer._ColorKind;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7616. get: function () {
  7617. return VertexBuffer._MatricesIndicesKind;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7623. get: function () {
  7624. return VertexBuffer._MatricesWeightsKind;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. VertexBuffer._PositionKind = "position";
  7630. VertexBuffer._NormalKind = "normal";
  7631. VertexBuffer._UVKind = "uv";
  7632. VertexBuffer._UV2Kind = "uv2";
  7633. VertexBuffer._ColorKind = "color";
  7634. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7635. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7636. return VertexBuffer;
  7637. })();
  7638. BABYLON.VertexBuffer = VertexBuffer;
  7639. })(BABYLON || (BABYLON = {}));
  7640. var __extends = this.__extends || function (d, b) {
  7641. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7642. function __() { this.constructor = d; }
  7643. __.prototype = b.prototype;
  7644. d.prototype = new __();
  7645. };
  7646. var BABYLON;
  7647. (function (BABYLON) {
  7648. var AbstractMesh = (function (_super) {
  7649. __extends(AbstractMesh, _super);
  7650. function AbstractMesh(name, scene) {
  7651. _super.call(this, name, scene);
  7652. this.position = new BABYLON.Vector3(0, 0, 0);
  7653. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7654. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7655. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7656. this.visibility = 1.0;
  7657. this.infiniteDistance = false;
  7658. this.isVisible = true;
  7659. this.isPickable = true;
  7660. this.showBoundingBox = false;
  7661. this.showSubMeshesBoundingBox = false;
  7662. this.onDispose = null;
  7663. this.checkCollisions = false;
  7664. this.isBlocker = false;
  7665. this.renderingGroupId = 0;
  7666. this.receiveShadows = false;
  7667. this.renderOutline = false;
  7668. this.outlineColor = BABYLON.Color3.Red();
  7669. this.outlineWidth = 0.02;
  7670. this.useOctreeForRenderingSelection = true;
  7671. this.useOctreeForPicking = true;
  7672. this.useOctreeForCollisions = true;
  7673. this.layerMask = 0xFFFFFFFF;
  7674. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7675. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7676. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7677. this._collider = new BABYLON.Collider();
  7678. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7679. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7680. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7681. this._localScaling = BABYLON.Matrix.Zero();
  7682. this._localRotation = BABYLON.Matrix.Zero();
  7683. this._localTranslation = BABYLON.Matrix.Zero();
  7684. this._localBillboard = BABYLON.Matrix.Zero();
  7685. this._localPivotScaling = BABYLON.Matrix.Zero();
  7686. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7687. this._localWorld = BABYLON.Matrix.Zero();
  7688. this._worldMatrix = BABYLON.Matrix.Zero();
  7689. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7690. this._absolutePosition = BABYLON.Vector3.Zero();
  7691. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7692. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7693. this._isDirty = false;
  7694. this._pivotMatrix = BABYLON.Matrix.Identity();
  7695. this._isDisposed = false;
  7696. this._renderId = 0;
  7697. this._intersectionsInProgress = new Array();
  7698. scene.meshes.push(this);
  7699. }
  7700. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7701. get: function () {
  7702. return AbstractMesh._BILLBOARDMODE_NONE;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7708. get: function () {
  7709. return AbstractMesh._BILLBOARDMODE_X;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7715. get: function () {
  7716. return AbstractMesh._BILLBOARDMODE_Y;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7722. get: function () {
  7723. return AbstractMesh._BILLBOARDMODE_Z;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7729. get: function () {
  7730. return AbstractMesh._BILLBOARDMODE_ALL;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7736. get: function () {
  7737. return false;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. AbstractMesh.prototype.getLOD = function (camera) {
  7743. return this;
  7744. };
  7745. AbstractMesh.prototype.getTotalVertices = function () {
  7746. return 0;
  7747. };
  7748. AbstractMesh.prototype.getIndices = function () {
  7749. return null;
  7750. };
  7751. AbstractMesh.prototype.getVerticesData = function (kind) {
  7752. return null;
  7753. };
  7754. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7755. return false;
  7756. };
  7757. AbstractMesh.prototype.getBoundingInfo = function () {
  7758. if (!this._boundingInfo) {
  7759. this._updateBoundingInfo();
  7760. }
  7761. return this._boundingInfo;
  7762. };
  7763. AbstractMesh.prototype._preActivate = function () {
  7764. };
  7765. AbstractMesh.prototype._activate = function (renderId) {
  7766. this._renderId = renderId;
  7767. };
  7768. AbstractMesh.prototype.getWorldMatrix = function () {
  7769. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7770. this.computeWorldMatrix();
  7771. }
  7772. return this._worldMatrix;
  7773. };
  7774. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7775. get: function () {
  7776. return this._worldMatrix;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7782. get: function () {
  7783. return this._absolutePosition;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7789. if (!this.rotationQuaternion) {
  7790. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7791. this.rotation = BABYLON.Vector3.Zero();
  7792. }
  7793. if (!space || space == 0 /* LOCAL */) {
  7794. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7795. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7796. } else {
  7797. if (this.parent) {
  7798. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7799. invertParentWorldMatrix.invert();
  7800. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7801. }
  7802. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7803. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7804. }
  7805. };
  7806. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7807. var displacementVector = axis.scale(distance);
  7808. if (!space || space == 0 /* LOCAL */) {
  7809. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7810. this.setPositionWithLocalVector(tempV3);
  7811. } else {
  7812. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7813. }
  7814. };
  7815. AbstractMesh.prototype.getAbsolutePosition = function () {
  7816. this.computeWorldMatrix();
  7817. return this._absolutePosition;
  7818. };
  7819. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7820. if (!absolutePosition) {
  7821. return;
  7822. }
  7823. var absolutePositionX;
  7824. var absolutePositionY;
  7825. var absolutePositionZ;
  7826. if (absolutePosition.x === undefined) {
  7827. if (arguments.length < 3) {
  7828. return;
  7829. }
  7830. absolutePositionX = arguments[0];
  7831. absolutePositionY = arguments[1];
  7832. absolutePositionZ = arguments[2];
  7833. } else {
  7834. absolutePositionX = absolutePosition.x;
  7835. absolutePositionY = absolutePosition.y;
  7836. absolutePositionZ = absolutePosition.z;
  7837. }
  7838. if (this.parent) {
  7839. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7840. invertParentWorldMatrix.invert();
  7841. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7842. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7843. } else {
  7844. this.position.x = absolutePositionX;
  7845. this.position.y = absolutePositionY;
  7846. this.position.z = absolutePositionZ;
  7847. }
  7848. };
  7849. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7850. this._pivotMatrix = matrix;
  7851. this._cache.pivotMatrixUpdated = true;
  7852. };
  7853. AbstractMesh.prototype.getPivotMatrix = function () {
  7854. return this._pivotMatrix;
  7855. };
  7856. AbstractMesh.prototype._isSynchronized = function () {
  7857. if (this._isDirty) {
  7858. return false;
  7859. }
  7860. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7861. return false;
  7862. if (this._cache.pivotMatrixUpdated) {
  7863. return false;
  7864. }
  7865. if (this.infiniteDistance) {
  7866. return false;
  7867. }
  7868. if (!this._cache.position.equals(this.position))
  7869. return false;
  7870. if (this.rotationQuaternion) {
  7871. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7872. return false;
  7873. } else {
  7874. if (!this._cache.rotation.equals(this.rotation))
  7875. return false;
  7876. }
  7877. if (!this._cache.scaling.equals(this.scaling))
  7878. return false;
  7879. return true;
  7880. };
  7881. AbstractMesh.prototype._initCache = function () {
  7882. _super.prototype._initCache.call(this);
  7883. this._cache.localMatrixUpdated = false;
  7884. this._cache.position = BABYLON.Vector3.Zero();
  7885. this._cache.scaling = BABYLON.Vector3.Zero();
  7886. this._cache.rotation = BABYLON.Vector3.Zero();
  7887. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7888. };
  7889. AbstractMesh.prototype.markAsDirty = function (property) {
  7890. if (property === "rotation") {
  7891. this.rotationQuaternion = null;
  7892. }
  7893. this._currentRenderId = Number.MAX_VALUE;
  7894. this._isDirty = true;
  7895. };
  7896. AbstractMesh.prototype._updateBoundingInfo = function () {
  7897. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7898. this._boundingInfo._update(this.worldMatrixFromCache);
  7899. if (!this.subMeshes) {
  7900. return;
  7901. }
  7902. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7903. var subMesh = this.subMeshes[subIndex];
  7904. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7905. }
  7906. };
  7907. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7908. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7909. return this._worldMatrix;
  7910. }
  7911. this._cache.position.copyFrom(this.position);
  7912. this._cache.scaling.copyFrom(this.scaling);
  7913. this._cache.pivotMatrixUpdated = false;
  7914. this._currentRenderId = this.getScene().getRenderId();
  7915. this._isDirty = false;
  7916. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7917. if (this.rotationQuaternion) {
  7918. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7919. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7920. } else {
  7921. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7922. this._cache.rotation.copyFrom(this.rotation);
  7923. }
  7924. if (this.infiniteDistance && !this.parent) {
  7925. var camera = this.getScene().activeCamera;
  7926. var cameraWorldMatrix = camera.getWorldMatrix();
  7927. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7928. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7929. } else {
  7930. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7931. }
  7932. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7933. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7934. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7935. var localPosition = this.position.clone();
  7936. var zero = this.getScene().activeCamera.position.clone();
  7937. if (this.parent && this.parent.position) {
  7938. localPosition.addInPlace(this.parent.position);
  7939. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7940. }
  7941. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7942. zero = this.getScene().activeCamera.position;
  7943. } else {
  7944. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7945. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7946. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7947. zero.y = localPosition.y + 0.001;
  7948. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7949. zero.z = localPosition.z + 0.001;
  7950. }
  7951. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7952. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7953. this._localBillboard.invert();
  7954. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7955. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7956. }
  7957. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7958. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  7959. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7960. } else {
  7961. this._worldMatrix.copyFrom(this._localWorld);
  7962. }
  7963. this._updateBoundingInfo();
  7964. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7965. return this._worldMatrix;
  7966. };
  7967. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7968. this.computeWorldMatrix();
  7969. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7970. };
  7971. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7972. this.computeWorldMatrix();
  7973. var invLocalWorldMatrix = this._localWorld.clone();
  7974. invLocalWorldMatrix.invert();
  7975. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7976. };
  7977. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7978. this.computeWorldMatrix();
  7979. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7980. };
  7981. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7982. yawCor = yawCor || 0;
  7983. pitchCor = pitchCor || 0;
  7984. rollCor = rollCor || 0;
  7985. var dv = targetPoint.subtract(this.position);
  7986. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7987. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7988. var pitch = Math.atan2(dv.y, len);
  7989. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7990. };
  7991. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7992. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  7993. return false;
  7994. }
  7995. return true;
  7996. };
  7997. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7998. if (!camera) {
  7999. camera = this.getScene().activeCamera;
  8000. }
  8001. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8002. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8003. return false;
  8004. }
  8005. return true;
  8006. };
  8007. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8008. if (!this._boundingInfo || !mesh._boundingInfo) {
  8009. return false;
  8010. }
  8011. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8012. };
  8013. AbstractMesh.prototype.intersectsPoint = function (point) {
  8014. if (!this._boundingInfo) {
  8015. return false;
  8016. }
  8017. return this._boundingInfo.intersectsPoint(point);
  8018. };
  8019. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8020. var physicsEngine = this.getScene().getPhysicsEngine();
  8021. if (!physicsEngine) {
  8022. return;
  8023. }
  8024. if (impostor.impostor) {
  8025. options = impostor;
  8026. impostor = impostor.impostor;
  8027. }
  8028. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8029. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8030. physicsEngine._unregisterMesh(this);
  8031. return;
  8032. }
  8033. options.mass = options.mass || 0;
  8034. options.friction = options.friction || 0.2;
  8035. options.restitution = options.restitution || 0.2;
  8036. this._physicImpostor = impostor;
  8037. this._physicsMass = options.mass;
  8038. this._physicsFriction = options.friction;
  8039. this._physicRestitution = options.restitution;
  8040. physicsEngine._registerMesh(this, impostor, options);
  8041. };
  8042. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8043. if (!this._physicImpostor) {
  8044. return BABYLON.PhysicsEngine.NoImpostor;
  8045. }
  8046. return this._physicImpostor;
  8047. };
  8048. AbstractMesh.prototype.getPhysicsMass = function () {
  8049. if (!this._physicsMass) {
  8050. return 0;
  8051. }
  8052. return this._physicsMass;
  8053. };
  8054. AbstractMesh.prototype.getPhysicsFriction = function () {
  8055. if (!this._physicsFriction) {
  8056. return 0;
  8057. }
  8058. return this._physicsFriction;
  8059. };
  8060. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8061. if (!this._physicRestitution) {
  8062. return 0;
  8063. }
  8064. return this._physicRestitution;
  8065. };
  8066. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8067. if (!this._physicImpostor) {
  8068. return;
  8069. }
  8070. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8071. };
  8072. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8073. if (!this._physicImpostor) {
  8074. return;
  8075. }
  8076. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8077. };
  8078. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8079. if (!this._physicImpostor) {
  8080. return;
  8081. }
  8082. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8083. };
  8084. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8085. var globalPosition = this.getAbsolutePosition();
  8086. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8087. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8088. this._collider.radius = this.ellipsoid;
  8089. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8090. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8091. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8092. this.position.addInPlace(this._diffPositionForCollisions);
  8093. }
  8094. };
  8095. /**
  8096. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8097. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8098. */
  8099. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8100. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8101. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8102. if (!this._submeshesOctree) {
  8103. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8104. }
  8105. this.computeWorldMatrix(true);
  8106. var bbox = this.getBoundingInfo().boundingBox;
  8107. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8108. return this._submeshesOctree;
  8109. };
  8110. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8111. this._generatePointsArray();
  8112. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8113. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8114. subMesh._lastColliderWorldVertices = [];
  8115. subMesh._trianglePlanes = [];
  8116. var start = subMesh.verticesStart;
  8117. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8118. for (var i = start; i < end; i++) {
  8119. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8120. }
  8121. }
  8122. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8123. };
  8124. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8125. var subMeshes;
  8126. var len;
  8127. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8128. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8129. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8130. len = intersections.length;
  8131. subMeshes = intersections.data;
  8132. } else {
  8133. subMeshes = this.subMeshes;
  8134. len = subMeshes.length;
  8135. }
  8136. for (var index = 0; index < len; index++) {
  8137. var subMesh = subMeshes[index];
  8138. if (len > 1 && !subMesh._checkCollision(collider))
  8139. continue;
  8140. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8141. }
  8142. };
  8143. AbstractMesh.prototype._checkCollision = function (collider) {
  8144. if (!this._boundingInfo._checkCollision(collider))
  8145. return;
  8146. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8147. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8148. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8149. };
  8150. AbstractMesh.prototype._generatePointsArray = function () {
  8151. return false;
  8152. };
  8153. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8154. var pickingInfo = new BABYLON.PickingInfo();
  8155. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8156. return pickingInfo;
  8157. }
  8158. if (!this._generatePointsArray()) {
  8159. return pickingInfo;
  8160. }
  8161. var intersectInfo = null;
  8162. var subMeshes;
  8163. var len;
  8164. if (this._submeshesOctree && this.useOctreeForPicking) {
  8165. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8166. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8167. len = intersections.length;
  8168. subMeshes = intersections.data;
  8169. } else {
  8170. subMeshes = this.subMeshes;
  8171. len = subMeshes.length;
  8172. }
  8173. for (var index = 0; index < len; index++) {
  8174. var subMesh = subMeshes[index];
  8175. if (len > 1 && !subMesh.canIntersects(ray))
  8176. continue;
  8177. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8178. if (currentIntersectInfo) {
  8179. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8180. intersectInfo = currentIntersectInfo;
  8181. if (fastCheck) {
  8182. break;
  8183. }
  8184. }
  8185. }
  8186. }
  8187. if (intersectInfo) {
  8188. var world = this.getWorldMatrix();
  8189. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8190. var direction = ray.direction.clone();
  8191. direction.normalize();
  8192. direction = direction.scale(intersectInfo.distance);
  8193. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8194. var pickedPoint = worldOrigin.add(worldDirection);
  8195. pickingInfo.hit = true;
  8196. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8197. pickingInfo.pickedPoint = pickedPoint;
  8198. pickingInfo.pickedMesh = this;
  8199. pickingInfo.bu = intersectInfo.bu;
  8200. pickingInfo.bv = intersectInfo.bv;
  8201. pickingInfo.faceId = intersectInfo.faceId;
  8202. return pickingInfo;
  8203. }
  8204. return pickingInfo;
  8205. };
  8206. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8207. return null;
  8208. };
  8209. AbstractMesh.prototype.releaseSubMeshes = function () {
  8210. if (this.subMeshes) {
  8211. while (this.subMeshes.length) {
  8212. this.subMeshes[0].dispose();
  8213. }
  8214. } else {
  8215. this.subMeshes = new Array();
  8216. }
  8217. };
  8218. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8219. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8220. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8221. }
  8222. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8223. var other = this._intersectionsInProgress[index];
  8224. var pos = other._intersectionsInProgress.indexOf(this);
  8225. other._intersectionsInProgress.splice(pos, 1);
  8226. }
  8227. this._intersectionsInProgress = [];
  8228. this.releaseSubMeshes();
  8229. var index = this.getScene().meshes.indexOf(this);
  8230. if (index != -1) {
  8231. this.getScene().meshes.splice(index, 1);
  8232. }
  8233. if (!doNotRecurse) {
  8234. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8235. if (this.getScene().particleSystems[index].emitter == this) {
  8236. this.getScene().particleSystems[index].dispose();
  8237. index--;
  8238. }
  8239. }
  8240. var objects = this.getScene().meshes.slice(0);
  8241. for (index = 0; index < objects.length; index++) {
  8242. if (objects[index].parent == this) {
  8243. objects[index].dispose();
  8244. }
  8245. }
  8246. } else {
  8247. for (index = 0; index < this.getScene().meshes.length; index++) {
  8248. var obj = this.getScene().meshes[index];
  8249. if (obj.parent === this) {
  8250. obj.parent = null;
  8251. obj.computeWorldMatrix(true);
  8252. }
  8253. }
  8254. }
  8255. this._isDisposed = true;
  8256. if (this.onDispose) {
  8257. this.onDispose();
  8258. }
  8259. };
  8260. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8261. AbstractMesh._BILLBOARDMODE_X = 1;
  8262. AbstractMesh._BILLBOARDMODE_Y = 2;
  8263. AbstractMesh._BILLBOARDMODE_Z = 4;
  8264. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8265. return AbstractMesh;
  8266. })(BABYLON.Node);
  8267. BABYLON.AbstractMesh = AbstractMesh;
  8268. })(BABYLON || (BABYLON = {}));
  8269. var __extends = this.__extends || function (d, b) {
  8270. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8271. function __() { this.constructor = d; }
  8272. __.prototype = b.prototype;
  8273. d.prototype = new __();
  8274. };
  8275. var BABYLON;
  8276. (function (BABYLON) {
  8277. var _InstancesBatch = (function () {
  8278. function _InstancesBatch() {
  8279. this.mustReturn = false;
  8280. this.visibleInstances = new Array();
  8281. this.renderSelf = new Array();
  8282. }
  8283. return _InstancesBatch;
  8284. })();
  8285. BABYLON._InstancesBatch = _InstancesBatch;
  8286. var Mesh = (function (_super) {
  8287. __extends(Mesh, _super);
  8288. function Mesh(name, scene) {
  8289. _super.call(this, name, scene);
  8290. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8291. this.instances = new Array();
  8292. this._LODLevels = new Array();
  8293. this._onBeforeRenderCallbacks = new Array();
  8294. this._onAfterRenderCallbacks = new Array();
  8295. this._visibleInstances = {};
  8296. this._renderIdForInstances = new Array();
  8297. this._batchCache = new _InstancesBatch();
  8298. this._instancesBufferSize = 32 * 16 * 4;
  8299. }
  8300. Mesh.prototype._sortLODLevels = function () {
  8301. this._LODLevels.sort(function (a, b) {
  8302. if (a.distance < b.distance) {
  8303. return 1;
  8304. }
  8305. if (a.distance > b.distance) {
  8306. return -1;
  8307. }
  8308. return 0;
  8309. });
  8310. };
  8311. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8312. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8313. this._LODLevels.push(level);
  8314. if (mesh) {
  8315. mesh._attachedLODLevel = level;
  8316. }
  8317. this._sortLODLevels();
  8318. return this;
  8319. };
  8320. Mesh.prototype.removeLODLevel = function (mesh) {
  8321. if (mesh && !mesh._attachedLODLevel) {
  8322. return this;
  8323. }
  8324. var index;
  8325. if (mesh) {
  8326. index = this._LODLevels.indexOf(mesh._attachedLODLevel);
  8327. mesh._attachedLODLevel = null;
  8328. this._LODLevels.splice(index, 1);
  8329. this._sortLODLevels();
  8330. } else {
  8331. for (index = 0; index < this._LODLevels.length; index++) {
  8332. if (this._LODLevels[index].mesh === null) {
  8333. this._LODLevels.splice(index, 1);
  8334. break;
  8335. }
  8336. }
  8337. }
  8338. return this;
  8339. };
  8340. Mesh.prototype.getLOD = function (camera) {
  8341. if (!this._LODLevels || this._LODLevels.length === 0) {
  8342. return this;
  8343. }
  8344. var distanceToCamera = this.getBoundingInfo().boundingSphere.centerWorld.subtract(camera.position).length();
  8345. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8346. return this;
  8347. }
  8348. for (var index = 0; index < this._LODLevels.length; index++) {
  8349. var level = this._LODLevels[index];
  8350. if (level.distance < distanceToCamera) {
  8351. if (level.mesh) {
  8352. level.mesh._worldMatrix = this._worldMatrix;
  8353. }
  8354. return level.mesh;
  8355. }
  8356. }
  8357. return this;
  8358. };
  8359. Object.defineProperty(Mesh.prototype, "geometry", {
  8360. get: function () {
  8361. return this._geometry;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Mesh.prototype.getTotalVertices = function () {
  8367. if (!this._geometry) {
  8368. return 0;
  8369. }
  8370. return this._geometry.getTotalVertices();
  8371. };
  8372. Mesh.prototype.getVerticesData = function (kind) {
  8373. if (!this._geometry) {
  8374. return null;
  8375. }
  8376. return this._geometry.getVerticesData(kind);
  8377. };
  8378. Mesh.prototype.getVertexBuffer = function (kind) {
  8379. if (!this._geometry) {
  8380. return undefined;
  8381. }
  8382. return this._geometry.getVertexBuffer(kind);
  8383. };
  8384. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8385. if (!this._geometry) {
  8386. if (this._delayInfo) {
  8387. return this._delayInfo.indexOf(kind) !== -1;
  8388. }
  8389. return false;
  8390. }
  8391. return this._geometry.isVerticesDataPresent(kind);
  8392. };
  8393. Mesh.prototype.getVerticesDataKinds = function () {
  8394. if (!this._geometry) {
  8395. var result = [];
  8396. if (this._delayInfo) {
  8397. for (var kind in this._delayInfo) {
  8398. result.push(kind);
  8399. }
  8400. }
  8401. return result;
  8402. }
  8403. return this._geometry.getVerticesDataKinds();
  8404. };
  8405. Mesh.prototype.getTotalIndices = function () {
  8406. if (!this._geometry) {
  8407. return 0;
  8408. }
  8409. return this._geometry.getTotalIndices();
  8410. };
  8411. Mesh.prototype.getIndices = function () {
  8412. if (!this._geometry) {
  8413. return [];
  8414. }
  8415. return this._geometry.getIndices();
  8416. };
  8417. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8418. get: function () {
  8419. return this._attachedLODLevel !== null && this._attachedLODLevel !== undefined;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. Mesh.prototype.isReady = function () {
  8425. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8426. return false;
  8427. }
  8428. return _super.prototype.isReady.call(this);
  8429. };
  8430. Mesh.prototype.isDisposed = function () {
  8431. return this._isDisposed;
  8432. };
  8433. Mesh.prototype._preActivate = function () {
  8434. var sceneRenderId = this.getScene().getRenderId();
  8435. if (this._preActivateId == sceneRenderId) {
  8436. return;
  8437. }
  8438. this._preActivateId = sceneRenderId;
  8439. this._visibleInstances = null;
  8440. };
  8441. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8442. if (!this._visibleInstances) {
  8443. this._visibleInstances = {};
  8444. this._visibleInstances.defaultRenderId = renderId;
  8445. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8446. }
  8447. if (!this._visibleInstances[renderId]) {
  8448. this._visibleInstances[renderId] = new Array();
  8449. }
  8450. this._visibleInstances[renderId].push(instance);
  8451. };
  8452. Mesh.prototype.refreshBoundingInfo = function () {
  8453. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8454. if (data) {
  8455. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8456. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8457. }
  8458. if (this.subMeshes) {
  8459. for (var index = 0; index < this.subMeshes.length; index++) {
  8460. this.subMeshes[index].refreshBoundingInfo();
  8461. }
  8462. }
  8463. this._updateBoundingInfo();
  8464. };
  8465. Mesh.prototype._createGlobalSubMesh = function () {
  8466. var totalVertices = this.getTotalVertices();
  8467. if (!totalVertices || !this.getIndices()) {
  8468. return null;
  8469. }
  8470. this.releaseSubMeshes();
  8471. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8472. };
  8473. Mesh.prototype.subdivide = function (count) {
  8474. if (count < 1) {
  8475. return;
  8476. }
  8477. var totalIndices = this.getTotalIndices();
  8478. var subdivisionSize = (totalIndices / count) | 0;
  8479. var offset = 0;
  8480. while (subdivisionSize % 3 != 0) {
  8481. subdivisionSize++;
  8482. }
  8483. this.releaseSubMeshes();
  8484. for (var index = 0; index < count; index++) {
  8485. if (offset >= totalIndices) {
  8486. break;
  8487. }
  8488. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8489. offset += subdivisionSize;
  8490. }
  8491. this.synchronizeInstances();
  8492. };
  8493. Mesh.prototype.setVerticesData = function (kind, data, updatable) {
  8494. if (kind instanceof Array) {
  8495. var temp = data;
  8496. data = kind;
  8497. kind = temp;
  8498. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8499. }
  8500. if (!this._geometry) {
  8501. var vertexData = new BABYLON.VertexData();
  8502. vertexData.set(data, kind);
  8503. var scene = this.getScene();
  8504. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8505. } else {
  8506. this._geometry.setVerticesData(kind, data, updatable);
  8507. }
  8508. };
  8509. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8510. if (!this._geometry) {
  8511. return;
  8512. }
  8513. if (!makeItUnique) {
  8514. this._geometry.updateVerticesData(kind, data, updateExtends);
  8515. } else {
  8516. this.makeGeometryUnique();
  8517. this.updateVerticesData(kind, data, updateExtends, false);
  8518. }
  8519. };
  8520. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8521. if (!this._geometry) {
  8522. return;
  8523. }
  8524. if (!makeItUnique) {
  8525. this._geometry.updateVerticesDataDirectly(kind, data);
  8526. } else {
  8527. this.makeGeometryUnique();
  8528. this.updateVerticesDataDirectly(kind, data, false);
  8529. }
  8530. };
  8531. Mesh.prototype.makeGeometryUnique = function () {
  8532. if (!this._geometry) {
  8533. return;
  8534. }
  8535. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8536. geometry.applyToMesh(this);
  8537. };
  8538. Mesh.prototype.setIndices = function (indices) {
  8539. if (!this._geometry) {
  8540. var vertexData = new BABYLON.VertexData();
  8541. vertexData.indices = indices;
  8542. var scene = this.getScene();
  8543. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8544. } else {
  8545. this._geometry.setIndices(indices);
  8546. }
  8547. };
  8548. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8549. var engine = this.getScene().getEngine();
  8550. var indexToBind;
  8551. switch (fillMode) {
  8552. case BABYLON.Material.PointFillMode:
  8553. indexToBind = null;
  8554. break;
  8555. case BABYLON.Material.WireFrameFillMode:
  8556. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8557. break;
  8558. default:
  8559. case BABYLON.Material.TriangleFillMode:
  8560. indexToBind = this._geometry.getIndexBuffer();
  8561. break;
  8562. }
  8563. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8564. };
  8565. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8566. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8567. return;
  8568. }
  8569. var engine = this.getScene().getEngine();
  8570. switch (fillMode) {
  8571. case BABYLON.Material.PointFillMode:
  8572. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8573. break;
  8574. case BABYLON.Material.WireFrameFillMode:
  8575. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8576. break;
  8577. default:
  8578. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8579. }
  8580. };
  8581. Mesh.prototype.registerBeforeRender = function (func) {
  8582. this._onBeforeRenderCallbacks.push(func);
  8583. };
  8584. Mesh.prototype.unregisterBeforeRender = function (func) {
  8585. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8586. if (index > -1) {
  8587. this._onBeforeRenderCallbacks.splice(index, 1);
  8588. }
  8589. };
  8590. Mesh.prototype.registerAfterRender = function (func) {
  8591. this._onAfterRenderCallbacks.push(func);
  8592. };
  8593. Mesh.prototype.unregisterAfterRender = function (func) {
  8594. var index = this._onAfterRenderCallbacks.indexOf(func);
  8595. if (index > -1) {
  8596. this._onAfterRenderCallbacks.splice(index, 1);
  8597. }
  8598. };
  8599. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8600. var scene = this.getScene();
  8601. this._batchCache.mustReturn = false;
  8602. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8603. this._batchCache.visibleInstances[subMeshId] = null;
  8604. if (this._visibleInstances) {
  8605. var currentRenderId = scene.getRenderId();
  8606. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8607. var selfRenderId = this._renderId;
  8608. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8609. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8610. currentRenderId = this._visibleInstances.defaultRenderId;
  8611. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8612. }
  8613. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8614. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8615. this._batchCache.mustReturn = true;
  8616. return this._batchCache;
  8617. }
  8618. if (currentRenderId !== selfRenderId) {
  8619. this._batchCache.renderSelf[subMeshId] = false;
  8620. }
  8621. }
  8622. this._renderIdForInstances[subMeshId] = currentRenderId;
  8623. }
  8624. return this._batchCache;
  8625. };
  8626. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8627. var matricesCount = this.instances.length + 1;
  8628. var bufferSize = matricesCount * 16 * 4;
  8629. while (this._instancesBufferSize < bufferSize) {
  8630. this._instancesBufferSize *= 2;
  8631. }
  8632. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8633. if (this._worldMatricesInstancesBuffer) {
  8634. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8635. }
  8636. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8637. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8638. }
  8639. var offset = 0;
  8640. var instancesCount = 0;
  8641. var world = this.getWorldMatrix();
  8642. if (batch.renderSelf[subMesh._id]) {
  8643. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8644. offset += 16;
  8645. instancesCount++;
  8646. }
  8647. var visibleInstances = batch.visibleInstances[subMesh._id];
  8648. if (visibleInstances) {
  8649. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8650. var instance = visibleInstances[instanceIndex];
  8651. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8652. offset += 16;
  8653. instancesCount++;
  8654. }
  8655. }
  8656. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8657. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8658. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8659. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8660. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8661. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8662. this._draw(subMesh, fillMode, instancesCount);
  8663. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8664. };
  8665. Mesh.prototype.render = function (subMesh) {
  8666. var scene = this.getScene();
  8667. var batch = this._getInstancesRenderList(subMesh._id);
  8668. if (batch.mustReturn) {
  8669. return;
  8670. }
  8671. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8672. return;
  8673. }
  8674. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8675. this._onBeforeRenderCallbacks[callbackIndex]();
  8676. }
  8677. var engine = scene.getEngine();
  8678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8679. var effectiveMaterial = subMesh.getMaterial();
  8680. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8681. return;
  8682. }
  8683. var savedDepthWrite = engine.getDepthWrite();
  8684. if (this.renderOutline) {
  8685. engine.setDepthWrite(false);
  8686. scene.getOutlineRenderer().render(subMesh, batch);
  8687. }
  8688. effectiveMaterial._preBind();
  8689. var effect = effectiveMaterial.getEffect();
  8690. var fillMode = engine.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8691. this._bind(subMesh, effect, fillMode);
  8692. var world = this.getWorldMatrix();
  8693. effectiveMaterial.bind(world, this);
  8694. if (hardwareInstancedRendering) {
  8695. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8696. } else {
  8697. if (batch.renderSelf[subMesh._id]) {
  8698. this._draw(subMesh, fillMode);
  8699. }
  8700. if (batch.visibleInstances[subMesh._id]) {
  8701. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8702. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8703. world = instance.getWorldMatrix();
  8704. effectiveMaterial.bindOnlyWorldMatrix(world);
  8705. this._draw(subMesh, fillMode);
  8706. }
  8707. }
  8708. }
  8709. effectiveMaterial.unbind();
  8710. if (this.renderOutline && savedDepthWrite) {
  8711. engine.setDepthWrite(true);
  8712. engine.setColorWrite(false);
  8713. scene.getOutlineRenderer().render(subMesh, batch);
  8714. engine.setColorWrite(true);
  8715. }
  8716. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8717. this._onAfterRenderCallbacks[callbackIndex]();
  8718. }
  8719. };
  8720. Mesh.prototype.getEmittedParticleSystems = function () {
  8721. var results = new Array();
  8722. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8723. var particleSystem = this.getScene().particleSystems[index];
  8724. if (particleSystem.emitter === this) {
  8725. results.push(particleSystem);
  8726. }
  8727. }
  8728. return results;
  8729. };
  8730. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8731. var results = new Array();
  8732. var descendants = this.getDescendants();
  8733. descendants.push(this);
  8734. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8735. var particleSystem = this.getScene().particleSystems[index];
  8736. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8737. results.push(particleSystem);
  8738. }
  8739. }
  8740. return results;
  8741. };
  8742. Mesh.prototype.getChildren = function () {
  8743. var results = [];
  8744. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8745. var mesh = this.getScene().meshes[index];
  8746. if (mesh.parent == this) {
  8747. results.push(mesh);
  8748. }
  8749. }
  8750. return results;
  8751. };
  8752. Mesh.prototype._checkDelayState = function () {
  8753. var _this = this;
  8754. var that = this;
  8755. var scene = this.getScene();
  8756. if (this._geometry) {
  8757. this._geometry.load(scene);
  8758. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8759. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8760. scene._addPendingData(that);
  8761. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8762. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8763. if (data instanceof ArrayBuffer) {
  8764. _this._delayLoadingFunction(data, _this);
  8765. } else {
  8766. _this._delayLoadingFunction(JSON.parse(data), _this);
  8767. }
  8768. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8769. scene._removePendingData(_this);
  8770. }, function () {
  8771. }, scene.database, getBinaryData);
  8772. }
  8773. };
  8774. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8775. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8776. return false;
  8777. }
  8778. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8779. return false;
  8780. }
  8781. this._checkDelayState();
  8782. return true;
  8783. };
  8784. Mesh.prototype.setMaterialByID = function (id) {
  8785. var materials = this.getScene().materials;
  8786. for (var index = 0; index < materials.length; index++) {
  8787. if (materials[index].id == id) {
  8788. this.material = materials[index];
  8789. return;
  8790. }
  8791. }
  8792. var multiMaterials = this.getScene().multiMaterials;
  8793. for (index = 0; index < multiMaterials.length; index++) {
  8794. if (multiMaterials[index].id == id) {
  8795. this.material = multiMaterials[index];
  8796. return;
  8797. }
  8798. }
  8799. };
  8800. Mesh.prototype.getAnimatables = function () {
  8801. var results = [];
  8802. if (this.material) {
  8803. results.push(this.material);
  8804. }
  8805. if (this.skeleton) {
  8806. results.push(this.skeleton);
  8807. }
  8808. return results;
  8809. };
  8810. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8811. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8812. return;
  8813. }
  8814. this._resetPointsArrayCache();
  8815. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8816. var temp = [];
  8817. for (var index = 0; index < data.length; index += 3) {
  8818. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8819. }
  8820. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8821. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8822. return;
  8823. }
  8824. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8825. for (index = 0; index < data.length; index += 3) {
  8826. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8827. }
  8828. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8829. };
  8830. Mesh.prototype._resetPointsArrayCache = function () {
  8831. this._positions = null;
  8832. };
  8833. Mesh.prototype._generatePointsArray = function () {
  8834. if (this._positions)
  8835. return true;
  8836. this._positions = [];
  8837. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8838. if (!data) {
  8839. return false;
  8840. }
  8841. for (var index = 0; index < data.length; index += 3) {
  8842. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8843. }
  8844. return true;
  8845. };
  8846. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8847. var result = new BABYLON.Mesh(name, this.getScene());
  8848. this._geometry.applyToMesh(result);
  8849. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8850. result.material = this.material;
  8851. if (newParent) {
  8852. result.parent = newParent;
  8853. }
  8854. if (!doNotCloneChildren) {
  8855. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8856. var mesh = this.getScene().meshes[index];
  8857. if (mesh.parent == this) {
  8858. mesh.clone(mesh.name, result);
  8859. }
  8860. }
  8861. }
  8862. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8863. var system = this.getScene().particleSystems[index];
  8864. if (system.emitter == this) {
  8865. system.clone(system.name, result);
  8866. }
  8867. }
  8868. result.computeWorldMatrix(true);
  8869. return result;
  8870. };
  8871. Mesh.prototype.dispose = function (doNotRecurse) {
  8872. if (this._geometry) {
  8873. this._geometry.releaseForMesh(this, true);
  8874. }
  8875. if (this._worldMatricesInstancesBuffer) {
  8876. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8877. this._worldMatricesInstancesBuffer = null;
  8878. }
  8879. while (this.instances.length) {
  8880. this.instances[0].dispose();
  8881. }
  8882. _super.prototype.dispose.call(this, doNotRecurse);
  8883. };
  8884. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8885. var _this = this;
  8886. var scene = this.getScene();
  8887. var onload = function (img) {
  8888. var canvas = document.createElement("canvas");
  8889. var context = canvas.getContext("2d");
  8890. var heightMapWidth = img.width;
  8891. var heightMapHeight = img.height;
  8892. canvas.width = heightMapWidth;
  8893. canvas.height = heightMapHeight;
  8894. context.drawImage(img, 0, 0);
  8895. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8896. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8897. };
  8898. BABYLON.Tools.LoadImage(url, onload, function () {
  8899. }, scene.database);
  8900. };
  8901. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8902. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8903. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8904. return;
  8905. }
  8906. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8907. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8908. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8909. var position = BABYLON.Vector3.Zero();
  8910. var normal = BABYLON.Vector3.Zero();
  8911. var uv = BABYLON.Vector2.Zero();
  8912. for (var index = 0; index < positions.length; index += 3) {
  8913. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8914. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8915. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8916. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8917. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8918. var pos = (u + v * heightMapWidth) * 4;
  8919. var r = buffer[pos] / 255.0;
  8920. var g = buffer[pos + 1] / 255.0;
  8921. var b = buffer[pos + 2] / 255.0;
  8922. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8923. normal.normalize();
  8924. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8925. position = position.add(normal);
  8926. position.toArray(positions, index);
  8927. }
  8928. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8929. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8930. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8931. };
  8932. Mesh.prototype.convertToFlatShadedMesh = function () {
  8933. var kinds = this.getVerticesDataKinds();
  8934. var vbs = [];
  8935. var data = [];
  8936. var newdata = [];
  8937. var updatableNormals = false;
  8938. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8939. var kind = kinds[kindIndex];
  8940. var vertexBuffer = this.getVertexBuffer(kind);
  8941. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8942. updatableNormals = vertexBuffer.isUpdatable();
  8943. kinds.splice(kindIndex, 1);
  8944. kindIndex--;
  8945. continue;
  8946. }
  8947. vbs[kind] = vertexBuffer;
  8948. data[kind] = vbs[kind].getData();
  8949. newdata[kind] = [];
  8950. }
  8951. var previousSubmeshes = this.subMeshes.slice(0);
  8952. var indices = this.getIndices();
  8953. var totalIndices = this.getTotalIndices();
  8954. for (index = 0; index < totalIndices; index++) {
  8955. var vertexIndex = indices[index];
  8956. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8957. kind = kinds[kindIndex];
  8958. var stride = vbs[kind].getStrideSize();
  8959. for (var offset = 0; offset < stride; offset++) {
  8960. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  8961. }
  8962. }
  8963. }
  8964. var normals = [];
  8965. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  8966. for (var index = 0; index < totalIndices; index += 3) {
  8967. indices[index] = index;
  8968. indices[index + 1] = index + 1;
  8969. indices[index + 2] = index + 2;
  8970. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  8971. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  8972. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  8973. var p1p2 = p1.subtract(p2);
  8974. var p3p2 = p3.subtract(p2);
  8975. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  8976. for (var localIndex = 0; localIndex < 3; localIndex++) {
  8977. normals.push(normal.x);
  8978. normals.push(normal.y);
  8979. normals.push(normal.z);
  8980. }
  8981. }
  8982. this.setIndices(indices);
  8983. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  8984. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8985. kind = kinds[kindIndex];
  8986. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  8987. }
  8988. this.releaseSubMeshes();
  8989. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  8990. var previousOne = previousSubmeshes[submeshIndex];
  8991. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  8992. }
  8993. this.synchronizeInstances();
  8994. };
  8995. Mesh.prototype.createInstance = function (name) {
  8996. return new BABYLON.InstancedMesh(name, this);
  8997. };
  8998. Mesh.prototype.synchronizeInstances = function () {
  8999. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9000. var instance = this.instances[instanceIndex];
  9001. instance._syncSubMeshes();
  9002. }
  9003. };
  9004. Mesh.CreateBox = function (name, size, scene, updatable) {
  9005. var box = new BABYLON.Mesh(name, scene);
  9006. var vertexData = BABYLON.VertexData.CreateBox(size);
  9007. vertexData.applyToMesh(box, updatable);
  9008. return box;
  9009. };
  9010. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9011. var sphere = new BABYLON.Mesh(name, scene);
  9012. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9013. vertexData.applyToMesh(sphere, updatable);
  9014. return sphere;
  9015. };
  9016. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9017. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9018. if (scene !== undefined) {
  9019. updatable = scene;
  9020. }
  9021. scene = subdivisions;
  9022. subdivisions = 1;
  9023. }
  9024. var cylinder = new BABYLON.Mesh(name, scene);
  9025. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9026. vertexData.applyToMesh(cylinder, updatable);
  9027. return cylinder;
  9028. };
  9029. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9030. var torus = new BABYLON.Mesh(name, scene);
  9031. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9032. vertexData.applyToMesh(torus, updatable);
  9033. return torus;
  9034. };
  9035. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9036. var torusKnot = new BABYLON.Mesh(name, scene);
  9037. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9038. vertexData.applyToMesh(torusKnot, updatable);
  9039. return torusKnot;
  9040. };
  9041. Mesh.CreateLines = function (name, points, scene, updatable) {
  9042. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9043. var vertexData = BABYLON.VertexData.CreateLines(points);
  9044. vertexData.applyToMesh(lines, updatable);
  9045. return lines;
  9046. };
  9047. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9048. var plane = new BABYLON.Mesh(name, scene);
  9049. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9050. vertexData.applyToMesh(plane, updatable);
  9051. return plane;
  9052. };
  9053. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9054. var ground = new BABYLON.GroundMesh(name, scene);
  9055. ground._setReady(false);
  9056. ground._subdivisions = subdivisions;
  9057. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9058. vertexData.applyToMesh(ground, updatable);
  9059. ground._setReady(true);
  9060. return ground;
  9061. };
  9062. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9063. var tiledGround = new BABYLON.Mesh(name, scene);
  9064. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9065. vertexData.applyToMesh(tiledGround, updatable);
  9066. return tiledGround;
  9067. };
  9068. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9069. var ground = new BABYLON.GroundMesh(name, scene);
  9070. ground._subdivisions = subdivisions;
  9071. ground._setReady(false);
  9072. var onload = function (img) {
  9073. var canvas = document.createElement("canvas");
  9074. var context = canvas.getContext("2d");
  9075. var heightMapWidth = img.width;
  9076. var heightMapHeight = img.height;
  9077. canvas.width = heightMapWidth;
  9078. canvas.height = heightMapHeight;
  9079. context.drawImage(img, 0, 0);
  9080. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9081. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9082. vertexData.applyToMesh(ground, updatable);
  9083. ground._setReady(true);
  9084. };
  9085. BABYLON.Tools.LoadImage(url, onload, function () {
  9086. }, scene.database);
  9087. return ground;
  9088. };
  9089. Mesh.MinMax = function (meshes) {
  9090. var minVector = null;
  9091. var maxVector = null;
  9092. for (var i in meshes) {
  9093. var mesh = meshes[i];
  9094. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9095. if (!minVector) {
  9096. minVector = boundingBox.minimumWorld;
  9097. maxVector = boundingBox.maximumWorld;
  9098. continue;
  9099. }
  9100. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9101. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9102. }
  9103. return {
  9104. min: minVector,
  9105. max: maxVector
  9106. };
  9107. };
  9108. Mesh.Center = function (meshesOrMinMaxVector) {
  9109. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9110. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9111. };
  9112. return Mesh;
  9113. })(BABYLON.AbstractMesh);
  9114. BABYLON.Mesh = Mesh;
  9115. })(BABYLON || (BABYLON = {}));
  9116. var __extends = this.__extends || function (d, b) {
  9117. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9118. function __() { this.constructor = d; }
  9119. __.prototype = b.prototype;
  9120. d.prototype = new __();
  9121. };
  9122. var BABYLON;
  9123. (function (BABYLON) {
  9124. var GroundMesh = (function (_super) {
  9125. __extends(GroundMesh, _super);
  9126. function GroundMesh(name, scene) {
  9127. _super.call(this, name, scene);
  9128. this.generateOctree = false;
  9129. this._worldInverse = new BABYLON.Matrix();
  9130. }
  9131. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9132. get: function () {
  9133. return this._subdivisions;
  9134. },
  9135. enumerable: true,
  9136. configurable: true
  9137. });
  9138. GroundMesh.prototype.optimize = function (chunksCount) {
  9139. this.subdivide(this._subdivisions);
  9140. this.createOrUpdateSubmeshesOctree(32);
  9141. };
  9142. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9143. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9144. this.getWorldMatrix().invertToRef(this._worldInverse);
  9145. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9146. var pickInfo = this.intersects(ray);
  9147. if (pickInfo.hit) {
  9148. return pickInfo.pickedPoint.y;
  9149. }
  9150. return 0;
  9151. };
  9152. return GroundMesh;
  9153. })(BABYLON.Mesh);
  9154. BABYLON.GroundMesh = GroundMesh;
  9155. })(BABYLON || (BABYLON = {}));
  9156. var __extends = this.__extends || function (d, b) {
  9157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9158. function __() { this.constructor = d; }
  9159. __.prototype = b.prototype;
  9160. d.prototype = new __();
  9161. };
  9162. var BABYLON;
  9163. (function (BABYLON) {
  9164. var InstancedMesh = (function (_super) {
  9165. __extends(InstancedMesh, _super);
  9166. function InstancedMesh(name, source) {
  9167. _super.call(this, name, source.getScene());
  9168. source.instances.push(this);
  9169. this._sourceMesh = source;
  9170. this.position.copyFrom(source.position);
  9171. this.rotation.copyFrom(source.rotation);
  9172. this.scaling.copyFrom(source.scaling);
  9173. if (source.rotationQuaternion) {
  9174. this.rotationQuaternion = source.rotationQuaternion.clone();
  9175. }
  9176. this.infiniteDistance = source.infiniteDistance;
  9177. this.setPivotMatrix(source.getPivotMatrix());
  9178. this.refreshBoundingInfo();
  9179. this._syncSubMeshes();
  9180. }
  9181. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9182. get: function () {
  9183. return this._sourceMesh.receiveShadows;
  9184. },
  9185. enumerable: true,
  9186. configurable: true
  9187. });
  9188. Object.defineProperty(InstancedMesh.prototype, "material", {
  9189. get: function () {
  9190. return this._sourceMesh.material;
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9196. get: function () {
  9197. return this._sourceMesh.visibility;
  9198. },
  9199. enumerable: true,
  9200. configurable: true
  9201. });
  9202. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9203. get: function () {
  9204. return this._sourceMesh.skeleton;
  9205. },
  9206. enumerable: true,
  9207. configurable: true
  9208. });
  9209. InstancedMesh.prototype.getTotalVertices = function () {
  9210. return this._sourceMesh.getTotalVertices();
  9211. };
  9212. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9213. get: function () {
  9214. return this._sourceMesh;
  9215. },
  9216. enumerable: true,
  9217. configurable: true
  9218. });
  9219. InstancedMesh.prototype.getVerticesData = function (kind) {
  9220. return this._sourceMesh.getVerticesData(kind);
  9221. };
  9222. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9223. return this._sourceMesh.isVerticesDataPresent(kind);
  9224. };
  9225. InstancedMesh.prototype.getIndices = function () {
  9226. return this._sourceMesh.getIndices();
  9227. };
  9228. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9229. get: function () {
  9230. return this._sourceMesh._positions;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9236. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9237. if (data) {
  9238. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9239. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9240. }
  9241. this._updateBoundingInfo();
  9242. };
  9243. InstancedMesh.prototype._preActivate = function () {
  9244. this.sourceMesh._preActivate();
  9245. };
  9246. InstancedMesh.prototype._activate = function (renderId) {
  9247. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  9248. };
  9249. InstancedMesh.prototype._syncSubMeshes = function () {
  9250. this.releaseSubMeshes();
  9251. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9252. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9253. }
  9254. };
  9255. InstancedMesh.prototype._generatePointsArray = function () {
  9256. return this._sourceMesh._generatePointsArray();
  9257. };
  9258. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9259. var result = this._sourceMesh.createInstance(name);
  9260. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9261. this.refreshBoundingInfo();
  9262. if (newParent) {
  9263. result.parent = newParent;
  9264. }
  9265. if (!doNotCloneChildren) {
  9266. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9267. var mesh = this.getScene().meshes[index];
  9268. if (mesh.parent == this) {
  9269. mesh.clone(mesh.name, result);
  9270. }
  9271. }
  9272. }
  9273. result.computeWorldMatrix(true);
  9274. return result;
  9275. };
  9276. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9277. var index = this._sourceMesh.instances.indexOf(this);
  9278. this._sourceMesh.instances.splice(index, 1);
  9279. _super.prototype.dispose.call(this, doNotRecurse);
  9280. };
  9281. return InstancedMesh;
  9282. })(BABYLON.AbstractMesh);
  9283. BABYLON.InstancedMesh = InstancedMesh;
  9284. })(BABYLON || (BABYLON = {}));
  9285. var BABYLON;
  9286. (function (BABYLON) {
  9287. var SubMesh = (function () {
  9288. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9289. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9290. this.materialIndex = materialIndex;
  9291. this.verticesStart = verticesStart;
  9292. this.verticesCount = verticesCount;
  9293. this.indexStart = indexStart;
  9294. this.indexCount = indexCount;
  9295. this._renderId = 0;
  9296. this._mesh = mesh;
  9297. this._renderingMesh = renderingMesh || mesh;
  9298. mesh.subMeshes.push(this);
  9299. this._id = mesh.subMeshes.length - 1;
  9300. if (createBoundingBox) {
  9301. this.refreshBoundingInfo();
  9302. }
  9303. }
  9304. SubMesh.prototype.getBoundingInfo = function () {
  9305. return this._boundingInfo;
  9306. };
  9307. SubMesh.prototype.getMesh = function () {
  9308. return this._mesh;
  9309. };
  9310. SubMesh.prototype.getRenderingMesh = function () {
  9311. return this._renderingMesh;
  9312. };
  9313. SubMesh.prototype.getMaterial = function () {
  9314. var rootMaterial = this._renderingMesh.material;
  9315. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9316. var multiMaterial = rootMaterial;
  9317. return multiMaterial.getSubMaterial(this.materialIndex);
  9318. }
  9319. if (!rootMaterial) {
  9320. return this._mesh.getScene().defaultMaterial;
  9321. }
  9322. return rootMaterial;
  9323. };
  9324. SubMesh.prototype.refreshBoundingInfo = function () {
  9325. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9326. if (!data) {
  9327. this._boundingInfo = this._mesh._boundingInfo;
  9328. return;
  9329. }
  9330. var indices = this._renderingMesh.getIndices();
  9331. var extend;
  9332. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9333. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9334. } else {
  9335. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9336. }
  9337. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9338. };
  9339. SubMesh.prototype._checkCollision = function (collider) {
  9340. return this._boundingInfo._checkCollision(collider);
  9341. };
  9342. SubMesh.prototype.updateBoundingInfo = function (world) {
  9343. if (!this._boundingInfo) {
  9344. this.refreshBoundingInfo();
  9345. }
  9346. this._boundingInfo._update(world);
  9347. };
  9348. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9349. return this._boundingInfo.isInFrustum(frustumPlanes);
  9350. };
  9351. SubMesh.prototype.render = function () {
  9352. this._renderingMesh.render(this);
  9353. };
  9354. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9355. if (!this._linesIndexBuffer) {
  9356. var linesIndices = [];
  9357. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9358. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9359. }
  9360. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9361. this.linesIndexCount = linesIndices.length;
  9362. }
  9363. return this._linesIndexBuffer;
  9364. };
  9365. SubMesh.prototype.canIntersects = function (ray) {
  9366. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9367. };
  9368. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9369. var intersectInfo = null;
  9370. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9371. var p0 = positions[indices[index]];
  9372. var p1 = positions[indices[index + 1]];
  9373. var p2 = positions[indices[index + 2]];
  9374. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9375. if (currentIntersectInfo) {
  9376. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9377. intersectInfo = currentIntersectInfo;
  9378. intersectInfo.faceId = index / 3;
  9379. if (fastCheck) {
  9380. break;
  9381. }
  9382. }
  9383. }
  9384. }
  9385. return intersectInfo;
  9386. };
  9387. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9388. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9389. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9390. return result;
  9391. };
  9392. SubMesh.prototype.dispose = function () {
  9393. if (this._linesIndexBuffer) {
  9394. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9395. this._linesIndexBuffer = null;
  9396. }
  9397. var index = this._mesh.subMeshes.indexOf(this);
  9398. this._mesh.subMeshes.splice(index, 1);
  9399. };
  9400. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9401. var minVertexIndex = Number.MAX_VALUE;
  9402. var maxVertexIndex = -Number.MAX_VALUE;
  9403. renderingMesh = renderingMesh || mesh;
  9404. var indices = renderingMesh.getIndices();
  9405. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9406. var vertexIndex = indices[index];
  9407. if (vertexIndex < minVertexIndex)
  9408. minVertexIndex = vertexIndex;
  9409. if (vertexIndex > maxVertexIndex)
  9410. maxVertexIndex = vertexIndex;
  9411. }
  9412. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9413. };
  9414. return SubMesh;
  9415. })();
  9416. BABYLON.SubMesh = SubMesh;
  9417. })(BABYLON || (BABYLON = {}));
  9418. var BABYLON;
  9419. (function (BABYLON) {
  9420. var BaseTexture = (function () {
  9421. function BaseTexture(scene) {
  9422. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9423. this.hasAlpha = false;
  9424. this.getAlphaFromRGB = false;
  9425. this.level = 1;
  9426. this.isCube = false;
  9427. this.isRenderTarget = false;
  9428. this.animations = new Array();
  9429. this.coordinatesIndex = 0;
  9430. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9431. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9432. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9433. this.anisotropicFilteringLevel = 4;
  9434. this._scene = scene;
  9435. this._scene.textures.push(this);
  9436. }
  9437. BaseTexture.prototype.getScene = function () {
  9438. return this._scene;
  9439. };
  9440. BaseTexture.prototype.getTextureMatrix = function () {
  9441. return null;
  9442. };
  9443. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9444. return null;
  9445. };
  9446. BaseTexture.prototype.getInternalTexture = function () {
  9447. return this._texture;
  9448. };
  9449. BaseTexture.prototype.isReady = function () {
  9450. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9451. return true;
  9452. }
  9453. if (this._texture) {
  9454. return this._texture.isReady;
  9455. }
  9456. return false;
  9457. };
  9458. BaseTexture.prototype.getSize = function () {
  9459. if (this._texture._width) {
  9460. return { width: this._texture._width, height: this._texture._height };
  9461. }
  9462. if (this._texture._size) {
  9463. return { width: this._texture._size, height: this._texture._size };
  9464. }
  9465. return { width: 0, height: 0 };
  9466. };
  9467. BaseTexture.prototype.getBaseSize = function () {
  9468. if (!this.isReady())
  9469. return { width: 0, height: 0 };
  9470. if (this._texture._size) {
  9471. return { width: this._texture._size, height: this._texture._size };
  9472. }
  9473. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9474. };
  9475. BaseTexture.prototype.scale = function (ratio) {
  9476. };
  9477. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9478. get: function () {
  9479. return false;
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9485. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9486. for (var index = 0; index < texturesCache.length; index++) {
  9487. var texturesCacheEntry = texturesCache[index];
  9488. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9489. texturesCache.splice(index, 1);
  9490. return;
  9491. }
  9492. }
  9493. };
  9494. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9495. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9496. for (var index = 0; index < texturesCache.length; index++) {
  9497. var texturesCacheEntry = texturesCache[index];
  9498. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9499. texturesCacheEntry.references++;
  9500. return texturesCacheEntry;
  9501. }
  9502. }
  9503. return null;
  9504. };
  9505. BaseTexture.prototype.delayLoad = function () {
  9506. };
  9507. BaseTexture.prototype.releaseInternalTexture = function () {
  9508. if (!this._texture) {
  9509. return;
  9510. }
  9511. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9512. this._texture.references--;
  9513. if (this._texture.references == 0) {
  9514. var index = texturesCache.indexOf(this._texture);
  9515. texturesCache.splice(index, 1);
  9516. this._scene.getEngine()._releaseTexture(this._texture);
  9517. delete this._texture;
  9518. }
  9519. };
  9520. BaseTexture.prototype.clone = function () {
  9521. return null;
  9522. };
  9523. BaseTexture.prototype.dispose = function () {
  9524. var index = this._scene.textures.indexOf(this);
  9525. if (index >= 0) {
  9526. this._scene.textures.splice(index, 1);
  9527. }
  9528. if (this._texture === undefined) {
  9529. return;
  9530. }
  9531. this.releaseInternalTexture();
  9532. if (this.onDispose) {
  9533. this.onDispose();
  9534. }
  9535. };
  9536. return BaseTexture;
  9537. })();
  9538. BABYLON.BaseTexture = BaseTexture;
  9539. })(BABYLON || (BABYLON = {}));
  9540. var BABYLON;
  9541. (function (BABYLON) {
  9542. var RenderingGroup = (function () {
  9543. function RenderingGroup(index, scene) {
  9544. this.index = index;
  9545. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9546. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9547. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9548. this._scene = scene;
  9549. }
  9550. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9551. if (customRenderFunction) {
  9552. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9553. return true;
  9554. }
  9555. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9556. return false;
  9557. }
  9558. var engine = this._scene.getEngine();
  9559. var subIndex;
  9560. var submesh;
  9561. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9562. submesh = this._opaqueSubMeshes.data[subIndex];
  9563. this._activeVertices += submesh.verticesCount;
  9564. submesh.render();
  9565. }
  9566. engine.setAlphaTesting(true);
  9567. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9568. submesh = this._alphaTestSubMeshes.data[subIndex];
  9569. this._activeVertices += submesh.verticesCount;
  9570. submesh.render();
  9571. }
  9572. engine.setAlphaTesting(false);
  9573. if (beforeTransparents) {
  9574. beforeTransparents();
  9575. }
  9576. if (this._transparentSubMeshes.length) {
  9577. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9578. submesh = this._transparentSubMeshes.data[subIndex];
  9579. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9580. }
  9581. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9582. sortedArray.sort(function (a, b) {
  9583. if (a._distanceToCamera < b._distanceToCamera) {
  9584. return 1;
  9585. }
  9586. if (a._distanceToCamera > b._distanceToCamera) {
  9587. return -1;
  9588. }
  9589. return 0;
  9590. });
  9591. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9592. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9593. submesh = sortedArray[subIndex];
  9594. this._activeVertices += submesh.verticesCount;
  9595. submesh.render();
  9596. }
  9597. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9598. }
  9599. return true;
  9600. };
  9601. RenderingGroup.prototype.prepare = function () {
  9602. this._opaqueSubMeshes.reset();
  9603. this._transparentSubMeshes.reset();
  9604. this._alphaTestSubMeshes.reset();
  9605. };
  9606. RenderingGroup.prototype.dispatch = function (subMesh) {
  9607. var material = subMesh.getMaterial();
  9608. var mesh = subMesh.getMesh();
  9609. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9610. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9611. this._transparentSubMeshes.push(subMesh);
  9612. }
  9613. } else if (material.needAlphaTesting()) {
  9614. this._alphaTestSubMeshes.push(subMesh);
  9615. } else {
  9616. this._opaqueSubMeshes.push(subMesh);
  9617. }
  9618. };
  9619. return RenderingGroup;
  9620. })();
  9621. BABYLON.RenderingGroup = RenderingGroup;
  9622. })(BABYLON || (BABYLON = {}));
  9623. var BABYLON;
  9624. (function (BABYLON) {
  9625. var RenderingManager = (function () {
  9626. function RenderingManager(scene) {
  9627. this._renderingGroups = new Array();
  9628. this._scene = scene;
  9629. }
  9630. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9631. if (this._scene._activeParticleSystems.length === 0) {
  9632. return;
  9633. }
  9634. var beforeParticlesDate = BABYLON.Tools.Now;
  9635. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9636. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9637. if (particleSystem.renderingGroupId !== index) {
  9638. continue;
  9639. }
  9640. this._clearDepthBuffer();
  9641. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9642. this._scene._activeParticles += particleSystem.render();
  9643. }
  9644. }
  9645. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9646. };
  9647. RenderingManager.prototype._renderSprites = function (index) {
  9648. if (this._scene.spriteManagers.length === 0) {
  9649. return;
  9650. }
  9651. var beforeSpritessDate = BABYLON.Tools.Now;
  9652. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9653. var spriteManager = this._scene.spriteManagers[id];
  9654. if (spriteManager.renderingGroupId === index) {
  9655. this._clearDepthBuffer();
  9656. spriteManager.render();
  9657. }
  9658. }
  9659. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9660. };
  9661. RenderingManager.prototype._clearDepthBuffer = function () {
  9662. if (this._depthBufferAlreadyCleaned) {
  9663. return;
  9664. }
  9665. this._scene.getEngine().clear(0, false, true);
  9666. this._depthBufferAlreadyCleaned = true;
  9667. };
  9668. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9669. var _this = this;
  9670. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9671. this._depthBufferAlreadyCleaned = false;
  9672. var renderingGroup = this._renderingGroups[index];
  9673. if (renderingGroup) {
  9674. this._clearDepthBuffer();
  9675. if (!renderingGroup.render(customRenderFunction, function () {
  9676. if (renderSprites) {
  9677. _this._renderSprites(index);
  9678. }
  9679. })) {
  9680. this._renderingGroups.splice(index, 1);
  9681. }
  9682. } else if (renderSprites) {
  9683. this._renderSprites(index);
  9684. }
  9685. if (renderParticles) {
  9686. this._renderParticles(index, activeMeshes);
  9687. }
  9688. }
  9689. };
  9690. RenderingManager.prototype.reset = function () {
  9691. for (var index in this._renderingGroups) {
  9692. var renderingGroup = this._renderingGroups[index];
  9693. renderingGroup.prepare();
  9694. }
  9695. };
  9696. RenderingManager.prototype.dispatch = function (subMesh) {
  9697. var mesh = subMesh.getMesh();
  9698. var renderingGroupId = mesh.renderingGroupId || 0;
  9699. if (!this._renderingGroups[renderingGroupId]) {
  9700. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9701. }
  9702. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9703. };
  9704. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9705. return RenderingManager;
  9706. })();
  9707. BABYLON.RenderingManager = RenderingManager;
  9708. })(BABYLON || (BABYLON = {}));
  9709. var __extends = this.__extends || function (d, b) {
  9710. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9711. function __() { this.constructor = d; }
  9712. __.prototype = b.prototype;
  9713. d.prototype = new __();
  9714. };
  9715. var BABYLON;
  9716. (function (BABYLON) {
  9717. var Texture = (function (_super) {
  9718. __extends(Texture, _super);
  9719. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9720. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9721. if (typeof onLoad === "undefined") { onLoad = null; }
  9722. if (typeof onError === "undefined") { onError = null; }
  9723. if (typeof buffer === "undefined") { buffer = null; }
  9724. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9725. _super.call(this, scene);
  9726. this.uOffset = 0;
  9727. this.vOffset = 0;
  9728. this.uScale = 1.0;
  9729. this.vScale = 1.0;
  9730. this.uAng = 0;
  9731. this.vAng = 0;
  9732. this.wAng = 0;
  9733. this.name = url;
  9734. this.url = url;
  9735. this._noMipmap = noMipmap;
  9736. this._invertY = invertY;
  9737. this._samplingMode = samplingMode;
  9738. this._buffer = buffer;
  9739. this._deleteBuffer = deleteBuffer;
  9740. if (!url) {
  9741. return;
  9742. }
  9743. this._texture = this._getFromCache(url, noMipmap);
  9744. if (!this._texture) {
  9745. if (!scene.useDelayedTextureLoading) {
  9746. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9747. if (deleteBuffer) {
  9748. delete this._buffer;
  9749. }
  9750. } else {
  9751. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9752. }
  9753. }
  9754. }
  9755. Texture.prototype.delayLoad = function () {
  9756. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9757. return;
  9758. }
  9759. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9760. this._texture = this._getFromCache(this.url, this._noMipmap);
  9761. if (!this._texture) {
  9762. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9763. if (this._deleteBuffer) {
  9764. delete this._buffer;
  9765. }
  9766. }
  9767. };
  9768. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9769. x -= this.uOffset + 0.5;
  9770. y -= this.vOffset + 0.5;
  9771. z -= 0.5;
  9772. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9773. t.x *= this.uScale;
  9774. t.y *= this.vScale;
  9775. t.x += 0.5;
  9776. t.y += 0.5;
  9777. t.z += 0.5;
  9778. };
  9779. Texture.prototype.getTextureMatrix = function () {
  9780. 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) {
  9781. return this._cachedTextureMatrix;
  9782. }
  9783. this._cachedUOffset = this.uOffset;
  9784. this._cachedVOffset = this.vOffset;
  9785. this._cachedUScale = this.uScale;
  9786. this._cachedVScale = this.vScale;
  9787. this._cachedUAng = this.uAng;
  9788. this._cachedVAng = this.vAng;
  9789. this._cachedWAng = this.wAng;
  9790. if (!this._cachedTextureMatrix) {
  9791. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9792. this._rowGenerationMatrix = new BABYLON.Matrix();
  9793. this._t0 = BABYLON.Vector3.Zero();
  9794. this._t1 = BABYLON.Vector3.Zero();
  9795. this._t2 = BABYLON.Vector3.Zero();
  9796. }
  9797. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9798. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9799. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9800. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9801. this._t1.subtractInPlace(this._t0);
  9802. this._t2.subtractInPlace(this._t0);
  9803. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9804. this._cachedTextureMatrix.m[0] = this._t1.x;
  9805. this._cachedTextureMatrix.m[1] = this._t1.y;
  9806. this._cachedTextureMatrix.m[2] = this._t1.z;
  9807. this._cachedTextureMatrix.m[4] = this._t2.x;
  9808. this._cachedTextureMatrix.m[5] = this._t2.y;
  9809. this._cachedTextureMatrix.m[6] = this._t2.z;
  9810. this._cachedTextureMatrix.m[8] = this._t0.x;
  9811. this._cachedTextureMatrix.m[9] = this._t0.y;
  9812. this._cachedTextureMatrix.m[10] = this._t0.z;
  9813. return this._cachedTextureMatrix;
  9814. };
  9815. Texture.prototype.getReflectionTextureMatrix = function () {
  9816. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9817. return this._cachedTextureMatrix;
  9818. }
  9819. if (!this._cachedTextureMatrix) {
  9820. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9821. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9822. }
  9823. switch (this.coordinatesMode) {
  9824. case BABYLON.Texture.SPHERICAL_MODE:
  9825. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9826. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9827. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9828. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9829. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9830. break;
  9831. case BABYLON.Texture.PLANAR_MODE:
  9832. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9833. this._cachedTextureMatrix[0] = this.uScale;
  9834. this._cachedTextureMatrix[5] = this.vScale;
  9835. this._cachedTextureMatrix[12] = this.uOffset;
  9836. this._cachedTextureMatrix[13] = this.vOffset;
  9837. break;
  9838. case BABYLON.Texture.PROJECTION_MODE:
  9839. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9840. this._projectionModeMatrix.m[0] = 0.5;
  9841. this._projectionModeMatrix.m[5] = -0.5;
  9842. this._projectionModeMatrix.m[10] = 0.0;
  9843. this._projectionModeMatrix.m[12] = 0.5;
  9844. this._projectionModeMatrix.m[13] = 0.5;
  9845. this._projectionModeMatrix.m[14] = 1.0;
  9846. this._projectionModeMatrix.m[15] = 1.0;
  9847. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9848. break;
  9849. default:
  9850. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9851. break;
  9852. }
  9853. return this._cachedTextureMatrix;
  9854. };
  9855. Texture.prototype.clone = function () {
  9856. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9857. newTexture.hasAlpha = this.hasAlpha;
  9858. newTexture.level = this.level;
  9859. newTexture.wrapU = this.wrapU;
  9860. newTexture.wrapV = this.wrapV;
  9861. newTexture.coordinatesIndex = this.coordinatesIndex;
  9862. newTexture.coordinatesMode = this.coordinatesMode;
  9863. newTexture.uOffset = this.uOffset;
  9864. newTexture.vOffset = this.vOffset;
  9865. newTexture.uScale = this.uScale;
  9866. newTexture.vScale = this.vScale;
  9867. newTexture.uAng = this.uAng;
  9868. newTexture.vAng = this.vAng;
  9869. newTexture.wAng = this.wAng;
  9870. return newTexture;
  9871. };
  9872. Texture.NEAREST_SAMPLINGMODE = 1;
  9873. Texture.BILINEAR_SAMPLINGMODE = 2;
  9874. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9875. Texture.EXPLICIT_MODE = 0;
  9876. Texture.SPHERICAL_MODE = 1;
  9877. Texture.PLANAR_MODE = 2;
  9878. Texture.CUBIC_MODE = 3;
  9879. Texture.PROJECTION_MODE = 4;
  9880. Texture.SKYBOX_MODE = 5;
  9881. Texture.CLAMP_ADDRESSMODE = 0;
  9882. Texture.WRAP_ADDRESSMODE = 1;
  9883. Texture.MIRROR_ADDRESSMODE = 2;
  9884. return Texture;
  9885. })(BABYLON.BaseTexture);
  9886. BABYLON.Texture = Texture;
  9887. })(BABYLON || (BABYLON = {}));
  9888. var __extends = this.__extends || function (d, b) {
  9889. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9890. function __() { this.constructor = d; }
  9891. __.prototype = b.prototype;
  9892. d.prototype = new __();
  9893. };
  9894. var BABYLON;
  9895. (function (BABYLON) {
  9896. var CubeTexture = (function (_super) {
  9897. __extends(CubeTexture, _super);
  9898. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9899. _super.call(this, scene);
  9900. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9901. this.name = rootUrl;
  9902. this.url = rootUrl;
  9903. this._noMipmap = noMipmap;
  9904. this.hasAlpha = false;
  9905. this._texture = this._getFromCache(rootUrl, noMipmap);
  9906. if (!extensions) {
  9907. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9908. }
  9909. this._extensions = extensions;
  9910. if (!this._texture) {
  9911. if (!scene.useDelayedTextureLoading) {
  9912. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9913. } else {
  9914. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9915. }
  9916. }
  9917. this.isCube = true;
  9918. this._textureMatrix = BABYLON.Matrix.Identity();
  9919. }
  9920. CubeTexture.prototype.clone = function () {
  9921. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9922. newTexture.level = this.level;
  9923. newTexture.wrapU = this.wrapU;
  9924. newTexture.wrapV = this.wrapV;
  9925. newTexture.coordinatesIndex = this.coordinatesIndex;
  9926. newTexture.coordinatesMode = this.coordinatesMode;
  9927. return newTexture;
  9928. };
  9929. CubeTexture.prototype.delayLoad = function () {
  9930. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9931. return;
  9932. }
  9933. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9934. this._texture = this._getFromCache(this.url, this._noMipmap);
  9935. if (!this._texture) {
  9936. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9937. }
  9938. };
  9939. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  9940. return this._textureMatrix;
  9941. };
  9942. return CubeTexture;
  9943. })(BABYLON.BaseTexture);
  9944. BABYLON.CubeTexture = CubeTexture;
  9945. })(BABYLON || (BABYLON = {}));
  9946. var __extends = this.__extends || function (d, b) {
  9947. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9948. function __() { this.constructor = d; }
  9949. __.prototype = b.prototype;
  9950. d.prototype = new __();
  9951. };
  9952. var BABYLON;
  9953. (function (BABYLON) {
  9954. var RenderTargetTexture = (function (_super) {
  9955. __extends(RenderTargetTexture, _super);
  9956. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  9957. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  9958. _super.call(this, null, scene, !generateMipMaps);
  9959. this.renderList = new Array();
  9960. this.renderParticles = true;
  9961. this.renderSprites = false;
  9962. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  9963. this._currentRefreshId = -1;
  9964. this._refreshRate = 1;
  9965. this.name = name;
  9966. this.isRenderTarget = true;
  9967. this._size = size;
  9968. this._generateMipMaps = generateMipMaps;
  9969. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  9970. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  9971. this._renderingManager = new BABYLON.RenderingManager(scene);
  9972. }
  9973. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  9974. this._currentRefreshId = -1;
  9975. };
  9976. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  9977. get: function () {
  9978. return this._refreshRate;
  9979. },
  9980. set: function (value) {
  9981. this._refreshRate = value;
  9982. this.resetRefreshCounter();
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. RenderTargetTexture.prototype._shouldRender = function () {
  9988. if (this._currentRefreshId === -1) {
  9989. this._currentRefreshId = 1;
  9990. return true;
  9991. }
  9992. if (this.refreshRate == this._currentRefreshId) {
  9993. this._currentRefreshId = 1;
  9994. return true;
  9995. }
  9996. this._currentRefreshId++;
  9997. return false;
  9998. };
  9999. RenderTargetTexture.prototype.isReady = function () {
  10000. if (!this.getScene().renderTargetsEnabled) {
  10001. return false;
  10002. }
  10003. return _super.prototype.isReady.call(this);
  10004. };
  10005. RenderTargetTexture.prototype.getRenderSize = function () {
  10006. return this._size;
  10007. };
  10008. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10009. get: function () {
  10010. return true;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. RenderTargetTexture.prototype.scale = function (ratio) {
  10016. var newSize = this._size * ratio;
  10017. this.resize(newSize, this._generateMipMaps);
  10018. };
  10019. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10020. this.releaseInternalTexture();
  10021. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10022. };
  10023. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10024. var scene = this.getScene();
  10025. var engine = scene.getEngine();
  10026. if (this._waitingRenderList) {
  10027. this.renderList = [];
  10028. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10029. var id = this._waitingRenderList[index];
  10030. this.renderList.push(scene.getMeshByID(id));
  10031. }
  10032. delete this._waitingRenderList;
  10033. }
  10034. if (!this.renderList) {
  10035. return;
  10036. }
  10037. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10038. engine.bindFramebuffer(this._texture);
  10039. }
  10040. engine.clear(scene.clearColor, true, true);
  10041. this._renderingManager.reset();
  10042. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10043. var mesh = this.renderList[meshIndex];
  10044. if (mesh) {
  10045. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10046. this.resetRefreshCounter();
  10047. continue;
  10048. }
  10049. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10050. mesh._activate(scene.getRenderId());
  10051. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10052. var subMesh = mesh.subMeshes[subIndex];
  10053. scene._activeVertices += subMesh.verticesCount;
  10054. this._renderingManager.dispatch(subMesh);
  10055. }
  10056. }
  10057. }
  10058. }
  10059. if (!this._doNotChangeAspectRatio) {
  10060. scene.updateTransformMatrix(true);
  10061. }
  10062. if (this.onBeforeRender) {
  10063. this.onBeforeRender();
  10064. }
  10065. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10066. if (useCameraPostProcess) {
  10067. scene.postProcessManager._finalizeFrame(false, this._texture);
  10068. }
  10069. if (this.onAfterRender) {
  10070. this.onAfterRender();
  10071. }
  10072. engine.unBindFramebuffer(this._texture);
  10073. if (!this._doNotChangeAspectRatio) {
  10074. scene.updateTransformMatrix(true);
  10075. }
  10076. };
  10077. RenderTargetTexture.prototype.clone = function () {
  10078. var textureSize = this.getSize();
  10079. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10080. newTexture.hasAlpha = this.hasAlpha;
  10081. newTexture.level = this.level;
  10082. newTexture.coordinatesMode = this.coordinatesMode;
  10083. newTexture.renderList = this.renderList.slice(0);
  10084. return newTexture;
  10085. };
  10086. return RenderTargetTexture;
  10087. })(BABYLON.Texture);
  10088. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10089. })(BABYLON || (BABYLON = {}));
  10090. var __extends = this.__extends || function (d, b) {
  10091. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10092. function __() { this.constructor = d; }
  10093. __.prototype = b.prototype;
  10094. d.prototype = new __();
  10095. };
  10096. var BABYLON;
  10097. (function (BABYLON) {
  10098. var ProceduralTexture = (function (_super) {
  10099. __extends(ProceduralTexture, _super);
  10100. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10101. _super.call(this, null, scene, !generateMipMaps);
  10102. this._currentRefreshId = -1;
  10103. this._refreshRate = 1;
  10104. this._vertexDeclaration = [2];
  10105. this._vertexStrideSize = 2 * 4;
  10106. this._uniforms = new Array();
  10107. this._samplers = new Array();
  10108. this._textures = new Array();
  10109. this._floats = new Array();
  10110. this._floatsArrays = {};
  10111. this._colors3 = new Array();
  10112. this._colors4 = new Array();
  10113. this._vectors2 = new Array();
  10114. this._vectors3 = new Array();
  10115. this._matrices = new Array();
  10116. scene._proceduralTextures.push(this);
  10117. this.name = name;
  10118. this.isRenderTarget = true;
  10119. this._size = size;
  10120. this._generateMipMaps = generateMipMaps;
  10121. this._fragment = fragment;
  10122. this._fallbackTexture = fallbackTexture;
  10123. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10124. var vertices = [];
  10125. vertices.push(1, 1);
  10126. vertices.push(-1, 1);
  10127. vertices.push(-1, -1);
  10128. vertices.push(1, -1);
  10129. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10130. var indices = [];
  10131. indices.push(0);
  10132. indices.push(1);
  10133. indices.push(2);
  10134. indices.push(0);
  10135. indices.push(2);
  10136. indices.push(3);
  10137. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10138. }
  10139. ProceduralTexture.prototype.isReady = function () {
  10140. var _this = this;
  10141. var engine = this.getScene().getEngine();
  10142. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10143. _this.releaseInternalTexture();
  10144. _this._texture = _this._fallbackTexture._texture;
  10145. _this._texture.references++;
  10146. });
  10147. return this._effect.isReady();
  10148. };
  10149. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10150. this._currentRefreshId = -1;
  10151. };
  10152. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10153. get: function () {
  10154. return this._refreshRate;
  10155. },
  10156. set: function (value) {
  10157. this._refreshRate = value;
  10158. this.resetRefreshCounter();
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. ProceduralTexture.prototype._shouldRender = function () {
  10164. if (!this.isReady() || !this._texture) {
  10165. return false;
  10166. }
  10167. if (this._currentRefreshId === -1) {
  10168. this._currentRefreshId = 1;
  10169. return true;
  10170. }
  10171. if (this.refreshRate == this._currentRefreshId) {
  10172. this._currentRefreshId = 1;
  10173. return true;
  10174. }
  10175. this._currentRefreshId++;
  10176. return false;
  10177. };
  10178. ProceduralTexture.prototype.getRenderSize = function () {
  10179. return this._size;
  10180. };
  10181. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10182. this.releaseInternalTexture();
  10183. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10184. };
  10185. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10186. if (this._uniforms.indexOf(uniformName) === -1) {
  10187. this._uniforms.push(uniformName);
  10188. }
  10189. };
  10190. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10191. if (this._samplers.indexOf(name) === -1) {
  10192. this._samplers.push(name);
  10193. }
  10194. this._textures[name] = texture;
  10195. return this;
  10196. };
  10197. ProceduralTexture.prototype.setFloat = function (name, value) {
  10198. this._checkUniform(name);
  10199. this._floats[name] = value;
  10200. return this;
  10201. };
  10202. ProceduralTexture.prototype.setFloats = function (name, value) {
  10203. this._checkUniform(name);
  10204. this._floatsArrays[name] = value;
  10205. return this;
  10206. };
  10207. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10208. this._checkUniform(name);
  10209. this._colors3[name] = value;
  10210. return this;
  10211. };
  10212. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10213. this._checkUniform(name);
  10214. this._colors4[name] = value;
  10215. return this;
  10216. };
  10217. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10218. this._checkUniform(name);
  10219. this._vectors2[name] = value;
  10220. return this;
  10221. };
  10222. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10223. this._checkUniform(name);
  10224. this._vectors3[name] = value;
  10225. return this;
  10226. };
  10227. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10228. this._checkUniform(name);
  10229. this._matrices[name] = value;
  10230. return this;
  10231. };
  10232. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10233. var scene = this.getScene();
  10234. var engine = scene.getEngine();
  10235. engine.bindFramebuffer(this._texture);
  10236. engine.clear(scene.clearColor, true, true);
  10237. engine.enableEffect(this._effect);
  10238. engine.setState(false);
  10239. for (var name in this._textures) {
  10240. this._effect.setTexture(name, this._textures[name]);
  10241. }
  10242. for (name in this._floats) {
  10243. this._effect.setFloat(name, this._floats[name]);
  10244. }
  10245. for (name in this._floatsArrays) {
  10246. this._effect.setArray(name, this._floatsArrays[name]);
  10247. }
  10248. for (name in this._colors3) {
  10249. this._effect.setColor3(name, this._colors3[name]);
  10250. }
  10251. for (name in this._colors4) {
  10252. var color = this._colors4[name];
  10253. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10254. }
  10255. for (name in this._vectors2) {
  10256. this._effect.setVector2(name, this._vectors2[name]);
  10257. }
  10258. for (name in this._vectors3) {
  10259. this._effect.setVector3(name, this._vectors3[name]);
  10260. }
  10261. for (name in this._matrices) {
  10262. this._effect.setMatrix(name, this._matrices[name]);
  10263. }
  10264. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10265. engine.draw(true, 0, 6);
  10266. engine.unBindFramebuffer(this._texture);
  10267. };
  10268. ProceduralTexture.prototype.clone = function () {
  10269. var textureSize = this.getSize();
  10270. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10271. newTexture.hasAlpha = this.hasAlpha;
  10272. newTexture.level = this.level;
  10273. newTexture.coordinatesMode = this.coordinatesMode;
  10274. return newTexture;
  10275. };
  10276. ProceduralTexture.prototype.dispose = function () {
  10277. var index = this.getScene()._proceduralTextures.indexOf(this);
  10278. if (index >= 0) {
  10279. this.getScene()._proceduralTextures.splice(index, 1);
  10280. }
  10281. _super.prototype.dispose.call(this);
  10282. };
  10283. return ProceduralTexture;
  10284. })(BABYLON.Texture);
  10285. BABYLON.ProceduralTexture = ProceduralTexture;
  10286. })(BABYLON || (BABYLON = {}));
  10287. var __extends = this.__extends || function (d, b) {
  10288. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10289. function __() { this.constructor = d; }
  10290. __.prototype = b.prototype;
  10291. d.prototype = new __();
  10292. };
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var WoodProceduralTexture = (function (_super) {
  10296. __extends(WoodProceduralTexture, _super);
  10297. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10298. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10299. this._ampScale = 100.0;
  10300. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  10301. this.updateShaderUniforms();
  10302. this.refreshRate = 0;
  10303. }
  10304. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10305. this.setFloat("ampScale", this._ampScale);
  10306. this.setColor3("woodColor", this._woodColor);
  10307. };
  10308. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10309. get: function () {
  10310. return this._ampScale;
  10311. },
  10312. set: function (value) {
  10313. this._ampScale = value;
  10314. this.updateShaderUniforms();
  10315. },
  10316. enumerable: true,
  10317. configurable: true
  10318. });
  10319. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  10320. get: function () {
  10321. return this._woodColor;
  10322. },
  10323. set: function (value) {
  10324. this._woodColor = value;
  10325. this.updateShaderUniforms();
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. return WoodProceduralTexture;
  10331. })(BABYLON.ProceduralTexture);
  10332. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10333. var FireProceduralTexture = (function (_super) {
  10334. __extends(FireProceduralTexture, _super);
  10335. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10336. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10337. this._time = 0.0;
  10338. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10339. this._shift = 1.6;
  10340. this._alpha = 1.0;
  10341. this._autoGenerateTime = true;
  10342. this._fireColors = FireProceduralTexture.RedFireColors;
  10343. this.updateShaderUniforms();
  10344. this.refreshRate = 1;
  10345. }
  10346. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10347. this.setFloat("iGlobalTime", this._time);
  10348. this.setVector2("speed", this._speed);
  10349. this.setFloat("shift", this._shift);
  10350. this.setFloat("alpha", this._alpha);
  10351. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10352. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10353. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10354. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10355. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10356. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10357. };
  10358. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10359. if (this._autoGenerateTime) {
  10360. this._time += this.getScene().getAnimationRatio() * 0.03;
  10361. this.updateShaderUniforms();
  10362. }
  10363. _super.prototype.render.call(this, useCameraPostProcess);
  10364. };
  10365. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10366. get: function () {
  10367. return [
  10368. [0.5, 0.0, 1.0],
  10369. [0.9, 0.0, 1.0],
  10370. [0.2, 0.0, 1.0],
  10371. [1.0, 0.9, 1.0],
  10372. [0.1, 0.1, 1.0],
  10373. [0.9, 0.9, 1.0]
  10374. ];
  10375. },
  10376. enumerable: true,
  10377. configurable: true
  10378. });
  10379. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10380. get: function () {
  10381. return [
  10382. [0.5, 1.0, 0.0],
  10383. [0.5, 1.0, 0.0],
  10384. [0.3, 0.4, 0.0],
  10385. [0.5, 1.0, 0.0],
  10386. [0.2, 0.0, 0.0],
  10387. [0.5, 1.0, 0.0]
  10388. ];
  10389. },
  10390. enumerable: true,
  10391. configurable: true
  10392. });
  10393. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10394. get: function () {
  10395. return [
  10396. [0.5, 0.0, 0.1],
  10397. [0.9, 0.0, 0.0],
  10398. [0.2, 0.0, 0.0],
  10399. [1.0, 0.9, 0.0],
  10400. [0.1, 0.1, 0.1],
  10401. [0.9, 0.9, 0.9]
  10402. ];
  10403. },
  10404. enumerable: true,
  10405. configurable: true
  10406. });
  10407. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10408. get: function () {
  10409. return [
  10410. [0.1, 0.0, 0.5],
  10411. [0.0, 0.0, 0.5],
  10412. [0.1, 0.0, 0.2],
  10413. [0.0, 0.0, 1.0],
  10414. [0.1, 0.2, 0.3],
  10415. [0.0, 0.2, 0.9]
  10416. ];
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10422. get: function () {
  10423. return this._fireColors;
  10424. },
  10425. set: function (value) {
  10426. this._fireColors = value;
  10427. this.updateShaderUniforms();
  10428. },
  10429. enumerable: true,
  10430. configurable: true
  10431. });
  10432. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10433. get: function () {
  10434. return this._time;
  10435. },
  10436. set: function (value) {
  10437. this._time = value;
  10438. this.updateShaderUniforms();
  10439. },
  10440. enumerable: true,
  10441. configurable: true
  10442. });
  10443. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10444. get: function () {
  10445. return this._speed;
  10446. },
  10447. set: function (value) {
  10448. this._speed = value;
  10449. this.updateShaderUniforms();
  10450. },
  10451. enumerable: true,
  10452. configurable: true
  10453. });
  10454. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10455. get: function () {
  10456. return this._shift;
  10457. },
  10458. set: function (value) {
  10459. this._shift = value;
  10460. this.updateShaderUniforms();
  10461. },
  10462. enumerable: true,
  10463. configurable: true
  10464. });
  10465. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10466. get: function () {
  10467. return this._alpha;
  10468. },
  10469. set: function (value) {
  10470. this._alpha = value;
  10471. this.updateShaderUniforms();
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. return FireProceduralTexture;
  10477. })(BABYLON.ProceduralTexture);
  10478. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10479. var CloudProceduralTexture = (function (_super) {
  10480. __extends(CloudProceduralTexture, _super);
  10481. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10482. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10483. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  10484. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  10485. this.updateShaderUniforms();
  10486. this.refreshRate = 0;
  10487. }
  10488. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  10489. this.setColor3("skyColor", this._skyColor);
  10490. this.setColor3("cloudColor", this._cloudColor);
  10491. };
  10492. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  10493. get: function () {
  10494. return this._skyColor;
  10495. },
  10496. set: function (value) {
  10497. this._skyColor = value;
  10498. this.updateShaderUniforms();
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  10504. get: function () {
  10505. return this._cloudColor;
  10506. },
  10507. set: function (value) {
  10508. this._cloudColor = value;
  10509. this.updateShaderUniforms();
  10510. },
  10511. enumerable: true,
  10512. configurable: true
  10513. });
  10514. return CloudProceduralTexture;
  10515. })(BABYLON.ProceduralTexture);
  10516. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10517. var GrassProceduralTexture = (function (_super) {
  10518. __extends(GrassProceduralTexture, _super);
  10519. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10520. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  10521. this.refreshRate = 0;
  10522. }
  10523. return GrassProceduralTexture;
  10524. })(BABYLON.ProceduralTexture);
  10525. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  10526. var RockProceduralTexture = (function (_super) {
  10527. __extends(RockProceduralTexture, _super);
  10528. function RockProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10529. _super.call(this, name, size, "rock", scene, fallbackTexture, generateMipMaps);
  10530. this.refreshRate = 0;
  10531. }
  10532. return RockProceduralTexture;
  10533. })(BABYLON.ProceduralTexture);
  10534. BABYLON.RockProceduralTexture = RockProceduralTexture;
  10535. var RoadProceduralTexture = (function (_super) {
  10536. __extends(RoadProceduralTexture, _super);
  10537. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10538. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  10539. this.refreshRate = 0;
  10540. }
  10541. return RoadProceduralTexture;
  10542. })(BABYLON.ProceduralTexture);
  10543. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  10544. })(BABYLON || (BABYLON = {}));
  10545. var __extends = this.__extends || function (d, b) {
  10546. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10547. function __() { this.constructor = d; }
  10548. __.prototype = b.prototype;
  10549. d.prototype = new __();
  10550. };
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. var MirrorTexture = (function (_super) {
  10554. __extends(MirrorTexture, _super);
  10555. function MirrorTexture(name, size, scene, generateMipMaps) {
  10556. var _this = this;
  10557. _super.call(this, name, size, scene, generateMipMaps, true);
  10558. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10559. this._transformMatrix = BABYLON.Matrix.Zero();
  10560. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10561. this.onBeforeRender = function () {
  10562. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10563. _this._savedViewMatrix = scene.getViewMatrix();
  10564. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10565. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10566. scene.clipPlane = _this.mirrorPlane;
  10567. scene.getEngine().cullBackFaces = false;
  10568. };
  10569. this.onAfterRender = function () {
  10570. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10571. scene.getEngine().cullBackFaces = true;
  10572. delete scene.clipPlane;
  10573. };
  10574. }
  10575. MirrorTexture.prototype.clone = function () {
  10576. var textureSize = this.getSize();
  10577. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10578. newTexture.hasAlpha = this.hasAlpha;
  10579. newTexture.level = this.level;
  10580. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10581. newTexture.renderList = this.renderList.slice(0);
  10582. return newTexture;
  10583. };
  10584. return MirrorTexture;
  10585. })(BABYLON.RenderTargetTexture);
  10586. BABYLON.MirrorTexture = MirrorTexture;
  10587. })(BABYLON || (BABYLON = {}));
  10588. var __extends = this.__extends || function (d, b) {
  10589. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10590. function __() { this.constructor = d; }
  10591. __.prototype = b.prototype;
  10592. d.prototype = new __();
  10593. };
  10594. var BABYLON;
  10595. (function (BABYLON) {
  10596. var DynamicTexture = (function (_super) {
  10597. __extends(DynamicTexture, _super);
  10598. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10599. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10600. _super.call(this, null, scene, !generateMipMaps);
  10601. this.name = name;
  10602. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10603. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10604. this._generateMipMaps = generateMipMaps;
  10605. if (options.getContext) {
  10606. this._canvas = options;
  10607. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10608. } else {
  10609. this._canvas = document.createElement("canvas");
  10610. if (options.width) {
  10611. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10612. } else {
  10613. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10614. }
  10615. }
  10616. var textureSize = this.getSize();
  10617. this._canvas.width = textureSize.width;
  10618. this._canvas.height = textureSize.height;
  10619. this._context = this._canvas.getContext("2d");
  10620. }
  10621. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10622. get: function () {
  10623. return true;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. DynamicTexture.prototype.scale = function (ratio) {
  10629. var textureSize = this.getSize();
  10630. textureSize.width *= ratio;
  10631. textureSize.height *= ratio;
  10632. this._canvas.width = textureSize.width;
  10633. this._canvas.height = textureSize.height;
  10634. this.releaseInternalTexture();
  10635. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10636. };
  10637. DynamicTexture.prototype.getContext = function () {
  10638. return this._context;
  10639. };
  10640. DynamicTexture.prototype.update = function (invertY) {
  10641. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10642. };
  10643. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10644. var size = this.getSize();
  10645. if (clearColor) {
  10646. this._context.fillStyle = clearColor;
  10647. this._context.fillRect(0, 0, size.width, size.height);
  10648. }
  10649. this._context.font = font;
  10650. if (x === null) {
  10651. var textSize = this._context.measureText(text);
  10652. x = (size.width - textSize.width) / 2;
  10653. }
  10654. this._context.fillStyle = color;
  10655. this._context.fillText(text, x, y);
  10656. this.update(invertY);
  10657. };
  10658. DynamicTexture.prototype.clone = function () {
  10659. var textureSize = this.getSize();
  10660. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10661. newTexture.hasAlpha = this.hasAlpha;
  10662. newTexture.level = this.level;
  10663. newTexture.wrapU = this.wrapU;
  10664. newTexture.wrapV = this.wrapV;
  10665. return newTexture;
  10666. };
  10667. return DynamicTexture;
  10668. })(BABYLON.Texture);
  10669. BABYLON.DynamicTexture = DynamicTexture;
  10670. })(BABYLON || (BABYLON = {}));
  10671. var __extends = this.__extends || function (d, b) {
  10672. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10673. function __() { this.constructor = d; }
  10674. __.prototype = b.prototype;
  10675. d.prototype = new __();
  10676. };
  10677. var BABYLON;
  10678. (function (BABYLON) {
  10679. var VideoTexture = (function (_super) {
  10680. __extends(VideoTexture, _super);
  10681. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10682. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10683. var _this = this;
  10684. _super.call(this, null, scene, !generateMipMaps, invertY);
  10685. this._autoLaunch = true;
  10686. this.name = name;
  10687. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10688. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10689. var requiredWidth = size.width || size;
  10690. var requiredHeight = size.height || size;
  10691. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10692. var textureSize = this.getSize();
  10693. this.video = document.createElement("video");
  10694. this.video.width = textureSize.width;
  10695. this.video.height = textureSize.height;
  10696. this.video.autoplay = false;
  10697. this.video.loop = true;
  10698. this.video.addEventListener("canplaythrough", function () {
  10699. if (_this._texture) {
  10700. _this._texture.isReady = true;
  10701. }
  10702. });
  10703. urls.forEach(function (url) {
  10704. var source = document.createElement("source");
  10705. source.src = url;
  10706. _this.video.appendChild(source);
  10707. });
  10708. this._lastUpdate = BABYLON.Tools.Now;
  10709. }
  10710. VideoTexture.prototype.update = function () {
  10711. if (this._autoLaunch) {
  10712. this._autoLaunch = false;
  10713. this.video.play();
  10714. }
  10715. var now = BABYLON.Tools.Now;
  10716. if (now - this._lastUpdate < 15) {
  10717. return false;
  10718. }
  10719. this._lastUpdate = now;
  10720. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10721. return true;
  10722. };
  10723. return VideoTexture;
  10724. })(BABYLON.Texture);
  10725. BABYLON.VideoTexture = VideoTexture;
  10726. })(BABYLON || (BABYLON = {}));
  10727. var BABYLON;
  10728. (function (BABYLON) {
  10729. var EffectFallbacks = (function () {
  10730. function EffectFallbacks() {
  10731. this._defines = {};
  10732. this._currentRank = 32;
  10733. this._maxRank = -1;
  10734. }
  10735. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10736. if (!this._defines[rank]) {
  10737. if (rank < this._currentRank) {
  10738. this._currentRank = rank;
  10739. }
  10740. if (rank > this._maxRank) {
  10741. this._maxRank = rank;
  10742. }
  10743. this._defines[rank] = new Array();
  10744. }
  10745. this._defines[rank].push(define);
  10746. };
  10747. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  10748. get: function () {
  10749. return this._currentRank <= this._maxRank;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. EffectFallbacks.prototype.reduce = function (currentDefines) {
  10755. var currentFallbacks = this._defines[this._currentRank];
  10756. for (var index = 0; index < currentFallbacks.length; index++) {
  10757. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  10758. }
  10759. this._currentRank++;
  10760. return currentDefines;
  10761. };
  10762. return EffectFallbacks;
  10763. })();
  10764. BABYLON.EffectFallbacks = EffectFallbacks;
  10765. var Effect = (function () {
  10766. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  10767. var _this = this;
  10768. this._isReady = false;
  10769. this._compilationError = "";
  10770. this._valueCache = [];
  10771. this._engine = engine;
  10772. this.name = baseName;
  10773. this.defines = defines;
  10774. this._uniformsNames = uniformsNames.concat(samplers);
  10775. this._samplers = samplers;
  10776. this._attributesNames = attributesNames;
  10777. this.onError = onError;
  10778. this.onCompiled = onCompiled;
  10779. var vertexSource;
  10780. var fragmentSource;
  10781. if (baseName.vertexElement) {
  10782. vertexSource = document.getElementById(baseName.vertexElement);
  10783. if (!vertexSource) {
  10784. vertexSource = baseName.vertexElement;
  10785. }
  10786. } else {
  10787. vertexSource = baseName.vertex || baseName;
  10788. }
  10789. if (baseName.fragmentElement) {
  10790. fragmentSource = document.getElementById(baseName.fragmentElement);
  10791. if (!fragmentSource) {
  10792. fragmentSource = baseName.fragmentElement;
  10793. }
  10794. } else {
  10795. fragmentSource = baseName.fragment || baseName;
  10796. }
  10797. this._loadVertexShader(vertexSource, function (vertexCode) {
  10798. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  10799. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  10800. });
  10801. });
  10802. }
  10803. Effect.prototype.isReady = function () {
  10804. return this._isReady;
  10805. };
  10806. Effect.prototype.getProgram = function () {
  10807. return this._program;
  10808. };
  10809. Effect.prototype.getAttributesNames = function () {
  10810. return this._attributesNames;
  10811. };
  10812. Effect.prototype.getAttributeLocation = function (index) {
  10813. return this._attributes[index];
  10814. };
  10815. Effect.prototype.getAttributeLocationByName = function (name) {
  10816. var index = this._attributesNames.indexOf(name);
  10817. return this._attributes[index];
  10818. };
  10819. Effect.prototype.getAttributesCount = function () {
  10820. return this._attributes.length;
  10821. };
  10822. Effect.prototype.getUniformIndex = function (uniformName) {
  10823. return this._uniformsNames.indexOf(uniformName);
  10824. };
  10825. Effect.prototype.getUniform = function (uniformName) {
  10826. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  10827. };
  10828. Effect.prototype.getSamplers = function () {
  10829. return this._samplers;
  10830. };
  10831. Effect.prototype.getCompilationError = function () {
  10832. return this._compilationError;
  10833. };
  10834. Effect.prototype._loadVertexShader = function (vertex, callback) {
  10835. if (vertex instanceof HTMLElement) {
  10836. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  10837. callback(vertexCode);
  10838. return;
  10839. }
  10840. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  10841. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  10842. return;
  10843. }
  10844. var vertexShaderUrl;
  10845. if (vertex[0] === ".") {
  10846. vertexShaderUrl = vertex;
  10847. } else {
  10848. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  10849. }
  10850. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  10851. };
  10852. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  10853. if (fragment instanceof HTMLElement) {
  10854. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  10855. callback(fragmentCode);
  10856. return;
  10857. }
  10858. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  10859. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  10860. return;
  10861. }
  10862. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  10863. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  10864. return;
  10865. }
  10866. var fragmentShaderUrl;
  10867. if (fragment[0] === ".") {
  10868. fragmentShaderUrl = fragment;
  10869. } else {
  10870. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  10871. }
  10872. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  10873. };
  10874. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  10875. try {
  10876. var engine = this._engine;
  10877. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  10878. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  10879. this._attributes = engine.getAttributes(this._program, attributesNames);
  10880. for (var index = 0; index < this._samplers.length; index++) {
  10881. var sampler = this.getUniform(this._samplers[index]);
  10882. if (sampler == null) {
  10883. this._samplers.splice(index, 1);
  10884. index--;
  10885. }
  10886. }
  10887. engine.bindSamplers(this);
  10888. this._isReady = true;
  10889. if (this.onCompiled) {
  10890. this.onCompiled(this);
  10891. }
  10892. } catch (e) {
  10893. if (e.message.indexOf("highp") !== -1) {
  10894. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  10895. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  10896. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10897. return;
  10898. }
  10899. if (fallbacks && fallbacks.isMoreFallbacks) {
  10900. defines = fallbacks.reduce(defines);
  10901. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  10902. } else {
  10903. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  10904. BABYLON.Tools.Error("Defines: " + defines);
  10905. BABYLON.Tools.Error("Error: " + e.message);
  10906. this._compilationError = e.message;
  10907. if (this.onError) {
  10908. this.onError(this, this._compilationError);
  10909. }
  10910. }
  10911. }
  10912. };
  10913. Effect.prototype._bindTexture = function (channel, texture) {
  10914. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  10915. };
  10916. Effect.prototype.setTexture = function (channel, texture) {
  10917. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  10918. };
  10919. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10920. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  10921. };
  10922. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  10923. if (!this._valueCache[uniformName]) {
  10924. this._valueCache[uniformName] = [x, y];
  10925. return;
  10926. }
  10927. this._valueCache[uniformName][0] = x;
  10928. this._valueCache[uniformName][1] = y;
  10929. };
  10930. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  10931. if (!this._valueCache[uniformName]) {
  10932. this._valueCache[uniformName] = [x, y, z];
  10933. return;
  10934. }
  10935. this._valueCache[uniformName][0] = x;
  10936. this._valueCache[uniformName][1] = y;
  10937. this._valueCache[uniformName][2] = z;
  10938. };
  10939. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  10940. if (!this._valueCache[uniformName]) {
  10941. this._valueCache[uniformName] = [x, y, z, w];
  10942. return;
  10943. }
  10944. this._valueCache[uniformName][0] = x;
  10945. this._valueCache[uniformName][1] = y;
  10946. this._valueCache[uniformName][2] = z;
  10947. this._valueCache[uniformName][3] = w;
  10948. };
  10949. Effect.prototype.setArray = function (uniformName, array) {
  10950. this._engine.setArray(this.getUniform(uniformName), array);
  10951. return this;
  10952. };
  10953. Effect.prototype.setMatrices = function (uniformName, matrices) {
  10954. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  10955. return this;
  10956. };
  10957. Effect.prototype.setMatrix = function (uniformName, matrix) {
  10958. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  10959. return this;
  10960. };
  10961. Effect.prototype.setFloat = function (uniformName, value) {
  10962. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  10963. return this;
  10964. this._valueCache[uniformName] = value;
  10965. this._engine.setFloat(this.getUniform(uniformName), value);
  10966. return this;
  10967. };
  10968. Effect.prototype.setBool = function (uniformName, bool) {
  10969. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  10970. return this;
  10971. this._valueCache[uniformName] = bool;
  10972. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  10973. return this;
  10974. };
  10975. Effect.prototype.setVector2 = function (uniformName, vector2) {
  10976. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  10977. return this;
  10978. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  10979. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  10980. return this;
  10981. };
  10982. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  10983. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  10984. return this;
  10985. this._cacheFloat2(uniformName, x, y);
  10986. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  10987. return this;
  10988. };
  10989. Effect.prototype.setVector3 = function (uniformName, vector3) {
  10990. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  10991. return this;
  10992. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  10993. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  10994. return this;
  10995. };
  10996. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  10997. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  10998. return this;
  10999. this._cacheFloat3(uniformName, x, y, z);
  11000. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11001. return this;
  11002. };
  11003. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11004. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  11005. return this;
  11006. this._cacheFloat4(uniformName, x, y, z, w);
  11007. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11008. return this;
  11009. };
  11010. Effect.prototype.setColor3 = function (uniformName, color3) {
  11011. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  11012. return this;
  11013. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11014. this._engine.setColor3(this.getUniform(uniformName), color3);
  11015. return this;
  11016. };
  11017. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11018. 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)
  11019. return this;
  11020. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11021. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11022. return this;
  11023. };
  11024. 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}",
  11025. 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}",
  11026. 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}",
  11027. 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}",
  11028. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11029. 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}",
  11030. 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}",
  11031. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n 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 diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11032. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  11033. 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}",
  11034. 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}",
  11035. 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}",
  11036. 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}",
  11037. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n\n float herbwidth = 8.0;\n\n vec3 dirt = vec3(0.32, 0.17, 0.09);\n vec3 herb = vec3(0.0, 0.39, 0.09);\n vec3 ground = dirt;\n\n herbwidth = floor(herbwidth - noise(vUV * 8.0 ));\n\n float ratioy = mod(floor(gl_FragCoord.y), herbwidth);\n float ratiox = mod(floor(gl_FragCoord.x), herbwidth);\n\n /*herb = herb * ratiox;\n dirt = dirt * ratioy;*/\n\n if (ratioy >= 0.0 && ratioy < herbwidth / fbm(vUV * 2.0))\n ground = herb;\n\n if (ratiox >= 0.0 && ratiox < herbwidth / 2.0)\n ground = herb;\n\n gl_FragColor = vec4(ground, 1.0);\n}",
  11038. 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}",
  11039. 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}",
  11040. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n diffuseColor *= vColor;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11041. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec3 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec3 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  11042. 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}",
  11043. 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}",
  11044. 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}",
  11045. 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}",
  11046. 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}",
  11047. 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}",
  11048. 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}",
  11049. 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}",
  11050. 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}",
  11051. 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}",
  11052. 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}",
  11053. 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}",
  11054. rockPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform float ringScale;\nuniform vec3 woodColor1;\nuniform vec3 woodColor2;\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\n\n\nvoid main(void) {\n\n\n /*vec3 rock = vec3(0.53, 0.53, 0.53);\n vec3 roll = vec3(0.18, 0.18, 0.18);\n\n float ratioy = mod(vUV.y * 50.0, fbm(vUV * 8.0));\n\n rock = rock * ratioy;\n roll = roll * ratioy;\n\n vec3 stone = mix(rock, roll, 0.5);\n\n\n gl_FragColor = vec4(stone, 1.0);*/\n\n\n /* voronoi.frag */\n\n\n vec2 seeds[16];\n vec3 colors[16];\n\n colors[0] = vec3(0.53, 0.53, 0.53);\n colors[1] = vec3(0.28, 0.28, 0.28);\n colors[2] = vec3(0.23, 0.23, 0.23);\n colors[3] = vec3(0.38, 0.38, 0.38);\n colors[4] = vec3(0.63, 0.63, 0.63);\n colors[5] = vec3(0.78, 0.78, 0.78);\n colors[6] = vec3(0.93, 0.93, 0.93);\n colors[7] = vec3(0.73, 0.73, 0.73);\n colors[8] = vec3(0.43, 0.43, 0.43);\n colors[9] = vec3(0.11, 0.11, 0.11);\n colors[10] = vec3(0.12, 0.12, 0.12);\n colors[11] = vec3(0.64, 0.64, 0.64);\n colors[12] = vec3(0.79, 0.79, 0.79);\n colors[13] = vec3(0.43, 0.43, 0.43);\n colors[14] = vec3(0.21, 0.21, 0.21);\n colors[15] = vec3(0.37, 0.37, 0.37);\n\n seeds[0] = vec2(0.1, 0.9);\n seeds[1] = vec2(0.2, 0.8);\n seeds[2] = vec2(0.3, 0.7);\n seeds[3] = vec2(0.4, 0.4);\n seeds[4] = vec2(0.5, 0.5);\n seeds[5] = vec2(0.6, 0.3);\n seeds[6] = vec2(0.7, 0.2);\n seeds[7] = vec2(0.8, 0.3);\n seeds[8] = vec2(0.9, 0.4);\n seeds[9] = vec2(1.0, 0.3);\n seeds[10] = vec2(0.5, 0.4);\n seeds[11] = vec2(0.7, 0.8);\n seeds[12] = vec2(0.5, 0.3);\n seeds[13] = vec2(0.7, 0.7);\n seeds[14] = vec2(0.3, 0.3);\n seeds[15] = vec2(0.7, 0.7);\n\n float dist = distance(seeds[0], vPosition);\n vec3 color = colors[0];\n\n float hotpoint = 1.0;\n float current = 1.0;\n for (int i = 1; i < 16; i++) {\n current = distance(seeds[i], vPosition);\n if (current < dist) {\n hotpoint++;\n color = colors[i];\n dist = current;\n }\n }\n\n if (hotpoint > 3.0)\n color = mix(vec3(0.39, 0.32, 0), color, 1.0 / hotpoint);\n\n gl_FragColor = vec4(color, 1.0);\n\n\n\n}",
  11055. 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}",
  11056. 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}",
  11057. 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}",
  11058. 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}",
  11059. 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}",
  11060. };
  11061. return Effect;
  11062. })();
  11063. BABYLON.Effect = Effect;
  11064. })(BABYLON || (BABYLON = {}));
  11065. var BABYLON;
  11066. (function (BABYLON) {
  11067. var Material = (function () {
  11068. function Material(name, scene, doNotAdd) {
  11069. this.name = name;
  11070. this.checkReadyOnEveryCall = true;
  11071. this.checkReadyOnlyOnce = false;
  11072. this.state = "";
  11073. this.alpha = 1.0;
  11074. this.backFaceCulling = true;
  11075. this._wasPreviouslyReady = false;
  11076. this._fillMode = Material.TriangleFillMode;
  11077. this.pointSize = 1.0;
  11078. this.id = name;
  11079. this._scene = scene;
  11080. if (!doNotAdd) {
  11081. scene.materials.push(this);
  11082. }
  11083. }
  11084. Object.defineProperty(Material, "TriangleFillMode", {
  11085. get: function () {
  11086. return Material._TriangleFillMode;
  11087. },
  11088. enumerable: true,
  11089. configurable: true
  11090. });
  11091. Object.defineProperty(Material, "WireFrameFillMode", {
  11092. get: function () {
  11093. return Material._WireFrameFillMode;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(Material, "PointFillMode", {
  11099. get: function () {
  11100. return Material._PointFillMode;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Material.prototype, "wireframe", {
  11106. get: function () {
  11107. return this._fillMode === Material.WireFrameFillMode;
  11108. },
  11109. set: function (value) {
  11110. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Material.prototype, "pointsCloud", {
  11116. get: function () {
  11117. return this._fillMode === Material.PointFillMode;
  11118. },
  11119. set: function (value) {
  11120. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Material.prototype, "fillMode", {
  11126. get: function () {
  11127. return this._fillMode;
  11128. },
  11129. set: function (value) {
  11130. this._fillMode = value;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. Material.prototype.isReady = function (mesh, useInstances) {
  11136. return true;
  11137. };
  11138. Material.prototype.getEffect = function () {
  11139. return this._effect;
  11140. };
  11141. Material.prototype.getScene = function () {
  11142. return this._scene;
  11143. };
  11144. Material.prototype.needAlphaBlending = function () {
  11145. return (this.alpha < 1.0);
  11146. };
  11147. Material.prototype.needAlphaTesting = function () {
  11148. return false;
  11149. };
  11150. Material.prototype.getAlphaTestTexture = function () {
  11151. return null;
  11152. };
  11153. Material.prototype.trackCreation = function (onCompiled, onError) {
  11154. };
  11155. Material.prototype._preBind = function () {
  11156. var engine = this._scene.getEngine();
  11157. engine.enableEffect(this._effect);
  11158. engine.setState(this.backFaceCulling);
  11159. };
  11160. Material.prototype.bind = function (world, mesh) {
  11161. };
  11162. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11163. };
  11164. Material.prototype.unbind = function () {
  11165. };
  11166. Material.prototype.dispose = function (forceDisposeEffect) {
  11167. var index = this._scene.materials.indexOf(this);
  11168. this._scene.materials.splice(index, 1);
  11169. if (forceDisposeEffect && this._effect) {
  11170. this._scene.getEngine()._releaseEffect(this._effect);
  11171. this._effect = null;
  11172. }
  11173. if (this.onDispose) {
  11174. this.onDispose();
  11175. }
  11176. };
  11177. Material._TriangleFillMode = 0;
  11178. Material._WireFrameFillMode = 1;
  11179. Material._PointFillMode = 2;
  11180. return Material;
  11181. })();
  11182. BABYLON.Material = Material;
  11183. })(BABYLON || (BABYLON = {}));
  11184. var __extends = this.__extends || function (d, b) {
  11185. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11186. function __() { this.constructor = d; }
  11187. __.prototype = b.prototype;
  11188. d.prototype = new __();
  11189. };
  11190. var BABYLON;
  11191. (function (BABYLON) {
  11192. var maxSimultaneousLights = 4;
  11193. var FresnelParameters = (function () {
  11194. function FresnelParameters() {
  11195. this.isEnabled = true;
  11196. this.leftColor = BABYLON.Color3.White();
  11197. this.rightColor = BABYLON.Color3.Black();
  11198. this.bias = 0;
  11199. this.power = 1;
  11200. }
  11201. return FresnelParameters;
  11202. })();
  11203. BABYLON.FresnelParameters = FresnelParameters;
  11204. var StandardMaterial = (function (_super) {
  11205. __extends(StandardMaterial, _super);
  11206. function StandardMaterial(name, scene) {
  11207. var _this = this;
  11208. _super.call(this, name, scene);
  11209. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11210. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11211. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11212. this.specularPower = 64;
  11213. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11214. this.useAlphaFromDiffuseTexture = false;
  11215. this.useSpecularOverAlpha = true;
  11216. this.fogEnabled = true;
  11217. this._cachedDefines = null;
  11218. this._renderTargets = new BABYLON.SmartArray(16);
  11219. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11220. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11221. this._scaledDiffuse = new BABYLON.Color3();
  11222. this._scaledSpecular = new BABYLON.Color3();
  11223. this.getRenderTargetTextures = function () {
  11224. _this._renderTargets.reset();
  11225. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11226. _this._renderTargets.push(_this.reflectionTexture);
  11227. }
  11228. return _this._renderTargets;
  11229. };
  11230. }
  11231. StandardMaterial.prototype.needAlphaBlending = function () {
  11232. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11233. };
  11234. StandardMaterial.prototype.needAlphaTesting = function () {
  11235. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11236. };
  11237. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11238. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11239. };
  11240. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11241. return this.diffuseTexture;
  11242. };
  11243. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11244. if (this.checkReadyOnlyOnce) {
  11245. if (this._wasPreviouslyReady) {
  11246. return true;
  11247. }
  11248. }
  11249. var scene = this.getScene();
  11250. if (!this.checkReadyOnEveryCall) {
  11251. if (this._renderId === scene.getRenderId()) {
  11252. return true;
  11253. }
  11254. }
  11255. var engine = scene.getEngine();
  11256. var defines = [];
  11257. var fallbacks = new BABYLON.EffectFallbacks();
  11258. if (scene.texturesEnabled) {
  11259. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11260. if (!this.diffuseTexture.isReady()) {
  11261. return false;
  11262. } else {
  11263. defines.push("#define DIFFUSE");
  11264. }
  11265. }
  11266. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11267. if (!this.ambientTexture.isReady()) {
  11268. return false;
  11269. } else {
  11270. defines.push("#define AMBIENT");
  11271. }
  11272. }
  11273. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11274. if (!this.opacityTexture.isReady()) {
  11275. return false;
  11276. } else {
  11277. defines.push("#define OPACITY");
  11278. if (this.opacityTexture.getAlphaFromRGB) {
  11279. defines.push("#define OPACITYRGB");
  11280. }
  11281. }
  11282. }
  11283. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11284. if (!this.reflectionTexture.isReady()) {
  11285. return false;
  11286. } else {
  11287. defines.push("#define REFLECTION");
  11288. fallbacks.addFallback(0, "REFLECTION");
  11289. }
  11290. }
  11291. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11292. if (!this.emissiveTexture.isReady()) {
  11293. return false;
  11294. } else {
  11295. defines.push("#define EMISSIVE");
  11296. }
  11297. }
  11298. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11299. if (!this.specularTexture.isReady()) {
  11300. return false;
  11301. } else {
  11302. defines.push("#define SPECULAR");
  11303. fallbacks.addFallback(0, "SPECULAR");
  11304. }
  11305. }
  11306. }
  11307. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11308. if (!this.bumpTexture.isReady()) {
  11309. return false;
  11310. } else {
  11311. defines.push("#define BUMP");
  11312. fallbacks.addFallback(0, "BUMP");
  11313. }
  11314. }
  11315. if (this.useSpecularOverAlpha) {
  11316. defines.push("#define SPECULAROVERALPHA");
  11317. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11318. }
  11319. if (scene.clipPlane) {
  11320. defines.push("#define CLIPPLANE");
  11321. }
  11322. if (engine.getAlphaTesting()) {
  11323. defines.push("#define ALPHATEST");
  11324. }
  11325. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11326. defines.push("#define ALPHAFROMDIFFUSE");
  11327. }
  11328. if (this.pointsCloud) {
  11329. defines.push("#define POINTSIZE");
  11330. }
  11331. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11332. defines.push("#define FOG");
  11333. fallbacks.addFallback(1, "FOG");
  11334. }
  11335. var shadowsActivated = false;
  11336. var lightIndex = 0;
  11337. if (scene.lightsEnabled) {
  11338. for (var index = 0; index < scene.lights.length; index++) {
  11339. var light = scene.lights[index];
  11340. if (!light.isEnabled()) {
  11341. continue;
  11342. }
  11343. if (light._excludedMeshesIds.length > 0) {
  11344. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11345. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11346. if (excludedMesh) {
  11347. light.excludedMeshes.push(excludedMesh);
  11348. }
  11349. }
  11350. light._excludedMeshesIds = [];
  11351. }
  11352. if (light._includedOnlyMeshesIds.length > 0) {
  11353. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11354. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11355. if (includedOnlyMesh) {
  11356. light.includedOnlyMeshes.push(includedOnlyMesh);
  11357. }
  11358. }
  11359. light._includedOnlyMeshesIds = [];
  11360. }
  11361. if (!light.canAffectMesh(mesh)) {
  11362. continue;
  11363. }
  11364. defines.push("#define LIGHT" + lightIndex);
  11365. if (lightIndex > 0) {
  11366. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11367. }
  11368. var type;
  11369. if (light instanceof BABYLON.SpotLight) {
  11370. type = "#define SPOTLIGHT" + lightIndex;
  11371. } else if (light instanceof BABYLON.HemisphericLight) {
  11372. type = "#define HEMILIGHT" + lightIndex;
  11373. } else {
  11374. type = "#define POINTDIRLIGHT" + lightIndex;
  11375. }
  11376. defines.push(type);
  11377. if (lightIndex > 0) {
  11378. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11379. }
  11380. if (scene.shadowsEnabled) {
  11381. var shadowGenerator = light.getShadowGenerator();
  11382. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11383. defines.push("#define SHADOW" + lightIndex);
  11384. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11385. if (!shadowsActivated) {
  11386. defines.push("#define SHADOWS");
  11387. shadowsActivated = true;
  11388. }
  11389. if (shadowGenerator.useVarianceShadowMap) {
  11390. defines.push("#define SHADOWVSM" + lightIndex);
  11391. if (lightIndex > 0) {
  11392. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11393. }
  11394. }
  11395. if (shadowGenerator.usePoissonSampling) {
  11396. defines.push("#define SHADOWPCF" + lightIndex);
  11397. if (lightIndex > 0) {
  11398. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11399. }
  11400. }
  11401. }
  11402. }
  11403. lightIndex++;
  11404. if (lightIndex == maxSimultaneousLights)
  11405. break;
  11406. }
  11407. }
  11408. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11409. var fresnelRank = 1;
  11410. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11411. defines.push("#define DIFFUSEFRESNEL");
  11412. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11413. fresnelRank++;
  11414. }
  11415. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11416. defines.push("#define OPACITYFRESNEL");
  11417. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11418. fresnelRank++;
  11419. }
  11420. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11421. defines.push("#define REFLECTIONFRESNEL");
  11422. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11423. fresnelRank++;
  11424. }
  11425. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11426. defines.push("#define EMISSIVEFRESNEL");
  11427. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11428. fresnelRank++;
  11429. }
  11430. defines.push("#define FRESNEL");
  11431. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11432. }
  11433. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11434. if (mesh) {
  11435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11436. attribs.push(BABYLON.VertexBuffer.UVKind);
  11437. defines.push("#define UV1");
  11438. }
  11439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11441. defines.push("#define UV2");
  11442. }
  11443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11444. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11445. defines.push("#define VERTEXCOLOR");
  11446. }
  11447. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11450. defines.push("#define BONES");
  11451. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11452. defines.push("#define BONES4");
  11453. fallbacks.addFallback(0, "BONES4");
  11454. }
  11455. if (useInstances) {
  11456. defines.push("#define INSTANCES");
  11457. attribs.push("world0");
  11458. attribs.push("world1");
  11459. attribs.push("world2");
  11460. attribs.push("world3");
  11461. }
  11462. }
  11463. var join = defines.join("\n");
  11464. if (this._cachedDefines != join) {
  11465. this._cachedDefines = join;
  11466. var shaderName = "default";
  11467. if (!scene.getEngine().getCaps().standardDerivatives) {
  11468. shaderName = "legacydefault";
  11469. }
  11470. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11471. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11472. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11473. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11474. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11475. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11476. "vFogInfos", "vFogColor", "pointSize",
  11477. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11478. "mBones",
  11479. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11480. "darkness0", "darkness1", "darkness2", "darkness3",
  11481. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11482. ], [
  11483. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11484. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11485. ], join, fallbacks, this.onCompiled, this.onError);
  11486. }
  11487. if (!this._effect.isReady()) {
  11488. return false;
  11489. }
  11490. this._renderId = scene.getRenderId();
  11491. this._wasPreviouslyReady = true;
  11492. return true;
  11493. };
  11494. StandardMaterial.prototype.unbind = function () {
  11495. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11496. this._effect.setTexture("reflection2DSampler", null);
  11497. }
  11498. };
  11499. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11500. this._effect.setMatrix("world", world);
  11501. };
  11502. StandardMaterial.prototype.bind = function (world, mesh) {
  11503. var scene = this.getScene();
  11504. this.bindOnlyWorldMatrix(world);
  11505. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11506. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11507. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11508. }
  11509. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11510. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11511. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11512. }
  11513. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11514. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11515. }
  11516. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11517. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11518. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11519. }
  11520. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11521. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11522. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11523. }
  11524. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11525. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11526. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11527. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11528. }
  11529. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11530. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11531. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11532. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11533. }
  11534. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11535. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11536. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11537. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11538. }
  11539. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11540. if (this.reflectionTexture.isCube) {
  11541. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11542. } else {
  11543. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11544. }
  11545. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11546. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11547. }
  11548. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11549. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11550. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11551. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11552. }
  11553. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11554. this._effect.setTexture("specularSampler", this.specularTexture);
  11555. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11556. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11557. }
  11558. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11559. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11560. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11561. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11562. }
  11563. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11564. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11565. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11566. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11567. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11568. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11569. if (scene.lightsEnabled) {
  11570. var lightIndex = 0;
  11571. for (var index = 0; index < scene.lights.length; index++) {
  11572. var light = scene.lights[index];
  11573. if (!light.isEnabled()) {
  11574. continue;
  11575. }
  11576. if (!light.canAffectMesh(mesh)) {
  11577. continue;
  11578. }
  11579. if (light instanceof BABYLON.PointLight) {
  11580. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11581. } else if (light instanceof BABYLON.DirectionalLight) {
  11582. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11583. } else if (light instanceof BABYLON.SpotLight) {
  11584. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11585. } else if (light instanceof BABYLON.HemisphericLight) {
  11586. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11587. }
  11588. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11589. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11590. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11591. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11592. if (scene.shadowsEnabled) {
  11593. var shadowGenerator = light.getShadowGenerator();
  11594. if (mesh.receiveShadows && shadowGenerator) {
  11595. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11596. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11597. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11598. }
  11599. }
  11600. lightIndex++;
  11601. if (lightIndex == maxSimultaneousLights)
  11602. break;
  11603. }
  11604. }
  11605. if (scene.clipPlane) {
  11606. var clipPlane = scene.clipPlane;
  11607. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11608. }
  11609. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11610. this._effect.setMatrix("view", scene.getViewMatrix());
  11611. }
  11612. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11613. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11614. this._effect.setColor3("vFogColor", scene.fogColor);
  11615. }
  11616. if (this.pointsCloud) {
  11617. this._effect.setFloat("pointSize", this.pointSize);
  11618. }
  11619. };
  11620. StandardMaterial.prototype.getAnimatables = function () {
  11621. var results = [];
  11622. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11623. results.push(this.diffuseTexture);
  11624. }
  11625. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11626. results.push(this.ambientTexture);
  11627. }
  11628. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11629. results.push(this.opacityTexture);
  11630. }
  11631. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11632. results.push(this.reflectionTexture);
  11633. }
  11634. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11635. results.push(this.emissiveTexture);
  11636. }
  11637. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11638. results.push(this.specularTexture);
  11639. }
  11640. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11641. results.push(this.bumpTexture);
  11642. }
  11643. return results;
  11644. };
  11645. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11646. if (this.diffuseTexture) {
  11647. this.diffuseTexture.dispose();
  11648. }
  11649. if (this.ambientTexture) {
  11650. this.ambientTexture.dispose();
  11651. }
  11652. if (this.opacityTexture) {
  11653. this.opacityTexture.dispose();
  11654. }
  11655. if (this.reflectionTexture) {
  11656. this.reflectionTexture.dispose();
  11657. }
  11658. if (this.emissiveTexture) {
  11659. this.emissiveTexture.dispose();
  11660. }
  11661. if (this.specularTexture) {
  11662. this.specularTexture.dispose();
  11663. }
  11664. if (this.bumpTexture) {
  11665. this.bumpTexture.dispose();
  11666. }
  11667. _super.prototype.dispose.call(this, forceDisposeEffect);
  11668. };
  11669. StandardMaterial.prototype.clone = function (name) {
  11670. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11671. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11672. newStandardMaterial.alpha = this.alpha;
  11673. newStandardMaterial.fillMode = this.fillMode;
  11674. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11675. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11676. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11677. }
  11678. if (this.ambientTexture && this.ambientTexture.clone) {
  11679. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11680. }
  11681. if (this.opacityTexture && this.opacityTexture.clone) {
  11682. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11683. }
  11684. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11685. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11686. }
  11687. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11688. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11689. }
  11690. if (this.specularTexture && this.specularTexture.clone) {
  11691. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11692. }
  11693. if (this.bumpTexture && this.bumpTexture.clone) {
  11694. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11695. }
  11696. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11697. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11698. newStandardMaterial.specularColor = this.specularColor.clone();
  11699. newStandardMaterial.specularPower = this.specularPower;
  11700. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11701. return newStandardMaterial;
  11702. };
  11703. StandardMaterial.DiffuseTextureEnabled = true;
  11704. StandardMaterial.AmbientTextureEnabled = true;
  11705. StandardMaterial.OpacityTextureEnabled = true;
  11706. StandardMaterial.ReflectionTextureEnabled = true;
  11707. StandardMaterial.EmissiveTextureEnabled = true;
  11708. StandardMaterial.SpecularTextureEnabled = true;
  11709. StandardMaterial.BumpTextureEnabled = true;
  11710. return StandardMaterial;
  11711. })(BABYLON.Material);
  11712. BABYLON.StandardMaterial = StandardMaterial;
  11713. })(BABYLON || (BABYLON = {}));
  11714. var __extends = this.__extends || function (d, b) {
  11715. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11716. function __() { this.constructor = d; }
  11717. __.prototype = b.prototype;
  11718. d.prototype = new __();
  11719. };
  11720. var BABYLON;
  11721. (function (BABYLON) {
  11722. var MultiMaterial = (function (_super) {
  11723. __extends(MultiMaterial, _super);
  11724. function MultiMaterial(name, scene) {
  11725. _super.call(this, name, scene, true);
  11726. this.subMaterials = new Array();
  11727. scene.multiMaterials.push(this);
  11728. }
  11729. MultiMaterial.prototype.getSubMaterial = function (index) {
  11730. if (index < 0 || index >= this.subMaterials.length) {
  11731. return this.getScene().defaultMaterial;
  11732. }
  11733. return this.subMaterials[index];
  11734. };
  11735. MultiMaterial.prototype.isReady = function (mesh) {
  11736. for (var index = 0; index < this.subMaterials.length; index++) {
  11737. var subMaterial = this.subMaterials[index];
  11738. if (subMaterial) {
  11739. if (!this.subMaterials[index].isReady(mesh)) {
  11740. return false;
  11741. }
  11742. }
  11743. }
  11744. return true;
  11745. };
  11746. return MultiMaterial;
  11747. })(BABYLON.Material);
  11748. BABYLON.MultiMaterial = MultiMaterial;
  11749. })(BABYLON || (BABYLON = {}));
  11750. var BABYLON;
  11751. (function (BABYLON) {
  11752. var Database = (function () {
  11753. function Database(urlToScene, callbackManifestChecked) {
  11754. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  11755. this.callbackManifestChecked = callbackManifestChecked;
  11756. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  11757. this.db = null;
  11758. this.enableSceneOffline = false;
  11759. this.enableTexturesOffline = false;
  11760. this.manifestVersionFound = 0;
  11761. this.mustUpdateRessources = false;
  11762. this.hasReachedQuota = false;
  11763. this.checkManifestFile();
  11764. }
  11765. Database.prototype.checkManifestFile = function () {
  11766. var _this = this;
  11767. function noManifestFile() {
  11768. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  11769. that.enableSceneOffline = false;
  11770. that.enableTexturesOffline = false;
  11771. that.callbackManifestChecked(false);
  11772. }
  11773. var that = this;
  11774. var manifestURL = this.currentSceneUrl + ".manifest";
  11775. var xhr = new XMLHttpRequest();
  11776. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  11777. xhr.open("GET", manifestURLTimeStamped, true);
  11778. xhr.addEventListener("load", function () {
  11779. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11780. try {
  11781. var manifestFile = JSON.parse(xhr.response);
  11782. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  11783. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  11784. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  11785. _this.manifestVersionFound = manifestFile.version;
  11786. }
  11787. if (_this.callbackManifestChecked) {
  11788. _this.callbackManifestChecked(true);
  11789. }
  11790. } catch (ex) {
  11791. noManifestFile();
  11792. }
  11793. } else {
  11794. noManifestFile();
  11795. }
  11796. }, false);
  11797. xhr.addEventListener("error", function (event) {
  11798. noManifestFile();
  11799. }, false);
  11800. try {
  11801. xhr.send();
  11802. } catch (ex) {
  11803. BABYLON.Tools.Error("Error on XHR send request.");
  11804. that.callbackManifestChecked(false);
  11805. }
  11806. };
  11807. Database.prototype.openAsync = function (successCallback, errorCallback) {
  11808. var _this = this;
  11809. function handleError() {
  11810. that.isSupported = false;
  11811. if (errorCallback)
  11812. errorCallback();
  11813. }
  11814. var that = this;
  11815. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  11816. this.isSupported = false;
  11817. if (errorCallback)
  11818. errorCallback();
  11819. } else {
  11820. if (!this.db) {
  11821. this.hasReachedQuota = false;
  11822. this.isSupported = true;
  11823. var request = this.idbFactory.open("babylonjs", 1);
  11824. request.onerror = function (event) {
  11825. handleError();
  11826. };
  11827. request.onblocked = function (event) {
  11828. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  11829. handleError();
  11830. };
  11831. request.onsuccess = function (event) {
  11832. _this.db = request.result;
  11833. successCallback();
  11834. };
  11835. request.onupgradeneeded = function (event) {
  11836. _this.db = (event.target).result;
  11837. try {
  11838. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  11839. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  11840. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  11841. } catch (ex) {
  11842. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  11843. handleError();
  11844. }
  11845. };
  11846. } else {
  11847. if (successCallback)
  11848. successCallback();
  11849. }
  11850. }
  11851. };
  11852. Database.prototype.loadImageFromDB = function (url, image) {
  11853. var _this = this;
  11854. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  11855. var saveAndLoadImage = function () {
  11856. if (!_this.hasReachedQuota && _this.db !== null) {
  11857. _this._saveImageIntoDBAsync(completeURL, image);
  11858. } else {
  11859. image.src = url;
  11860. }
  11861. };
  11862. if (!this.mustUpdateRessources) {
  11863. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  11864. } else {
  11865. saveAndLoadImage();
  11866. }
  11867. };
  11868. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  11869. if (this.isSupported && this.db !== null) {
  11870. var texture;
  11871. var transaction = this.db.transaction(["textures"]);
  11872. transaction.onabort = function (event) {
  11873. image.src = url;
  11874. };
  11875. transaction.oncomplete = function (event) {
  11876. var blobTextureURL;
  11877. if (texture) {
  11878. var URL = window.URL || window.webkitURL;
  11879. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  11880. image.onerror = function () {
  11881. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  11882. image.src = url;
  11883. };
  11884. image.src = blobTextureURL;
  11885. } else {
  11886. notInDBCallback();
  11887. }
  11888. };
  11889. var getRequest = transaction.objectStore("textures").get(url);
  11890. getRequest.onsuccess = function (event) {
  11891. texture = (event.target).result;
  11892. };
  11893. getRequest.onerror = function (event) {
  11894. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  11895. image.src = url;
  11896. };
  11897. } else {
  11898. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11899. image.src = url;
  11900. }
  11901. };
  11902. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  11903. var _this = this;
  11904. if (this.isSupported) {
  11905. var generateBlobUrl = function () {
  11906. var blobTextureURL;
  11907. if (blob) {
  11908. var URL = window.URL || window.webkitURL;
  11909. try {
  11910. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  11911. } catch (ex) {
  11912. blobTextureURL = URL.createObjectURL(blob);
  11913. }
  11914. }
  11915. image.src = blobTextureURL;
  11916. };
  11917. if (BABYLON.Database.isUASupportingBlobStorage) {
  11918. var xhr = new XMLHttpRequest(), blob;
  11919. xhr.open("GET", url, true);
  11920. xhr.responseType = "blob";
  11921. xhr.addEventListener("load", function () {
  11922. if (xhr.status === 200) {
  11923. blob = xhr.response;
  11924. var transaction = _this.db.transaction(["textures"], "readwrite");
  11925. transaction.onabort = function (event) {
  11926. try {
  11927. if (event.srcElement.error.name === "QuotaExceededError") {
  11928. this.hasReachedQuota = true;
  11929. }
  11930. } catch (ex) {
  11931. }
  11932. generateBlobUrl();
  11933. };
  11934. transaction.oncomplete = function (event) {
  11935. generateBlobUrl();
  11936. };
  11937. var newTexture = { textureUrl: url, data: blob };
  11938. try {
  11939. var addRequest = transaction.objectStore("textures").put(newTexture);
  11940. addRequest.onsuccess = function (event) {
  11941. };
  11942. addRequest.onerror = function (event) {
  11943. generateBlobUrl();
  11944. };
  11945. } catch (ex) {
  11946. if (ex.code === 25) {
  11947. BABYLON.Database.isUASupportingBlobStorage = false;
  11948. }
  11949. image.src = url;
  11950. }
  11951. } else {
  11952. image.src = url;
  11953. }
  11954. }, false);
  11955. xhr.addEventListener("error", function (event) {
  11956. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  11957. image.src = url;
  11958. }, false);
  11959. xhr.send();
  11960. } else {
  11961. image.src = url;
  11962. }
  11963. } else {
  11964. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  11965. image.src = url;
  11966. }
  11967. };
  11968. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  11969. var _this = this;
  11970. var updateVersion = function (event) {
  11971. _this._saveVersionIntoDBAsync(url, versionLoaded);
  11972. };
  11973. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  11974. };
  11975. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  11976. var _this = this;
  11977. if (this.isSupported) {
  11978. var version;
  11979. try {
  11980. var transaction = this.db.transaction(["versions"]);
  11981. transaction.oncomplete = function (event) {
  11982. if (version) {
  11983. if (_this.manifestVersionFound > version.data) {
  11984. _this.mustUpdateRessources = true;
  11985. updateInDBCallback();
  11986. } else {
  11987. callback(version.data);
  11988. }
  11989. } else {
  11990. _this.mustUpdateRessources = true;
  11991. updateInDBCallback();
  11992. }
  11993. };
  11994. transaction.onabort = function (event) {
  11995. callback(-1);
  11996. };
  11997. var getRequest = transaction.objectStore("versions").get(url);
  11998. getRequest.onsuccess = function (event) {
  11999. version = (event.target).result;
  12000. };
  12001. getRequest.onerror = function (event) {
  12002. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  12003. callback(-1);
  12004. };
  12005. } catch (ex) {
  12006. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  12007. callback(-1);
  12008. }
  12009. } else {
  12010. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12011. callback(-1);
  12012. }
  12013. };
  12014. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  12015. var _this = this;
  12016. if (this.isSupported && !this.hasReachedQuota) {
  12017. try {
  12018. var transaction = this.db.transaction(["versions"], "readwrite");
  12019. transaction.onabort = function (event) {
  12020. try {
  12021. if (event.srcElement.error.name === "QuotaExceededError") {
  12022. _this.hasReachedQuota = true;
  12023. }
  12024. } catch (ex) {
  12025. }
  12026. callback(-1);
  12027. };
  12028. transaction.oncomplete = function (event) {
  12029. callback(_this.manifestVersionFound);
  12030. };
  12031. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  12032. var addRequest = transaction.objectStore("versions").put(newVersion);
  12033. addRequest.onsuccess = function (event) {
  12034. };
  12035. addRequest.onerror = function (event) {
  12036. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  12037. };
  12038. } catch (ex) {
  12039. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  12040. callback(-1);
  12041. }
  12042. } else {
  12043. callback(-1);
  12044. }
  12045. };
  12046. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12047. var _this = this;
  12048. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12049. var saveAndLoadFile = function (event) {
  12050. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12051. };
  12052. this._checkVersionFromDB(completeUrl, function (version) {
  12053. if (version !== -1) {
  12054. if (!_this.mustUpdateRessources) {
  12055. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12056. } else {
  12057. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12058. }
  12059. } else {
  12060. errorCallback();
  12061. }
  12062. });
  12063. };
  12064. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12065. if (this.isSupported) {
  12066. var targetStore;
  12067. if (url.indexOf(".babylon") !== -1) {
  12068. targetStore = "scenes";
  12069. } else {
  12070. targetStore = "textures";
  12071. }
  12072. var file;
  12073. var transaction = this.db.transaction([targetStore]);
  12074. transaction.oncomplete = function (event) {
  12075. if (file) {
  12076. callback(file.data);
  12077. } else {
  12078. notInDBCallback();
  12079. }
  12080. };
  12081. transaction.onabort = function (event) {
  12082. notInDBCallback();
  12083. };
  12084. var getRequest = transaction.objectStore(targetStore).get(url);
  12085. getRequest.onsuccess = function (event) {
  12086. file = (event.target).result;
  12087. };
  12088. getRequest.onerror = function (event) {
  12089. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12090. notInDBCallback();
  12091. };
  12092. } else {
  12093. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12094. callback();
  12095. }
  12096. };
  12097. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12098. var _this = this;
  12099. if (this.isSupported) {
  12100. var targetStore;
  12101. if (url.indexOf(".babylon") !== -1) {
  12102. targetStore = "scenes";
  12103. } else {
  12104. targetStore = "textures";
  12105. }
  12106. var xhr = new XMLHttpRequest(), fileData;
  12107. xhr.open("GET", url, true);
  12108. if (useArrayBuffer) {
  12109. xhr.responseType = "arraybuffer";
  12110. }
  12111. xhr.onprogress = progressCallback;
  12112. xhr.addEventListener("load", function () {
  12113. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12114. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12115. if (!_this.hasReachedQuota) {
  12116. var transaction = _this.db.transaction([targetStore], "readwrite");
  12117. transaction.onabort = function (event) {
  12118. try {
  12119. if (event.srcElement.error.name === "QuotaExceededError") {
  12120. this.hasReachedQuota = true;
  12121. }
  12122. } catch (ex) {
  12123. }
  12124. callback(fileData);
  12125. };
  12126. transaction.oncomplete = function (event) {
  12127. callback(fileData);
  12128. };
  12129. var newFile;
  12130. if (targetStore === "scenes") {
  12131. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12132. } else {
  12133. newFile = { textureUrl: url, data: fileData };
  12134. }
  12135. try {
  12136. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12137. addRequest.onsuccess = function (event) {
  12138. };
  12139. addRequest.onerror = function (event) {
  12140. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12141. };
  12142. } catch (ex) {
  12143. callback(fileData);
  12144. }
  12145. } else {
  12146. callback(fileData);
  12147. }
  12148. } else {
  12149. callback();
  12150. }
  12151. }, false);
  12152. xhr.addEventListener("error", function (event) {
  12153. BABYLON.Tools.Error("error on XHR request.");
  12154. callback();
  12155. }, false);
  12156. xhr.send();
  12157. } else {
  12158. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12159. callback();
  12160. }
  12161. };
  12162. Database.isUASupportingBlobStorage = true;
  12163. Database.parseURL = function (url) {
  12164. var a = document.createElement('a');
  12165. a.href = url;
  12166. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12167. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12168. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12169. return absLocation;
  12170. };
  12171. Database.ReturnFullUrlLocation = function (url) {
  12172. if (url.indexOf("http:/") === -1) {
  12173. return (BABYLON.Database.parseURL(window.location.href) + url);
  12174. } else {
  12175. return url;
  12176. }
  12177. };
  12178. return Database;
  12179. })();
  12180. BABYLON.Database = Database;
  12181. })(BABYLON || (BABYLON = {}));
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. var SpriteManager = (function () {
  12185. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12186. this.name = name;
  12187. this.cellSize = cellSize;
  12188. this.sprites = new Array();
  12189. this.renderingGroupId = 0;
  12190. this.fogEnabled = true;
  12191. this._vertexDeclaration = [3, 4, 4, 4];
  12192. this._vertexStrideSize = 15 * 4;
  12193. this._capacity = capacity;
  12194. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12195. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12196. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12197. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12198. this._scene = scene;
  12199. this._scene.spriteManagers.push(this);
  12200. this._vertexDeclaration = [3, 4, 4, 4];
  12201. this._vertexStrideSize = 15 * 4;
  12202. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12203. var indices = [];
  12204. var index = 0;
  12205. for (var count = 0; count < capacity; count++) {
  12206. indices.push(index);
  12207. indices.push(index + 1);
  12208. indices.push(index + 2);
  12209. indices.push(index);
  12210. indices.push(index + 2);
  12211. indices.push(index + 3);
  12212. index += 4;
  12213. }
  12214. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12215. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12216. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12217. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12218. }
  12219. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12220. var arrayOffset = index * 15;
  12221. if (offsetX == 0)
  12222. offsetX = this._epsilon;
  12223. else if (offsetX == 1)
  12224. offsetX = 1 - this._epsilon;
  12225. if (offsetY == 0)
  12226. offsetY = this._epsilon;
  12227. else if (offsetY == 1)
  12228. offsetY = 1 - this._epsilon;
  12229. this._vertices[arrayOffset] = sprite.position.x;
  12230. this._vertices[arrayOffset + 1] = sprite.position.y;
  12231. this._vertices[arrayOffset + 2] = sprite.position.z;
  12232. this._vertices[arrayOffset + 3] = sprite.angle;
  12233. this._vertices[arrayOffset + 4] = sprite.size;
  12234. this._vertices[arrayOffset + 5] = offsetX;
  12235. this._vertices[arrayOffset + 6] = offsetY;
  12236. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12237. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12238. var offset = (sprite.cellIndex / rowSize) >> 0;
  12239. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12240. this._vertices[arrayOffset + 10] = offset;
  12241. this._vertices[arrayOffset + 11] = sprite.color.r;
  12242. this._vertices[arrayOffset + 12] = sprite.color.g;
  12243. this._vertices[arrayOffset + 13] = sprite.color.b;
  12244. this._vertices[arrayOffset + 14] = sprite.color.a;
  12245. };
  12246. SpriteManager.prototype.render = function () {
  12247. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12248. return;
  12249. var engine = this._scene.getEngine();
  12250. var baseSize = this._spriteTexture.getBaseSize();
  12251. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12252. var max = Math.min(this._capacity, this.sprites.length);
  12253. var rowSize = baseSize.width / this.cellSize;
  12254. var offset = 0;
  12255. for (var index = 0; index < max; index++) {
  12256. var sprite = this.sprites[index];
  12257. if (!sprite) {
  12258. continue;
  12259. }
  12260. sprite._animate(deltaTime);
  12261. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12262. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12263. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12264. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12265. }
  12266. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12267. var effect = this._effectBase;
  12268. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12269. effect = this._effectFog;
  12270. }
  12271. engine.enableEffect(effect);
  12272. var viewMatrix = this._scene.getViewMatrix();
  12273. effect.setTexture("diffuseSampler", this._spriteTexture);
  12274. effect.setMatrix("view", viewMatrix);
  12275. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12276. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12277. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12278. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12279. effect.setColor3("vFogColor", this._scene.fogColor);
  12280. }
  12281. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12282. effect.setBool("alphaTest", true);
  12283. engine.setColorWrite(false);
  12284. engine.draw(true, 0, max * 6);
  12285. engine.setColorWrite(true);
  12286. effect.setBool("alphaTest", false);
  12287. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12288. engine.draw(true, 0, max * 6);
  12289. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12290. };
  12291. SpriteManager.prototype.dispose = function () {
  12292. if (this._vertexBuffer) {
  12293. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12294. this._vertexBuffer = null;
  12295. }
  12296. if (this._indexBuffer) {
  12297. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12298. this._indexBuffer = null;
  12299. }
  12300. if (this._spriteTexture) {
  12301. this._spriteTexture.dispose();
  12302. this._spriteTexture = null;
  12303. }
  12304. var index = this._scene.spriteManagers.indexOf(this);
  12305. this._scene.spriteManagers.splice(index, 1);
  12306. if (this.onDispose) {
  12307. this.onDispose();
  12308. }
  12309. };
  12310. return SpriteManager;
  12311. })();
  12312. BABYLON.SpriteManager = SpriteManager;
  12313. })(BABYLON || (BABYLON = {}));
  12314. var BABYLON;
  12315. (function (BABYLON) {
  12316. var Sprite = (function () {
  12317. function Sprite(name, manager) {
  12318. this.name = name;
  12319. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12320. this.size = 1.0;
  12321. this.angle = 0;
  12322. this.cellIndex = 0;
  12323. this.invertU = 0;
  12324. this.invertV = 0;
  12325. this.animations = new Array();
  12326. this._animationStarted = false;
  12327. this._loopAnimation = false;
  12328. this._fromIndex = 0;
  12329. this._toIndex = 0;
  12330. this._delay = 0;
  12331. this._direction = 1;
  12332. this._frameCount = 0;
  12333. this._time = 0;
  12334. this._manager = manager;
  12335. this._manager.sprites.push(this);
  12336. this.position = BABYLON.Vector3.Zero();
  12337. }
  12338. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12339. this._fromIndex = from;
  12340. this._toIndex = to;
  12341. this._loopAnimation = loop;
  12342. this._delay = delay;
  12343. this._animationStarted = true;
  12344. this._direction = from < to ? 1 : -1;
  12345. this.cellIndex = from;
  12346. this._time = 0;
  12347. };
  12348. Sprite.prototype.stopAnimation = function () {
  12349. this._animationStarted = false;
  12350. };
  12351. Sprite.prototype._animate = function (deltaTime) {
  12352. if (!this._animationStarted)
  12353. return;
  12354. this._time += deltaTime;
  12355. if (this._time > this._delay) {
  12356. this._time = this._time % this._delay;
  12357. this.cellIndex += this._direction;
  12358. if (this.cellIndex == this._toIndex) {
  12359. if (this._loopAnimation) {
  12360. this.cellIndex = this._fromIndex;
  12361. } else {
  12362. this._animationStarted = false;
  12363. if (this.disposeWhenFinishedAnimating) {
  12364. this.dispose();
  12365. }
  12366. }
  12367. }
  12368. }
  12369. };
  12370. Sprite.prototype.dispose = function () {
  12371. for (var i = 0; i < this._manager.sprites.length; i++) {
  12372. if (this._manager.sprites[i] == this) {
  12373. this._manager.sprites.splice(i, 1);
  12374. }
  12375. }
  12376. };
  12377. return Sprite;
  12378. })();
  12379. BABYLON.Sprite = Sprite;
  12380. })(BABYLON || (BABYLON = {}));
  12381. var BABYLON;
  12382. (function (BABYLON) {
  12383. var Layer = (function () {
  12384. function Layer(name, imgUrl, scene, isBackground, color) {
  12385. this.name = name;
  12386. this._vertexDeclaration = [2];
  12387. this._vertexStrideSize = 2 * 4;
  12388. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12389. this.isBackground = isBackground === undefined ? true : isBackground;
  12390. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12391. this._scene = scene;
  12392. this._scene.layers.push(this);
  12393. var vertices = [];
  12394. vertices.push(1, 1);
  12395. vertices.push(-1, 1);
  12396. vertices.push(-1, -1);
  12397. vertices.push(1, -1);
  12398. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12399. var indices = [];
  12400. indices.push(0);
  12401. indices.push(1);
  12402. indices.push(2);
  12403. indices.push(0);
  12404. indices.push(2);
  12405. indices.push(3);
  12406. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12407. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12408. }
  12409. Layer.prototype.render = function () {
  12410. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12411. return;
  12412. var engine = this._scene.getEngine();
  12413. engine.enableEffect(this._effect);
  12414. engine.setState(false);
  12415. this._effect.setTexture("textureSampler", this.texture);
  12416. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12417. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12418. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12419. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12420. engine.draw(true, 0, 6);
  12421. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12422. };
  12423. Layer.prototype.dispose = function () {
  12424. if (this._vertexBuffer) {
  12425. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12426. this._vertexBuffer = null;
  12427. }
  12428. if (this._indexBuffer) {
  12429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12430. this._indexBuffer = null;
  12431. }
  12432. if (this.texture) {
  12433. this.texture.dispose();
  12434. this.texture = null;
  12435. }
  12436. var index = this._scene.layers.indexOf(this);
  12437. this._scene.layers.splice(index, 1);
  12438. if (this.onDispose) {
  12439. this.onDispose();
  12440. }
  12441. };
  12442. return Layer;
  12443. })();
  12444. BABYLON.Layer = Layer;
  12445. })(BABYLON || (BABYLON = {}));
  12446. var BABYLON;
  12447. (function (BABYLON) {
  12448. var Particle = (function () {
  12449. function Particle() {
  12450. this.position = BABYLON.Vector3.Zero();
  12451. this.direction = BABYLON.Vector3.Zero();
  12452. this.color = new BABYLON.Color4(0, 0, 0, 0);
  12453. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  12454. this.lifeTime = 1.0;
  12455. this.age = 0;
  12456. this.size = 0;
  12457. this.angle = 0;
  12458. this.angularSpeed = 0;
  12459. }
  12460. return Particle;
  12461. })();
  12462. BABYLON.Particle = Particle;
  12463. })(BABYLON || (BABYLON = {}));
  12464. var BABYLON;
  12465. (function (BABYLON) {
  12466. var randomNumber = function (min, max) {
  12467. if (min == max) {
  12468. return (min);
  12469. }
  12470. var random = Math.random();
  12471. return ((random * (max - min)) + min);
  12472. };
  12473. var ParticleSystem = (function () {
  12474. function ParticleSystem(name, capacity, scene, customEffect) {
  12475. var _this = this;
  12476. this.name = name;
  12477. this.renderingGroupId = 0;
  12478. this.emitter = null;
  12479. this.emitRate = 10;
  12480. this.manualEmitCount = -1;
  12481. this.updateSpeed = 0.01;
  12482. this.targetStopDuration = 0;
  12483. this.disposeOnStop = false;
  12484. this.minEmitPower = 1;
  12485. this.maxEmitPower = 1;
  12486. this.minLifeTime = 1;
  12487. this.maxLifeTime = 1;
  12488. this.minSize = 1;
  12489. this.maxSize = 1;
  12490. this.minAngularSpeed = 0;
  12491. this.maxAngularSpeed = 0;
  12492. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12493. this.forceDepthWrite = false;
  12494. this.gravity = BABYLON.Vector3.Zero();
  12495. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12496. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12497. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12498. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12499. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12500. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12501. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12502. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12503. this.particles = new Array();
  12504. this._vertexDeclaration = [3, 4, 4];
  12505. this._vertexStrideSize = 11 * 4;
  12506. this._stockParticles = new Array();
  12507. this._newPartsExcess = 0;
  12508. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12509. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12510. this._scaledDirection = BABYLON.Vector3.Zero();
  12511. this._scaledGravity = BABYLON.Vector3.Zero();
  12512. this._currentRenderId = -1;
  12513. this._started = false;
  12514. this._stopped = false;
  12515. this._actualFrame = 0;
  12516. this.id = name;
  12517. this._capacity = capacity;
  12518. this._scene = scene;
  12519. this._customEffect = customEffect;
  12520. scene.particleSystems.push(this);
  12521. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12522. var indices = [];
  12523. var index = 0;
  12524. for (var count = 0; count < capacity; count++) {
  12525. indices.push(index);
  12526. indices.push(index + 1);
  12527. indices.push(index + 2);
  12528. indices.push(index);
  12529. indices.push(index + 2);
  12530. indices.push(index + 3);
  12531. index += 4;
  12532. }
  12533. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12534. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12535. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12536. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12537. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12538. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12539. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12540. };
  12541. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12542. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12543. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12544. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12546. };
  12547. }
  12548. ParticleSystem.prototype.getCapacity = function () {
  12549. return this._capacity;
  12550. };
  12551. ParticleSystem.prototype.isAlive = function () {
  12552. return this._alive;
  12553. };
  12554. ParticleSystem.prototype.isStarted = function () {
  12555. return this._started;
  12556. };
  12557. ParticleSystem.prototype.start = function () {
  12558. this._started = true;
  12559. this._stopped = false;
  12560. this._actualFrame = 0;
  12561. };
  12562. ParticleSystem.prototype.stop = function () {
  12563. this._stopped = true;
  12564. };
  12565. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12566. var offset = index * 11;
  12567. this._vertices[offset] = particle.position.x;
  12568. this._vertices[offset + 1] = particle.position.y;
  12569. this._vertices[offset + 2] = particle.position.z;
  12570. this._vertices[offset + 3] = particle.color.r;
  12571. this._vertices[offset + 4] = particle.color.g;
  12572. this._vertices[offset + 5] = particle.color.b;
  12573. this._vertices[offset + 6] = particle.color.a;
  12574. this._vertices[offset + 7] = particle.angle;
  12575. this._vertices[offset + 8] = particle.size;
  12576. this._vertices[offset + 9] = offsetX;
  12577. this._vertices[offset + 10] = offsetY;
  12578. };
  12579. ParticleSystem.prototype._update = function (newParticles) {
  12580. this._alive = this.particles.length > 0;
  12581. for (var index = 0; index < this.particles.length; index++) {
  12582. var particle = this.particles[index];
  12583. particle.age += this._scaledUpdateSpeed;
  12584. if (particle.age >= particle.lifeTime) {
  12585. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12586. index--;
  12587. continue;
  12588. } else {
  12589. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12590. particle.color.addInPlace(this._scaledColorStep);
  12591. if (particle.color.a < 0)
  12592. particle.color.a = 0;
  12593. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12594. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12595. particle.position.addInPlace(this._scaledDirection);
  12596. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12597. particle.direction.addInPlace(this._scaledGravity);
  12598. }
  12599. }
  12600. var worldMatrix;
  12601. if (this.emitter.position) {
  12602. worldMatrix = this.emitter.getWorldMatrix();
  12603. } else {
  12604. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12605. }
  12606. for (index = 0; index < newParticles; index++) {
  12607. if (this.particles.length == this._capacity) {
  12608. break;
  12609. }
  12610. if (this._stockParticles.length !== 0) {
  12611. particle = this._stockParticles.pop();
  12612. particle.age = 0;
  12613. } else {
  12614. particle = new BABYLON.Particle();
  12615. }
  12616. this.particles.push(particle);
  12617. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12618. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12619. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12620. particle.size = randomNumber(this.minSize, this.maxSize);
  12621. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12622. this.startPositionFunction(worldMatrix, particle.position);
  12623. var step = randomNumber(0, 1.0);
  12624. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12625. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12626. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12627. }
  12628. };
  12629. ParticleSystem.prototype._getEffect = function () {
  12630. if (this._customEffect) {
  12631. return this._customEffect;
  12632. }
  12633. ;
  12634. var defines = [];
  12635. if (this._scene.clipPlane) {
  12636. defines.push("#define CLIPPLANE");
  12637. }
  12638. var join = defines.join("\n");
  12639. if (this._cachedDefines != join) {
  12640. this._cachedDefines = join;
  12641. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12642. }
  12643. return this._effect;
  12644. };
  12645. ParticleSystem.prototype.animate = function () {
  12646. if (!this._started)
  12647. return;
  12648. var effect = this._getEffect();
  12649. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12650. return;
  12651. if (this._currentRenderId === this._scene.getRenderId()) {
  12652. return;
  12653. }
  12654. this._currentRenderId = this._scene.getRenderId();
  12655. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12656. var emitCout;
  12657. if (this.manualEmitCount > -1) {
  12658. emitCout = this.manualEmitCount;
  12659. this.manualEmitCount = 0;
  12660. } else {
  12661. emitCout = this.emitRate;
  12662. }
  12663. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12664. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12665. if (this._newPartsExcess > 1.0) {
  12666. newParticles += this._newPartsExcess >> 0;
  12667. this._newPartsExcess -= this._newPartsExcess >> 0;
  12668. }
  12669. this._alive = false;
  12670. if (!this._stopped) {
  12671. this._actualFrame += this._scaledUpdateSpeed;
  12672. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12673. this.stop();
  12674. } else {
  12675. newParticles = 0;
  12676. }
  12677. this._update(newParticles);
  12678. if (this._stopped) {
  12679. if (!this._alive) {
  12680. this._started = false;
  12681. if (this.disposeOnStop) {
  12682. this._scene._toBeDisposed.push(this);
  12683. }
  12684. }
  12685. }
  12686. var offset = 0;
  12687. for (var index = 0; index < this.particles.length; index++) {
  12688. var particle = this.particles[index];
  12689. this._appendParticleVertex(offset++, particle, 0, 0);
  12690. this._appendParticleVertex(offset++, particle, 1, 0);
  12691. this._appendParticleVertex(offset++, particle, 1, 1);
  12692. this._appendParticleVertex(offset++, particle, 0, 1);
  12693. }
  12694. var engine = this._scene.getEngine();
  12695. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12696. };
  12697. ParticleSystem.prototype.render = function () {
  12698. var effect = this._getEffect();
  12699. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12700. return 0;
  12701. var engine = this._scene.getEngine();
  12702. engine.enableEffect(effect);
  12703. var viewMatrix = this._scene.getViewMatrix();
  12704. effect.setTexture("diffuseSampler", this.particleTexture);
  12705. effect.setMatrix("view", viewMatrix);
  12706. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12707. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12708. if (this._scene.clipPlane) {
  12709. var clipPlane = this._scene.clipPlane;
  12710. var invView = viewMatrix.clone();
  12711. invView.invert();
  12712. effect.setMatrix("invView", invView);
  12713. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12714. }
  12715. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12716. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12717. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12718. } else {
  12719. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12720. }
  12721. if (this.forceDepthWrite) {
  12722. engine.setDepthWrite(true);
  12723. }
  12724. engine.draw(true, 0, this.particles.length * 6);
  12725. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12726. return this.particles.length;
  12727. };
  12728. ParticleSystem.prototype.dispose = function () {
  12729. if (this._vertexBuffer) {
  12730. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12731. this._vertexBuffer = null;
  12732. }
  12733. if (this._indexBuffer) {
  12734. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12735. this._indexBuffer = null;
  12736. }
  12737. if (this.particleTexture) {
  12738. this.particleTexture.dispose();
  12739. this.particleTexture = null;
  12740. }
  12741. var index = this._scene.particleSystems.indexOf(this);
  12742. this._scene.particleSystems.splice(index, 1);
  12743. if (this.onDispose) {
  12744. this.onDispose();
  12745. }
  12746. };
  12747. ParticleSystem.prototype.clone = function (name, newEmitter) {
  12748. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  12749. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  12750. if (newEmitter === undefined) {
  12751. newEmitter = this.emitter;
  12752. }
  12753. result.emitter = newEmitter;
  12754. if (this.particleTexture) {
  12755. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  12756. }
  12757. result.start();
  12758. return result;
  12759. };
  12760. ParticleSystem.BLENDMODE_ONEONE = 0;
  12761. ParticleSystem.BLENDMODE_STANDARD = 1;
  12762. return ParticleSystem;
  12763. })();
  12764. BABYLON.ParticleSystem = ParticleSystem;
  12765. })(BABYLON || (BABYLON = {}));
  12766. var BABYLON;
  12767. (function (BABYLON) {
  12768. var Animation = (function () {
  12769. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  12770. this.name = name;
  12771. this.targetProperty = targetProperty;
  12772. this.framePerSecond = framePerSecond;
  12773. this.dataType = dataType;
  12774. this.loopMode = loopMode;
  12775. this._offsetsCache = {};
  12776. this._highLimitsCache = {};
  12777. this._stopped = false;
  12778. this.targetPropertyPath = targetProperty.split(".");
  12779. this.dataType = dataType;
  12780. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  12781. }
  12782. Animation.prototype.isStopped = function () {
  12783. return this._stopped;
  12784. };
  12785. Animation.prototype.getKeys = function () {
  12786. return this._keys;
  12787. };
  12788. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  12789. return startValue + (endValue - startValue) * gradient;
  12790. };
  12791. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  12792. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  12793. };
  12794. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  12795. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  12796. };
  12797. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  12798. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  12799. };
  12800. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  12801. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  12802. };
  12803. Animation.prototype.clone = function () {
  12804. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  12805. clone.setKeys(this._keys);
  12806. return clone;
  12807. };
  12808. Animation.prototype.setKeys = function (values) {
  12809. this._keys = values.slice(0);
  12810. this._offsetsCache = {};
  12811. this._highLimitsCache = {};
  12812. };
  12813. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  12814. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  12815. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  12816. }
  12817. this.currentFrame = currentFrame;
  12818. for (var key = 0; key < this._keys.length; key++) {
  12819. if (this._keys[key + 1].frame >= currentFrame) {
  12820. var startValue = this._keys[key].value;
  12821. var endValue = this._keys[key + 1].value;
  12822. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  12823. switch (this.dataType) {
  12824. case Animation.ANIMATIONTYPE_FLOAT:
  12825. switch (loopMode) {
  12826. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12827. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12828. return this.floatInterpolateFunction(startValue, endValue, gradient);
  12829. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12830. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  12831. }
  12832. break;
  12833. case Animation.ANIMATIONTYPE_QUATERNION:
  12834. var quaternion = null;
  12835. switch (loopMode) {
  12836. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12837. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12838. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  12839. break;
  12840. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12841. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12842. break;
  12843. }
  12844. return quaternion;
  12845. case Animation.ANIMATIONTYPE_VECTOR3:
  12846. switch (loopMode) {
  12847. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12848. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12849. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  12850. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12851. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12852. }
  12853. case Animation.ANIMATIONTYPE_VECTOR2:
  12854. switch (loopMode) {
  12855. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12856. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12857. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  12858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12859. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12860. }
  12861. case Animation.ANIMATIONTYPE_COLOR3:
  12862. switch (loopMode) {
  12863. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12864. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12865. return this.color3InterpolateFunction(startValue, endValue, gradient);
  12866. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12867. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  12868. }
  12869. case Animation.ANIMATIONTYPE_MATRIX:
  12870. switch (loopMode) {
  12871. case Animation.ANIMATIONLOOPMODE_CYCLE:
  12872. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  12873. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  12874. return startValue;
  12875. }
  12876. default:
  12877. break;
  12878. }
  12879. break;
  12880. }
  12881. }
  12882. return this._keys[this._keys.length - 1].value;
  12883. };
  12884. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  12885. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  12886. this._stopped = true;
  12887. return false;
  12888. }
  12889. var returnValue = true;
  12890. if (this._keys[0].frame != 0) {
  12891. var newKey = {
  12892. frame: 0,
  12893. value: this._keys[0].value
  12894. };
  12895. this._keys.splice(0, 0, newKey);
  12896. }
  12897. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  12898. from = this._keys[0].frame;
  12899. }
  12900. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  12901. to = this._keys[this._keys.length - 1].frame;
  12902. }
  12903. var range = to - from;
  12904. var offsetValue;
  12905. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  12906. if (ratio > range && !loop) {
  12907. returnValue = false;
  12908. highLimitValue = this._keys[this._keys.length - 1].value;
  12909. } else {
  12910. var highLimitValue = 0;
  12911. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  12912. var keyOffset = to.toString() + from.toString();
  12913. if (!this._offsetsCache[keyOffset]) {
  12914. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12915. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  12916. switch (this.dataType) {
  12917. case Animation.ANIMATIONTYPE_FLOAT:
  12918. this._offsetsCache[keyOffset] = toValue - fromValue;
  12919. break;
  12920. case Animation.ANIMATIONTYPE_QUATERNION:
  12921. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12922. break;
  12923. case Animation.ANIMATIONTYPE_VECTOR3:
  12924. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12925. case Animation.ANIMATIONTYPE_VECTOR2:
  12926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12927. case Animation.ANIMATIONTYPE_COLOR3:
  12928. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  12929. default:
  12930. break;
  12931. }
  12932. this._highLimitsCache[keyOffset] = toValue;
  12933. }
  12934. highLimitValue = this._highLimitsCache[keyOffset];
  12935. offsetValue = this._offsetsCache[keyOffset];
  12936. }
  12937. }
  12938. if (offsetValue === undefined) {
  12939. switch (this.dataType) {
  12940. case Animation.ANIMATIONTYPE_FLOAT:
  12941. offsetValue = 0;
  12942. break;
  12943. case Animation.ANIMATIONTYPE_QUATERNION:
  12944. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  12945. break;
  12946. case Animation.ANIMATIONTYPE_VECTOR3:
  12947. offsetValue = BABYLON.Vector3.Zero();
  12948. break;
  12949. case Animation.ANIMATIONTYPE_VECTOR2:
  12950. offsetValue = BABYLON.Vector2.Zero();
  12951. break;
  12952. case Animation.ANIMATIONTYPE_COLOR3:
  12953. offsetValue = BABYLON.Color3.Black();
  12954. }
  12955. }
  12956. var repeatCount = (ratio / range) >> 0;
  12957. var currentFrame = returnValue ? from + ratio % range : to;
  12958. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  12959. if (this.targetPropertyPath.length > 1) {
  12960. var property = this._target[this.targetPropertyPath[0]];
  12961. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  12962. property = property[this.targetPropertyPath[index]];
  12963. }
  12964. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  12965. } else {
  12966. this._target[this.targetPropertyPath[0]] = currentValue;
  12967. }
  12968. if (this._target.markAsDirty) {
  12969. this._target.markAsDirty(this.targetProperty);
  12970. }
  12971. if (!returnValue) {
  12972. this._stopped = true;
  12973. }
  12974. return returnValue;
  12975. };
  12976. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  12977. get: function () {
  12978. return Animation._ANIMATIONTYPE_FLOAT;
  12979. },
  12980. enumerable: true,
  12981. configurable: true
  12982. });
  12983. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  12984. get: function () {
  12985. return Animation._ANIMATIONTYPE_VECTOR3;
  12986. },
  12987. enumerable: true,
  12988. configurable: true
  12989. });
  12990. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  12991. get: function () {
  12992. return Animation._ANIMATIONTYPE_VECTOR2;
  12993. },
  12994. enumerable: true,
  12995. configurable: true
  12996. });
  12997. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  12998. get: function () {
  12999. return Animation._ANIMATIONTYPE_QUATERNION;
  13000. },
  13001. enumerable: true,
  13002. configurable: true
  13003. });
  13004. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13005. get: function () {
  13006. return Animation._ANIMATIONTYPE_MATRIX;
  13007. },
  13008. enumerable: true,
  13009. configurable: true
  13010. });
  13011. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13012. get: function () {
  13013. return Animation._ANIMATIONTYPE_COLOR3;
  13014. },
  13015. enumerable: true,
  13016. configurable: true
  13017. });
  13018. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13019. get: function () {
  13020. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13021. },
  13022. enumerable: true,
  13023. configurable: true
  13024. });
  13025. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13026. get: function () {
  13027. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13033. get: function () {
  13034. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13035. },
  13036. enumerable: true,
  13037. configurable: true
  13038. });
  13039. Animation._ANIMATIONTYPE_FLOAT = 0;
  13040. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13041. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13042. Animation._ANIMATIONTYPE_MATRIX = 3;
  13043. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13044. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13045. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13046. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13047. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13048. return Animation;
  13049. })();
  13050. BABYLON.Animation = Animation;
  13051. })(BABYLON || (BABYLON = {}));
  13052. var BABYLON;
  13053. (function (BABYLON) {
  13054. var Animatable = (function () {
  13055. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13056. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13057. if (typeof toFrame === "undefined") { toFrame = 100; }
  13058. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13059. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13060. this.target = target;
  13061. this.fromFrame = fromFrame;
  13062. this.toFrame = toFrame;
  13063. this.loopAnimation = loopAnimation;
  13064. this.speedRatio = speedRatio;
  13065. this.onAnimationEnd = onAnimationEnd;
  13066. this._animations = new Array();
  13067. this._paused = false;
  13068. this.animationStarted = false;
  13069. if (animations) {
  13070. this.appendAnimations(target, animations);
  13071. }
  13072. this._scene = scene;
  13073. scene._activeAnimatables.push(this);
  13074. }
  13075. Animatable.prototype.appendAnimations = function (target, animations) {
  13076. for (var index = 0; index < animations.length; index++) {
  13077. var animation = animations[index];
  13078. animation._target = target;
  13079. this._animations.push(animation);
  13080. }
  13081. };
  13082. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13083. var animations = this._animations;
  13084. for (var index = 0; index < animations.length; index++) {
  13085. if (animations[index].targetProperty === property) {
  13086. return animations[index];
  13087. }
  13088. }
  13089. return null;
  13090. };
  13091. Animatable.prototype.pause = function () {
  13092. if (this._paused) {
  13093. return;
  13094. }
  13095. this._paused = true;
  13096. };
  13097. Animatable.prototype.restart = function () {
  13098. this._paused = false;
  13099. };
  13100. Animatable.prototype.stop = function () {
  13101. var index = this._scene._activeAnimatables.indexOf(this);
  13102. if (index > -1) {
  13103. this._scene._activeAnimatables.splice(index, 1);
  13104. }
  13105. if (this.onAnimationEnd) {
  13106. this.onAnimationEnd();
  13107. }
  13108. };
  13109. Animatable.prototype._animate = function (delay) {
  13110. if (this._paused) {
  13111. if (!this._pausedDelay) {
  13112. this._pausedDelay = delay;
  13113. }
  13114. return true;
  13115. }
  13116. if (!this._localDelayOffset) {
  13117. this._localDelayOffset = delay;
  13118. } else if (this._pausedDelay) {
  13119. this._localDelayOffset += delay - this._pausedDelay;
  13120. this._pausedDelay = null;
  13121. }
  13122. var running = false;
  13123. var animations = this._animations;
  13124. for (var index = 0; index < animations.length; index++) {
  13125. var animation = animations[index];
  13126. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13127. running = running || isRunning;
  13128. }
  13129. if (!running && this.onAnimationEnd) {
  13130. this.onAnimationEnd();
  13131. }
  13132. return running;
  13133. };
  13134. return Animatable;
  13135. })();
  13136. BABYLON.Animatable = Animatable;
  13137. })(BABYLON || (BABYLON = {}));
  13138. var BABYLON;
  13139. (function (BABYLON) {
  13140. var Octree = (function () {
  13141. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13142. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13143. this.maxDepth = maxDepth;
  13144. this.dynamicContent = new Array();
  13145. this._maxBlockCapacity = maxBlockCapacity || 64;
  13146. this._selectionContent = new BABYLON.SmartArray(1024);
  13147. this._creationFunc = creationFunc;
  13148. }
  13149. Octree.prototype.update = function (worldMin, worldMax, entries) {
  13150. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  13151. };
  13152. Octree.prototype.addMesh = function (entry) {
  13153. for (var index = 0; index < this.blocks.length; index++) {
  13154. var block = this.blocks[index];
  13155. block.addEntry(entry);
  13156. }
  13157. };
  13158. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  13159. this._selectionContent.reset();
  13160. for (var index = 0; index < this.blocks.length; index++) {
  13161. var block = this.blocks[index];
  13162. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  13163. }
  13164. if (allowDuplicate) {
  13165. this._selectionContent.concat(this.dynamicContent);
  13166. } else {
  13167. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13168. }
  13169. return this._selectionContent;
  13170. };
  13171. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  13172. this._selectionContent.reset();
  13173. for (var index = 0; index < this.blocks.length; index++) {
  13174. var block = this.blocks[index];
  13175. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  13176. }
  13177. if (allowDuplicate) {
  13178. this._selectionContent.concat(this.dynamicContent);
  13179. } else {
  13180. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13181. }
  13182. return this._selectionContent;
  13183. };
  13184. Octree.prototype.intersectsRay = function (ray) {
  13185. this._selectionContent.reset();
  13186. for (var index = 0; index < this.blocks.length; index++) {
  13187. var block = this.blocks[index];
  13188. block.intersectsRay(ray, this._selectionContent);
  13189. }
  13190. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13191. return this._selectionContent;
  13192. };
  13193. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  13194. target.blocks = new Array();
  13195. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  13196. for (var x = 0; x < 2; x++) {
  13197. for (var y = 0; y < 2; y++) {
  13198. for (var z = 0; z < 2; z++) {
  13199. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  13200. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  13201. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  13202. block.addEntries(entries);
  13203. target.blocks.push(block);
  13204. }
  13205. }
  13206. }
  13207. };
  13208. Octree.CreationFuncForMeshes = function (entry, block) {
  13209. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13210. block.entries.push(entry);
  13211. }
  13212. };
  13213. Octree.CreationFuncForSubMeshes = function (entry, block) {
  13214. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13215. block.entries.push(entry);
  13216. }
  13217. };
  13218. return Octree;
  13219. })();
  13220. BABYLON.Octree = Octree;
  13221. })(BABYLON || (BABYLON = {}));
  13222. var BABYLON;
  13223. (function (BABYLON) {
  13224. var OctreeBlock = (function () {
  13225. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  13226. this.entries = new Array();
  13227. this._boundingVectors = new Array();
  13228. this._capacity = capacity;
  13229. this._depth = depth;
  13230. this._maxDepth = maxDepth;
  13231. this._creationFunc = creationFunc;
  13232. this._minPoint = minPoint;
  13233. this._maxPoint = maxPoint;
  13234. this._boundingVectors.push(minPoint.clone());
  13235. this._boundingVectors.push(maxPoint.clone());
  13236. this._boundingVectors.push(minPoint.clone());
  13237. this._boundingVectors[2].x = maxPoint.x;
  13238. this._boundingVectors.push(minPoint.clone());
  13239. this._boundingVectors[3].y = maxPoint.y;
  13240. this._boundingVectors.push(minPoint.clone());
  13241. this._boundingVectors[4].z = maxPoint.z;
  13242. this._boundingVectors.push(maxPoint.clone());
  13243. this._boundingVectors[5].z = minPoint.z;
  13244. this._boundingVectors.push(maxPoint.clone());
  13245. this._boundingVectors[6].x = minPoint.x;
  13246. this._boundingVectors.push(maxPoint.clone());
  13247. this._boundingVectors[7].y = minPoint.y;
  13248. }
  13249. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  13250. get: function () {
  13251. return this._capacity;
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  13257. get: function () {
  13258. return this._minPoint;
  13259. },
  13260. enumerable: true,
  13261. configurable: true
  13262. });
  13263. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  13264. get: function () {
  13265. return this._maxPoint;
  13266. },
  13267. enumerable: true,
  13268. configurable: true
  13269. });
  13270. OctreeBlock.prototype.addEntry = function (entry) {
  13271. if (this.blocks) {
  13272. for (var index = 0; index < this.blocks.length; index++) {
  13273. var block = this.blocks[index];
  13274. block.addEntry(entry);
  13275. }
  13276. return;
  13277. }
  13278. this._creationFunc(entry, this);
  13279. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  13280. this.createInnerBlocks();
  13281. }
  13282. };
  13283. OctreeBlock.prototype.addEntries = function (entries) {
  13284. for (var index = 0; index < entries.length; index++) {
  13285. var mesh = entries[index];
  13286. this.addEntry(mesh);
  13287. }
  13288. };
  13289. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  13290. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  13291. if (this.blocks) {
  13292. for (var index = 0; index < this.blocks.length; index++) {
  13293. var block = this.blocks[index];
  13294. block.select(frustumPlanes, selection, allowDuplicate);
  13295. }
  13296. return;
  13297. }
  13298. if (allowDuplicate) {
  13299. selection.concat(this.entries);
  13300. } else {
  13301. selection.concatWithNoDuplicate(this.entries);
  13302. }
  13303. }
  13304. };
  13305. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  13306. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  13307. if (this.blocks) {
  13308. for (var index = 0; index < this.blocks.length; index++) {
  13309. var block = this.blocks[index];
  13310. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  13311. }
  13312. return;
  13313. }
  13314. if (allowDuplicate) {
  13315. selection.concat(this.entries);
  13316. } else {
  13317. selection.concatWithNoDuplicate(this.entries);
  13318. }
  13319. }
  13320. };
  13321. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  13322. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  13323. if (this.blocks) {
  13324. for (var index = 0; index < this.blocks.length; index++) {
  13325. var block = this.blocks[index];
  13326. block.intersectsRay(ray, selection);
  13327. }
  13328. return;
  13329. }
  13330. selection.concatWithNoDuplicate(this.entries);
  13331. }
  13332. };
  13333. OctreeBlock.prototype.createInnerBlocks = function () {
  13334. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  13335. };
  13336. return OctreeBlock;
  13337. })();
  13338. BABYLON.OctreeBlock = OctreeBlock;
  13339. })(BABYLON || (BABYLON = {}));
  13340. var BABYLON;
  13341. (function (BABYLON) {
  13342. var Bone = (function () {
  13343. function Bone(name, skeleton, parentBone, matrix) {
  13344. this.name = name;
  13345. this.children = new Array();
  13346. this.animations = new Array();
  13347. this._worldTransform = new BABYLON.Matrix();
  13348. this._absoluteTransform = new BABYLON.Matrix();
  13349. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  13350. this._skeleton = skeleton;
  13351. this._matrix = matrix;
  13352. this._baseMatrix = matrix;
  13353. skeleton.bones.push(this);
  13354. if (parentBone) {
  13355. this._parent = parentBone;
  13356. parentBone.children.push(this);
  13357. } else {
  13358. this._parent = null;
  13359. }
  13360. this._updateDifferenceMatrix();
  13361. }
  13362. Bone.prototype.getParent = function () {
  13363. return this._parent;
  13364. };
  13365. Bone.prototype.getLocalMatrix = function () {
  13366. return this._matrix;
  13367. };
  13368. Bone.prototype.getBaseMatrix = function () {
  13369. return this._baseMatrix;
  13370. };
  13371. Bone.prototype.getWorldMatrix = function () {
  13372. return this._worldTransform;
  13373. };
  13374. Bone.prototype.getInvertedAbsoluteTransform = function () {
  13375. return this._invertedAbsoluteTransform;
  13376. };
  13377. Bone.prototype.getAbsoluteMatrix = function () {
  13378. var matrix = this._matrix.clone();
  13379. var parent = this._parent;
  13380. while (parent) {
  13381. matrix = matrix.multiply(parent.getLocalMatrix());
  13382. parent = parent.getParent();
  13383. }
  13384. return matrix;
  13385. };
  13386. Bone.prototype.updateMatrix = function (matrix) {
  13387. this._matrix = matrix;
  13388. this._skeleton._markAsDirty();
  13389. this._updateDifferenceMatrix();
  13390. };
  13391. Bone.prototype._updateDifferenceMatrix = function () {
  13392. if (this._parent) {
  13393. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  13394. } else {
  13395. this._absoluteTransform.copyFrom(this._matrix);
  13396. }
  13397. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  13398. for (var index = 0; index < this.children.length; index++) {
  13399. this.children[index]._updateDifferenceMatrix();
  13400. }
  13401. };
  13402. Bone.prototype.markAsDirty = function () {
  13403. this._skeleton._markAsDirty();
  13404. };
  13405. return Bone;
  13406. })();
  13407. BABYLON.Bone = Bone;
  13408. })(BABYLON || (BABYLON = {}));
  13409. var BABYLON;
  13410. (function (BABYLON) {
  13411. var Skeleton = (function () {
  13412. function Skeleton(name, id, scene) {
  13413. this.name = name;
  13414. this.id = id;
  13415. this.bones = new Array();
  13416. this._isDirty = true;
  13417. this._identity = BABYLON.Matrix.Identity();
  13418. this.bones = [];
  13419. this._scene = scene;
  13420. scene.skeletons.push(this);
  13421. }
  13422. Skeleton.prototype.getTransformMatrices = function () {
  13423. return this._transformMatrices;
  13424. };
  13425. Skeleton.prototype._markAsDirty = function () {
  13426. this._isDirty = true;
  13427. };
  13428. Skeleton.prototype.prepare = function () {
  13429. if (!this._isDirty) {
  13430. return;
  13431. }
  13432. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  13433. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  13434. }
  13435. for (var index = 0; index < this.bones.length; index++) {
  13436. var bone = this.bones[index];
  13437. var parentBone = bone.getParent();
  13438. if (parentBone) {
  13439. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  13440. } else {
  13441. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  13442. }
  13443. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  13444. }
  13445. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  13446. this._isDirty = false;
  13447. };
  13448. Skeleton.prototype.getAnimatables = function () {
  13449. if (!this._animatables || this._animatables.length != this.bones.length) {
  13450. this._animatables = [];
  13451. for (var index = 0; index < this.bones.length; index++) {
  13452. this._animatables.push(this.bones[index]);
  13453. }
  13454. }
  13455. return this._animatables;
  13456. };
  13457. Skeleton.prototype.clone = function (name, id) {
  13458. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  13459. for (var index = 0; index < this.bones.length; index++) {
  13460. var source = this.bones[index];
  13461. var parentBone = null;
  13462. if (source.getParent()) {
  13463. var parentIndex = this.bones.indexOf(source.getParent());
  13464. parentBone = result.bones[parentIndex];
  13465. }
  13466. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  13467. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  13468. }
  13469. return result;
  13470. };
  13471. return Skeleton;
  13472. })();
  13473. BABYLON.Skeleton = Skeleton;
  13474. })(BABYLON || (BABYLON = {}));
  13475. var BABYLON;
  13476. (function (BABYLON) {
  13477. var PostProcess = (function () {
  13478. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13479. this.name = name;
  13480. this.width = -1;
  13481. this.height = -1;
  13482. this._reusable = false;
  13483. this._textures = new BABYLON.SmartArray(2);
  13484. this._currentRenderTextureInd = 0;
  13485. if (camera != null) {
  13486. this._camera = camera;
  13487. this._scene = camera.getScene();
  13488. camera.attachPostProcess(this);
  13489. this._engine = this._scene.getEngine();
  13490. } else {
  13491. this._engine = engine;
  13492. }
  13493. this._renderRatio = ratio;
  13494. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13495. this._reusable = reusable || false;
  13496. samplers = samplers || [];
  13497. samplers.push("textureSampler");
  13498. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13499. }
  13500. PostProcess.prototype.isReusable = function () {
  13501. return this._reusable;
  13502. };
  13503. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13504. camera = camera || this._camera;
  13505. var scene = camera.getScene();
  13506. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13507. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13508. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13509. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13510. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13511. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13512. if (this._textures.length > 0) {
  13513. for (var i = 0; i < this._textures.length; i++) {
  13514. this._engine._releaseTexture(this._textures.data[i]);
  13515. }
  13516. this._textures.reset();
  13517. }
  13518. this.width = desiredWidth;
  13519. this.height = desiredHeight;
  13520. 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 }));
  13521. if (this._reusable) {
  13522. 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 }));
  13523. }
  13524. if (this.onSizeChanged) {
  13525. this.onSizeChanged();
  13526. }
  13527. }
  13528. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13529. if (this.onActivate) {
  13530. this.onActivate(camera);
  13531. }
  13532. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13533. if (this._reusable) {
  13534. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13535. }
  13536. };
  13537. PostProcess.prototype.apply = function () {
  13538. if (!this._effect.isReady())
  13539. return null;
  13540. this._engine.enableEffect(this._effect);
  13541. this._engine.setState(false);
  13542. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13543. this._engine.setDepthBuffer(false);
  13544. this._engine.setDepthWrite(false);
  13545. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13546. if (this.onApply) {
  13547. this.onApply(this._effect);
  13548. }
  13549. return this._effect;
  13550. };
  13551. PostProcess.prototype.dispose = function (camera) {
  13552. camera = camera || this._camera;
  13553. if (this._textures.length > 0) {
  13554. for (var i = 0; i < this._textures.length; i++) {
  13555. this._engine._releaseTexture(this._textures.data[i]);
  13556. }
  13557. this._textures.reset();
  13558. }
  13559. camera.detachPostProcess(this);
  13560. var index = camera._postProcesses.indexOf(this);
  13561. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13562. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13563. }
  13564. };
  13565. return PostProcess;
  13566. })();
  13567. BABYLON.PostProcess = PostProcess;
  13568. })(BABYLON || (BABYLON = {}));
  13569. var BABYLON;
  13570. (function (BABYLON) {
  13571. var PostProcessManager = (function () {
  13572. function PostProcessManager(scene) {
  13573. this._vertexDeclaration = [2];
  13574. this._vertexStrideSize = 2 * 4;
  13575. this._scene = scene;
  13576. var vertices = [];
  13577. vertices.push(1, 1);
  13578. vertices.push(-1, 1);
  13579. vertices.push(-1, -1);
  13580. vertices.push(1, -1);
  13581. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13582. var indices = [];
  13583. indices.push(0);
  13584. indices.push(1);
  13585. indices.push(2);
  13586. indices.push(0);
  13587. indices.push(2);
  13588. indices.push(3);
  13589. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13590. }
  13591. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13592. var postProcesses = this._scene.activeCamera._postProcesses;
  13593. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13594. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13595. return false;
  13596. }
  13597. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13598. return true;
  13599. };
  13600. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13601. var postProcesses = this._scene.activeCamera._postProcesses;
  13602. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13603. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13604. return;
  13605. }
  13606. var engine = this._scene.getEngine();
  13607. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13608. if (index < postProcessesTakenIndices.length - 1) {
  13609. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13610. } else {
  13611. if (targetTexture) {
  13612. engine.bindFramebuffer(targetTexture);
  13613. } else {
  13614. engine.restoreDefaultFramebuffer();
  13615. }
  13616. }
  13617. if (doNotPresent) {
  13618. break;
  13619. }
  13620. var pp = postProcesses[postProcessesTakenIndices[index]];
  13621. var effect = pp.apply();
  13622. if (effect) {
  13623. if (pp.onBeforeRender) {
  13624. pp.onBeforeRender(effect);
  13625. }
  13626. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13627. engine.draw(true, 0, 6);
  13628. }
  13629. }
  13630. engine.setDepthBuffer(true);
  13631. engine.setDepthWrite(true);
  13632. };
  13633. PostProcessManager.prototype.dispose = function () {
  13634. if (this._vertexBuffer) {
  13635. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13636. this._vertexBuffer = null;
  13637. }
  13638. if (this._indexBuffer) {
  13639. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13640. this._indexBuffer = null;
  13641. }
  13642. };
  13643. return PostProcessManager;
  13644. })();
  13645. BABYLON.PostProcessManager = PostProcessManager;
  13646. })(BABYLON || (BABYLON = {}));
  13647. var __extends = this.__extends || function (d, b) {
  13648. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13649. function __() { this.constructor = d; }
  13650. __.prototype = b.prototype;
  13651. d.prototype = new __();
  13652. };
  13653. var BABYLON;
  13654. (function (BABYLON) {
  13655. var PassPostProcess = (function (_super) {
  13656. __extends(PassPostProcess, _super);
  13657. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13658. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13659. }
  13660. return PassPostProcess;
  13661. })(BABYLON.PostProcess);
  13662. BABYLON.PassPostProcess = PassPostProcess;
  13663. })(BABYLON || (BABYLON = {}));
  13664. var __extends = this.__extends || function (d, b) {
  13665. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13666. function __() { this.constructor = d; }
  13667. __.prototype = b.prototype;
  13668. d.prototype = new __();
  13669. };
  13670. var BABYLON;
  13671. (function (BABYLON) {
  13672. var BlurPostProcess = (function (_super) {
  13673. __extends(BlurPostProcess, _super);
  13674. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13675. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13676. var _this = this;
  13677. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13678. this.direction = direction;
  13679. this.blurWidth = blurWidth;
  13680. this.onApply = function (effect) {
  13681. effect.setFloat2("screenSize", _this.width, _this.height);
  13682. effect.setVector2("direction", _this.direction);
  13683. effect.setFloat("blurWidth", _this.blurWidth);
  13684. };
  13685. }
  13686. return BlurPostProcess;
  13687. })(BABYLON.PostProcess);
  13688. BABYLON.BlurPostProcess = BlurPostProcess;
  13689. })(BABYLON || (BABYLON = {}));
  13690. var __extends = this.__extends || function (d, b) {
  13691. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13692. function __() { this.constructor = d; }
  13693. __.prototype = b.prototype;
  13694. d.prototype = new __();
  13695. };
  13696. var BABYLON;
  13697. (function (BABYLON) {
  13698. var FilterPostProcess = (function (_super) {
  13699. __extends(FilterPostProcess, _super);
  13700. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13701. var _this = this;
  13702. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13703. this.kernelMatrix = kernelMatrix;
  13704. this.onApply = function (effect) {
  13705. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13706. };
  13707. }
  13708. return FilterPostProcess;
  13709. })(BABYLON.PostProcess);
  13710. BABYLON.FilterPostProcess = FilterPostProcess;
  13711. })(BABYLON || (BABYLON = {}));
  13712. var __extends = this.__extends || function (d, b) {
  13713. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13714. function __() { this.constructor = d; }
  13715. __.prototype = b.prototype;
  13716. d.prototype = new __();
  13717. };
  13718. var BABYLON;
  13719. (function (BABYLON) {
  13720. var RefractionPostProcess = (function (_super) {
  13721. __extends(RefractionPostProcess, _super);
  13722. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13723. var _this = this;
  13724. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13725. this.color = color;
  13726. this.depth = depth;
  13727. this.colorLevel = colorLevel;
  13728. this.onActivate = function (cam) {
  13729. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13730. };
  13731. this.onApply = function (effect) {
  13732. effect.setColor3("baseColor", _this.color);
  13733. effect.setFloat("depth", _this.depth);
  13734. effect.setFloat("colorLevel", _this.colorLevel);
  13735. effect.setTexture("refractionSampler", _this._refRexture);
  13736. };
  13737. }
  13738. RefractionPostProcess.prototype.dispose = function (camera) {
  13739. if (this._refRexture) {
  13740. this._refRexture.dispose();
  13741. }
  13742. _super.prototype.dispose.call(this, camera);
  13743. };
  13744. return RefractionPostProcess;
  13745. })(BABYLON.PostProcess);
  13746. BABYLON.RefractionPostProcess = RefractionPostProcess;
  13747. })(BABYLON || (BABYLON = {}));
  13748. var __extends = this.__extends || function (d, b) {
  13749. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13750. function __() { this.constructor = d; }
  13751. __.prototype = b.prototype;
  13752. d.prototype = new __();
  13753. };
  13754. var BABYLON;
  13755. (function (BABYLON) {
  13756. var BlackAndWhitePostProcess = (function (_super) {
  13757. __extends(BlackAndWhitePostProcess, _super);
  13758. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13759. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  13760. }
  13761. return BlackAndWhitePostProcess;
  13762. })(BABYLON.PostProcess);
  13763. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  13764. })(BABYLON || (BABYLON = {}));
  13765. var __extends = this.__extends || function (d, b) {
  13766. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13767. function __() { this.constructor = d; }
  13768. __.prototype = b.prototype;
  13769. d.prototype = new __();
  13770. };
  13771. var BABYLON;
  13772. (function (BABYLON) {
  13773. var ConvolutionPostProcess = (function (_super) {
  13774. __extends(ConvolutionPostProcess, _super);
  13775. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  13776. var _this = this;
  13777. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  13778. this.kernel = kernel;
  13779. this.onApply = function (effect) {
  13780. effect.setFloat2("screenSize", _this.width, _this.height);
  13781. effect.setArray("kernel", _this.kernel);
  13782. };
  13783. }
  13784. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  13785. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  13786. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  13787. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  13788. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  13789. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  13790. return ConvolutionPostProcess;
  13791. })(BABYLON.PostProcess);
  13792. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  13793. })(BABYLON || (BABYLON = {}));
  13794. var __extends = this.__extends || function (d, b) {
  13795. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13796. function __() { this.constructor = d; }
  13797. __.prototype = b.prototype;
  13798. d.prototype = new __();
  13799. };
  13800. var BABYLON;
  13801. (function (BABYLON) {
  13802. var FxaaPostProcess = (function (_super) {
  13803. __extends(FxaaPostProcess, _super);
  13804. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13805. var _this = this;
  13806. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  13807. this.onSizeChanged = function () {
  13808. _this.texelWidth = 1.0 / _this.width;
  13809. _this.texelHeight = 1.0 / _this.height;
  13810. };
  13811. this.onApply = function (effect) {
  13812. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  13813. };
  13814. }
  13815. return FxaaPostProcess;
  13816. })(BABYLON.PostProcess);
  13817. BABYLON.FxaaPostProcess = FxaaPostProcess;
  13818. })(BABYLON || (BABYLON = {}));
  13819. var BABYLON;
  13820. (function (BABYLON) {
  13821. var LensFlare = (function () {
  13822. function LensFlare(size, position, color, imgUrl, system) {
  13823. this.size = size;
  13824. this.position = position;
  13825. this.dispose = function () {
  13826. if (this.texture) {
  13827. this.texture.dispose();
  13828. }
  13829. var index = this._system.lensFlares.indexOf(this);
  13830. this._system.lensFlares.splice(index, 1);
  13831. };
  13832. this.color = color || new BABYLON.Color3(1, 1, 1);
  13833. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  13834. this._system = system;
  13835. system.lensFlares.push(this);
  13836. }
  13837. return LensFlare;
  13838. })();
  13839. BABYLON.LensFlare = LensFlare;
  13840. })(BABYLON || (BABYLON = {}));
  13841. var BABYLON;
  13842. (function (BABYLON) {
  13843. var LensFlareSystem = (function () {
  13844. function LensFlareSystem(name, emitter, scene) {
  13845. this.name = name;
  13846. this.lensFlares = new Array();
  13847. this.borderLimit = 300;
  13848. this._vertexDeclaration = [2];
  13849. this._vertexStrideSize = 2 * 4;
  13850. this._isEnabled = true;
  13851. this._scene = scene;
  13852. this._emitter = emitter;
  13853. scene.lensFlareSystems.push(this);
  13854. this.meshesSelectionPredicate = function (m) {
  13855. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  13856. };
  13857. var vertices = [];
  13858. vertices.push(1, 1);
  13859. vertices.push(-1, 1);
  13860. vertices.push(-1, -1);
  13861. vertices.push(1, -1);
  13862. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13863. var indices = [];
  13864. indices.push(0);
  13865. indices.push(1);
  13866. indices.push(2);
  13867. indices.push(0);
  13868. indices.push(2);
  13869. indices.push(3);
  13870. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13871. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  13872. }
  13873. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  13874. get: function () {
  13875. return this._isEnabled;
  13876. },
  13877. set: function (value) {
  13878. this._isEnabled = value;
  13879. },
  13880. enumerable: true,
  13881. configurable: true
  13882. });
  13883. LensFlareSystem.prototype.getScene = function () {
  13884. return this._scene;
  13885. };
  13886. LensFlareSystem.prototype.getEmitter = function () {
  13887. return this._emitter;
  13888. };
  13889. LensFlareSystem.prototype.getEmitterPosition = function () {
  13890. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  13891. };
  13892. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  13893. var position = this.getEmitterPosition();
  13894. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  13895. this._positionX = position.x;
  13896. this._positionY = position.y;
  13897. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  13898. if (position.z > 0) {
  13899. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  13900. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  13901. return true;
  13902. }
  13903. }
  13904. return false;
  13905. };
  13906. LensFlareSystem.prototype._isVisible = function () {
  13907. if (!this._isEnabled) {
  13908. return false;
  13909. }
  13910. var emitterPosition = this.getEmitterPosition();
  13911. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  13912. var distance = direction.length();
  13913. direction.normalize();
  13914. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  13915. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  13916. return !pickInfo.hit || pickInfo.distance > distance;
  13917. };
  13918. LensFlareSystem.prototype.render = function () {
  13919. if (!this._effect.isReady())
  13920. return false;
  13921. var engine = this._scene.getEngine();
  13922. var viewport = this._scene.activeCamera.viewport;
  13923. var globalViewport = viewport.toGlobal(engine);
  13924. if (!this.computeEffectivePosition(globalViewport)) {
  13925. return false;
  13926. }
  13927. if (!this._isVisible()) {
  13928. return false;
  13929. }
  13930. var awayX;
  13931. var awayY;
  13932. if (this._positionX < this.borderLimit + globalViewport.x) {
  13933. awayX = this.borderLimit + globalViewport.x - this._positionX;
  13934. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  13935. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  13936. } else {
  13937. awayX = 0;
  13938. }
  13939. if (this._positionY < this.borderLimit + globalViewport.y) {
  13940. awayY = this.borderLimit + globalViewport.y - this._positionY;
  13941. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  13942. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  13943. } else {
  13944. awayY = 0;
  13945. }
  13946. var away = (awayX > awayY) ? awayX : awayY;
  13947. if (away > this.borderLimit) {
  13948. away = this.borderLimit;
  13949. }
  13950. var intensity = 1.0 - (away / this.borderLimit);
  13951. if (intensity < 0) {
  13952. return false;
  13953. }
  13954. if (intensity > 1.0) {
  13955. intensity = 1.0;
  13956. }
  13957. var centerX = globalViewport.x + globalViewport.width / 2;
  13958. var centerY = globalViewport.y + globalViewport.height / 2;
  13959. var distX = centerX - this._positionX;
  13960. var distY = centerY - this._positionY;
  13961. engine.enableEffect(this._effect);
  13962. engine.setState(false);
  13963. engine.setDepthBuffer(false);
  13964. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13965. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13966. for (var index = 0; index < this.lensFlares.length; index++) {
  13967. var flare = this.lensFlares[index];
  13968. var x = centerX - (distX * flare.position);
  13969. var y = centerY - (distY * flare.position);
  13970. var cw = flare.size;
  13971. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  13972. var cx = 2 * (x / globalViewport.width) - 1.0;
  13973. var cy = 1.0 - 2 * (y / globalViewport.height);
  13974. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  13975. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  13976. this._effect.setTexture("textureSampler", flare.texture);
  13977. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  13978. engine.draw(true, 0, 6);
  13979. }
  13980. engine.setDepthBuffer(true);
  13981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13982. return true;
  13983. };
  13984. LensFlareSystem.prototype.dispose = function () {
  13985. if (this._vertexBuffer) {
  13986. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13987. this._vertexBuffer = null;
  13988. }
  13989. if (this._indexBuffer) {
  13990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13991. this._indexBuffer = null;
  13992. }
  13993. while (this.lensFlares.length) {
  13994. this.lensFlares[0].dispose();
  13995. }
  13996. var index = this._scene.lensFlareSystems.indexOf(this);
  13997. this._scene.lensFlareSystems.splice(index, 1);
  13998. };
  13999. return LensFlareSystem;
  14000. })();
  14001. BABYLON.LensFlareSystem = LensFlareSystem;
  14002. })(BABYLON || (BABYLON = {}));
  14003. var BABYLON;
  14004. (function (BABYLON) {
  14005. var IntersectionInfo = (function () {
  14006. function IntersectionInfo(bu, bv, distance) {
  14007. this.bu = bu;
  14008. this.bv = bv;
  14009. this.distance = distance;
  14010. this.faceId = 0;
  14011. }
  14012. return IntersectionInfo;
  14013. })();
  14014. BABYLON.IntersectionInfo = IntersectionInfo;
  14015. var PickingInfo = (function () {
  14016. function PickingInfo() {
  14017. this.hit = false;
  14018. this.distance = 0;
  14019. this.pickedPoint = null;
  14020. this.pickedMesh = null;
  14021. this.bu = 0;
  14022. this.bv = 0;
  14023. this.faceId = -1;
  14024. }
  14025. PickingInfo.prototype.getNormal = function () {
  14026. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14027. return null;
  14028. }
  14029. var indices = this.pickedMesh.getIndices();
  14030. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14031. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  14032. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  14033. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  14034. normal0 = normal0.scale(this.bu);
  14035. normal1 = normal1.scale(this.bv);
  14036. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  14037. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  14038. };
  14039. PickingInfo.prototype.getTextureCoordinates = function () {
  14040. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14041. return null;
  14042. }
  14043. var indices = this.pickedMesh.getIndices();
  14044. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14045. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  14046. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  14047. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  14048. uv0 = uv0.scale(this.bu);
  14049. uv1 = uv1.scale(this.bv);
  14050. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  14051. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  14052. };
  14053. return PickingInfo;
  14054. })();
  14055. BABYLON.PickingInfo = PickingInfo;
  14056. })(BABYLON || (BABYLON = {}));
  14057. var BABYLON;
  14058. (function (BABYLON) {
  14059. var FilesInput = (function () {
  14060. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  14061. this.engine = p_engine;
  14062. this.canvas = p_canvas;
  14063. this.currentScene = p_scene;
  14064. this.sceneLoadedCallback = p_sceneLoadedCallback;
  14065. this.progressCallback = p_progressCallback;
  14066. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  14067. this.textureLoadingCallback = p_textureLoadingCallback;
  14068. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  14069. }
  14070. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  14071. var _this = this;
  14072. if (p_elementToMonitor) {
  14073. this.elementToMonitor = p_elementToMonitor;
  14074. this.elementToMonitor.addEventListener("dragenter", function (e) {
  14075. _this.drag(e);
  14076. }, false);
  14077. this.elementToMonitor.addEventListener("dragover", function (e) {
  14078. _this.drag(e);
  14079. }, false);
  14080. this.elementToMonitor.addEventListener("drop", function (e) {
  14081. _this.drop(e);
  14082. }, false);
  14083. }
  14084. };
  14085. FilesInput.prototype.renderFunction = function () {
  14086. if (this.additionnalRenderLoopLogicCallback) {
  14087. this.additionnalRenderLoopLogicCallback();
  14088. }
  14089. if (this.currentScene) {
  14090. if (this.textureLoadingCallback) {
  14091. var remaining = this.currentScene.getWaitingItemsCount();
  14092. if (remaining > 0) {
  14093. this.textureLoadingCallback(remaining);
  14094. }
  14095. }
  14096. this.currentScene.render();
  14097. }
  14098. };
  14099. FilesInput.prototype.drag = function (e) {
  14100. e.stopPropagation();
  14101. e.preventDefault();
  14102. };
  14103. FilesInput.prototype.drop = function (eventDrop) {
  14104. eventDrop.stopPropagation();
  14105. eventDrop.preventDefault();
  14106. this.loadFiles(eventDrop);
  14107. };
  14108. FilesInput.prototype.loadFiles = function (event) {
  14109. var _this = this;
  14110. var that = this;
  14111. if (this.startingProcessingFilesCallback)
  14112. this.startingProcessingFilesCallback();
  14113. var sceneFileToLoad;
  14114. var filesToLoad;
  14115. if (event && event.dataTransfer && event.dataTransfer.files) {
  14116. filesToLoad = event.dataTransfer.files;
  14117. }
  14118. if (event && event.target && event.target.files) {
  14119. filesToLoad = event.target.files;
  14120. }
  14121. if (filesToLoad && filesToLoad.length > 0) {
  14122. for (var i = 0; i < filesToLoad.length; i++) {
  14123. switch (filesToLoad[i].type) {
  14124. case "image/jpeg":
  14125. case "image/png":
  14126. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  14127. break;
  14128. case "image/targa":
  14129. case "image/vnd.ms-dds":
  14130. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  14131. break;
  14132. default:
  14133. 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) {
  14134. sceneFileToLoad = filesToLoad[i];
  14135. }
  14136. break;
  14137. }
  14138. }
  14139. if (sceneFileToLoad) {
  14140. if (this.currentScene) {
  14141. this.engine.stopRenderLoop();
  14142. this.currentScene.dispose();
  14143. }
  14144. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  14145. that.currentScene = newScene;
  14146. that.currentScene.executeWhenReady(function () {
  14147. if (that.currentScene.activeCamera) {
  14148. that.currentScene.activeCamera.attachControl(that.canvas);
  14149. }
  14150. if (that.sceneLoadedCallback) {
  14151. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  14152. }
  14153. that.engine.runRenderLoop(function () {
  14154. that.renderFunction();
  14155. });
  14156. });
  14157. }, function (progress) {
  14158. if (_this.progressCallback) {
  14159. _this.progressCallback(progress);
  14160. }
  14161. });
  14162. } else {
  14163. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  14164. }
  14165. }
  14166. };
  14167. FilesInput.FilesTextures = new Array();
  14168. FilesInput.FilesToLoad = new Array();
  14169. return FilesInput;
  14170. })();
  14171. BABYLON.FilesInput = FilesInput;
  14172. })(BABYLON || (BABYLON = {}));
  14173. var BABYLON;
  14174. (function (BABYLON) {
  14175. var OimoJSPlugin = (function () {
  14176. function OimoJSPlugin() {
  14177. this._registeredMeshes = [];
  14178. /**
  14179. * Update the body position according to the mesh position
  14180. * @param mesh
  14181. */
  14182. this.updateBodyPosition = function (mesh) {
  14183. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14184. var registeredMesh = this._registeredMeshes[index];
  14185. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14186. var body = registeredMesh.body.body;
  14187. mesh.computeWorldMatrix(true);
  14188. var center = mesh.getBoundingInfo().boundingBox.center;
  14189. body.setPosition(center.x, center.y, center.z);
  14190. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14191. return;
  14192. }
  14193. if (registeredMesh.mesh.parent === mesh) {
  14194. mesh.computeWorldMatrix(true);
  14195. registeredMesh.mesh.computeWorldMatrix(true);
  14196. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14197. var absoluteRotation = mesh.rotation;
  14198. body = registeredMesh.body.body;
  14199. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14200. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14201. return;
  14202. }
  14203. }
  14204. };
  14205. }
  14206. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14207. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14208. };
  14209. OimoJSPlugin.prototype.initialize = function (iterations) {
  14210. this._world = new OIMO.World();
  14211. this._world.clear();
  14212. };
  14213. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14214. this._world.gravity = gravity;
  14215. };
  14216. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14217. var body = null;
  14218. this.unregisterMesh(mesh);
  14219. mesh.computeWorldMatrix(true);
  14220. switch (impostor) {
  14221. case BABYLON.PhysicsEngine.SphereImpostor:
  14222. var bbox = mesh.getBoundingInfo().boundingBox;
  14223. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14224. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14225. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14226. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14227. var deltaPosition = mesh.position.subtract(bbox.center);
  14228. body = new OIMO.Body({
  14229. type: 'sphere',
  14230. size: [size],
  14231. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14232. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14233. move: options.mass != 0,
  14234. config: [options.mass, options.friction, options.restitution],
  14235. world: this._world
  14236. });
  14237. this._registeredMeshes.push({
  14238. mesh: mesh,
  14239. body: body,
  14240. delta: deltaPosition
  14241. });
  14242. break;
  14243. case BABYLON.PhysicsEngine.PlaneImpostor:
  14244. case BABYLON.PhysicsEngine.BoxImpostor:
  14245. bbox = mesh.getBoundingInfo().boundingBox;
  14246. var min = bbox.minimumWorld;
  14247. var max = bbox.maximumWorld;
  14248. var box = max.subtract(min);
  14249. var sizeX = this._checkWithEpsilon(box.x);
  14250. var sizeY = this._checkWithEpsilon(box.y);
  14251. var sizeZ = this._checkWithEpsilon(box.z);
  14252. var deltaPosition = mesh.position.subtract(bbox.center);
  14253. body = new OIMO.Body({
  14254. type: 'box',
  14255. size: [sizeX, sizeY, sizeZ],
  14256. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14257. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14258. move: options.mass != 0,
  14259. config: [options.mass, options.friction, options.restitution],
  14260. world: this._world
  14261. });
  14262. this._registeredMeshes.push({
  14263. mesh: mesh,
  14264. body: body,
  14265. delta: deltaPosition
  14266. });
  14267. break;
  14268. }
  14269. return body;
  14270. };
  14271. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14272. var types = [], sizes = [], positions = [], rotations = [];
  14273. var initialMesh = parts[0].mesh;
  14274. for (var index = 0; index < parts.length; index++) {
  14275. var part = parts[index];
  14276. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14277. types.push(bodyParameters.type);
  14278. sizes.push.apply(sizes, bodyParameters.size);
  14279. positions.push.apply(positions, bodyParameters.pos);
  14280. rotations.push.apply(rotations, bodyParameters.rot);
  14281. }
  14282. var body = new OIMO.Body({
  14283. type: types,
  14284. size: sizes,
  14285. pos: positions,
  14286. rot: rotations,
  14287. move: options.mass != 0,
  14288. config: [options.mass, options.friction, options.restitution],
  14289. world: this._world
  14290. });
  14291. this._registeredMeshes.push({
  14292. mesh: initialMesh,
  14293. body: body
  14294. });
  14295. return body;
  14296. };
  14297. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14298. var bodyParameters = null;
  14299. var mesh = part.mesh;
  14300. switch (part.impostor) {
  14301. case BABYLON.PhysicsEngine.SphereImpostor:
  14302. var bbox = mesh.getBoundingInfo().boundingBox;
  14303. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14304. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14305. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14306. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14307. bodyParameters = {
  14308. type: 'sphere',
  14309. /* bug with oimo : sphere needs 3 sizes in this case */
  14310. size: [size, -1, -1],
  14311. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  14312. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14313. };
  14314. break;
  14315. case BABYLON.PhysicsEngine.PlaneImpostor:
  14316. case BABYLON.PhysicsEngine.BoxImpostor:
  14317. bbox = mesh.getBoundingInfo().boundingBox;
  14318. var min = bbox.minimumWorld;
  14319. var max = bbox.maximumWorld;
  14320. var box = max.subtract(min);
  14321. var sizeX = this._checkWithEpsilon(box.x);
  14322. var sizeY = this._checkWithEpsilon(box.y);
  14323. var sizeZ = this._checkWithEpsilon(box.z);
  14324. var relativePosition = mesh.position;
  14325. bodyParameters = {
  14326. type: 'box',
  14327. size: [sizeX, sizeY, sizeZ],
  14328. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  14329. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14330. };
  14331. break;
  14332. }
  14333. return bodyParameters;
  14334. };
  14335. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  14336. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14337. var registeredMesh = this._registeredMeshes[index];
  14338. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14339. if (registeredMesh.body) {
  14340. this._world.removeRigidBody(registeredMesh.body.body);
  14341. this._unbindBody(registeredMesh.body);
  14342. }
  14343. this._registeredMeshes.splice(index, 1);
  14344. return;
  14345. }
  14346. }
  14347. };
  14348. OimoJSPlugin.prototype._unbindBody = function (body) {
  14349. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14350. var registeredMesh = this._registeredMeshes[index];
  14351. if (registeredMesh.body === body) {
  14352. registeredMesh.body = null;
  14353. }
  14354. }
  14355. };
  14356. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  14357. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14358. var registeredMesh = this._registeredMeshes[index];
  14359. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14360. var mass = registeredMesh.body.body.massInfo.mass;
  14361. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  14362. return;
  14363. }
  14364. }
  14365. };
  14366. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14367. var body1 = null, body2 = null;
  14368. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14369. var registeredMesh = this._registeredMeshes[index];
  14370. if (registeredMesh.mesh === mesh1) {
  14371. body1 = registeredMesh.body.body;
  14372. } else if (registeredMesh.mesh === mesh2) {
  14373. body2 = registeredMesh.body.body;
  14374. }
  14375. }
  14376. if (!body1 || !body2) {
  14377. return false;
  14378. }
  14379. if (!options) {
  14380. options = {};
  14381. }
  14382. new OIMO.Link({
  14383. type: options.type,
  14384. body1: body1,
  14385. body2: body2,
  14386. min: options.min,
  14387. max: options.max,
  14388. axe1: options.axe1,
  14389. axe2: options.axe2,
  14390. pos1: [pivot1.x, pivot1.y, pivot1.z],
  14391. pos2: [pivot2.x, pivot2.y, pivot2.z],
  14392. collision: options.collision,
  14393. spring: options.spring,
  14394. world: this._world
  14395. });
  14396. return true;
  14397. };
  14398. OimoJSPlugin.prototype.dispose = function () {
  14399. this._world.clear();
  14400. while (this._registeredMeshes.length) {
  14401. this.unregisterMesh(this._registeredMeshes[0].mesh);
  14402. }
  14403. };
  14404. OimoJSPlugin.prototype.isSupported = function () {
  14405. return OIMO !== undefined;
  14406. };
  14407. OimoJSPlugin.prototype._getLastShape = function (body) {
  14408. var lastShape = body.shapes;
  14409. while (lastShape.next) {
  14410. lastShape = lastShape.next;
  14411. }
  14412. return lastShape;
  14413. };
  14414. OimoJSPlugin.prototype.runOneStep = function (time) {
  14415. this._world.step();
  14416. var i = this._registeredMeshes.length;
  14417. var m;
  14418. while (i--) {
  14419. var body = this._registeredMeshes[i].body.body;
  14420. var mesh = this._registeredMeshes[i].mesh;
  14421. var delta = this._registeredMeshes[i].delta;
  14422. if (!body.sleeping) {
  14423. if (body.shapes.next) {
  14424. var parentShape = this._getLastShape(body);
  14425. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  14426. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  14427. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  14428. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  14429. if (!mesh.rotationQuaternion) {
  14430. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14431. }
  14432. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14433. } else {
  14434. m = body.getMatrix();
  14435. mtx = BABYLON.Matrix.FromArray(m);
  14436. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  14437. if (!delta) {
  14438. mesh.position.x = bodyX;
  14439. mesh.position.y = bodyY;
  14440. mesh.position.z = bodyZ;
  14441. } else {
  14442. mesh.position.x = bodyX + delta.x;
  14443. mesh.position.y = bodyY + delta.y;
  14444. mesh.position.z = bodyZ + delta.z;
  14445. }
  14446. if (!mesh.rotationQuaternion) {
  14447. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14448. }
  14449. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14450. }
  14451. }
  14452. }
  14453. };
  14454. return OimoJSPlugin;
  14455. })();
  14456. BABYLON.OimoJSPlugin = OimoJSPlugin;
  14457. })(BABYLON || (BABYLON = {}));
  14458. var BABYLON;
  14459. (function (BABYLON) {
  14460. var PhysicsEngine = (function () {
  14461. function PhysicsEngine(plugin) {
  14462. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  14463. }
  14464. PhysicsEngine.prototype._initialize = function (gravity) {
  14465. this._currentPlugin.initialize();
  14466. this._setGravity(gravity);
  14467. };
  14468. PhysicsEngine.prototype._runOneStep = function (delta) {
  14469. if (delta > 0.1) {
  14470. delta = 0.1;
  14471. } else if (delta <= 0) {
  14472. delta = 1.0 / 60.0;
  14473. }
  14474. this._currentPlugin.runOneStep(delta);
  14475. };
  14476. PhysicsEngine.prototype._setGravity = function (gravity) {
  14477. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14478. this._currentPlugin.setGravity(this.gravity);
  14479. };
  14480. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14481. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14482. };
  14483. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14484. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14485. };
  14486. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14487. this._currentPlugin.unregisterMesh(mesh);
  14488. };
  14489. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14490. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14491. };
  14492. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14493. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14494. };
  14495. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14496. this._currentPlugin.updateBodyPosition(mesh);
  14497. };
  14498. PhysicsEngine.prototype.dispose = function () {
  14499. this._currentPlugin.dispose();
  14500. };
  14501. PhysicsEngine.prototype.isSupported = function () {
  14502. return this._currentPlugin.isSupported();
  14503. };
  14504. PhysicsEngine.NoImpostor = 0;
  14505. PhysicsEngine.SphereImpostor = 1;
  14506. PhysicsEngine.BoxImpostor = 2;
  14507. PhysicsEngine.PlaneImpostor = 3;
  14508. PhysicsEngine.MeshImpostor = 4;
  14509. PhysicsEngine.CapsuleImpostor = 5;
  14510. PhysicsEngine.ConeImpostor = 6;
  14511. PhysicsEngine.CylinderImpostor = 7;
  14512. PhysicsEngine.ConvexHullImpostor = 8;
  14513. PhysicsEngine.Epsilon = 0.001;
  14514. return PhysicsEngine;
  14515. })();
  14516. BABYLON.PhysicsEngine = PhysicsEngine;
  14517. })(BABYLON || (BABYLON = {}));
  14518. var BABYLON;
  14519. (function (BABYLON) {
  14520. var serializeLight = function (light) {
  14521. var serializationObject = {};
  14522. serializationObject.name = light.name;
  14523. serializationObject.id = light.id;
  14524. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14525. if (light instanceof BABYLON.PointLight) {
  14526. serializationObject.type = 0;
  14527. serializationObject.position = light.position.asArray();
  14528. } else if (light instanceof BABYLON.DirectionalLight) {
  14529. serializationObject.type = 1;
  14530. var directionalLight = light;
  14531. serializationObject.position = directionalLight.position.asArray();
  14532. serializationObject.direction = directionalLight.direction.asArray();
  14533. } else if (light instanceof BABYLON.SpotLight) {
  14534. serializationObject.type = 2;
  14535. var spotLight = light;
  14536. serializationObject.position = spotLight.position.asArray();
  14537. serializationObject.direction = spotLight.position.asArray();
  14538. serializationObject.angle = spotLight.angle;
  14539. serializationObject.exponent = spotLight.exponent;
  14540. } else if (light instanceof BABYLON.HemisphericLight) {
  14541. serializationObject.type = 3;
  14542. var hemisphericLight = light;
  14543. serializationObject.direction = hemisphericLight.direction.asArray();
  14544. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14545. }
  14546. if (light.intensity) {
  14547. serializationObject.intensity = light.intensity;
  14548. }
  14549. serializationObject.range = light.range;
  14550. serializationObject.diffuse = light.diffuse.asArray();
  14551. serializationObject.specular = light.specular.asArray();
  14552. return serializationObject;
  14553. };
  14554. var serializeFresnelParameter = function (fresnelParameter) {
  14555. var serializationObject = {};
  14556. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14557. serializationObject.leftColor = fresnelParameter.leftColor;
  14558. serializationObject.rightColor = fresnelParameter.rightColor;
  14559. serializationObject.bias = fresnelParameter.bias;
  14560. serializationObject.power = fresnelParameter.power;
  14561. return serializationObject;
  14562. };
  14563. var serializeCamera = function (camera) {
  14564. var serializationObject = {};
  14565. serializationObject.name = camera.name;
  14566. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14567. serializationObject.id = camera.id;
  14568. serializationObject.position = camera.position.asArray();
  14569. if (camera.parent) {
  14570. serializationObject.parentId = camera.parent.id;
  14571. }
  14572. serializationObject.rotation = camera.rotation.asArray();
  14573. if (camera.lockedTarget && camera.lockedTarget.id) {
  14574. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14575. }
  14576. serializationObject.fov = camera.fov;
  14577. serializationObject.minZ = camera.minZ;
  14578. serializationObject.maxZ = camera.maxZ;
  14579. serializationObject.speed = camera.speed;
  14580. serializationObject.inertia = camera.inertia;
  14581. serializationObject.checkCollisions = camera.checkCollisions;
  14582. serializationObject.applyGravity = camera.applyGravity;
  14583. if (camera.ellipsoid) {
  14584. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14585. }
  14586. appendAnimations(camera, serializationObject);
  14587. serializationObject.layerMask = camera.layerMask;
  14588. return serializationObject;
  14589. };
  14590. var appendAnimations = function (source, destination) {
  14591. if (source.animations) {
  14592. destination.animations = [];
  14593. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14594. var animation = source.animations[animationIndex];
  14595. destination.animations.push(serializeAnimation(animation));
  14596. }
  14597. }
  14598. };
  14599. var serializeAnimation = function (animation) {
  14600. var serializationObject = {};
  14601. serializationObject.name = animation.name;
  14602. serializationObject.property = animation.targetProperty;
  14603. serializationObject.framePerSecond = animation.framePerSecond;
  14604. serializationObject.dataType = animation.dataType;
  14605. serializationObject.loopBehavior = animation.loopMode;
  14606. var dataType = animation.dataType;
  14607. serializationObject.keys = [];
  14608. var keys = animation.getKeys();
  14609. for (var index = 0; index < keys.length; index++) {
  14610. var animationKey = keys[index];
  14611. var key = {};
  14612. key.frame = animationKey.frame;
  14613. switch (dataType) {
  14614. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14615. key.values = [animationKey.value];
  14616. break;
  14617. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14618. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14619. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14620. key.values = animationKey.value.asArray();
  14621. break;
  14622. }
  14623. serializationObject.keys.push(key);
  14624. }
  14625. return serializationObject;
  14626. };
  14627. var serializeMultiMaterial = function (material) {
  14628. var serializationObject = {};
  14629. serializationObject.name = material.name;
  14630. serializationObject.id = material.id;
  14631. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14632. serializationObject.materials = [];
  14633. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14634. var subMat = material.subMaterials[matIndex];
  14635. if (subMat) {
  14636. serializationObject.materials.push(subMat.id);
  14637. } else {
  14638. serializationObject.materials.push(null);
  14639. }
  14640. }
  14641. return serializationObject;
  14642. };
  14643. var serializeMaterial = function (material) {
  14644. var serializationObject = {};
  14645. serializationObject.name = material.name;
  14646. serializationObject.ambient = material.ambientColor.asArray();
  14647. serializationObject.diffuse = material.diffuseColor.asArray();
  14648. serializationObject.specular = material.specularColor.asArray();
  14649. serializationObject.specularPower = material.specularPower;
  14650. serializationObject.emissive = material.emissiveColor.asArray();
  14651. serializationObject.alpha = material.alpha;
  14652. serializationObject.id = material.id;
  14653. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14654. serializationObject.backFaceCulling = material.backFaceCulling;
  14655. if (material.diffuseTexture) {
  14656. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14657. }
  14658. if (material.diffuseFresnelParameters) {
  14659. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14660. }
  14661. if (material.ambientTexture) {
  14662. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14663. }
  14664. if (material.opacityTexture) {
  14665. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14666. }
  14667. if (material.opacityFresnelParameters) {
  14668. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14669. }
  14670. if (material.reflectionTexture) {
  14671. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14672. }
  14673. if (material.reflectionFresnelParameters) {
  14674. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14675. }
  14676. if (material.emissiveTexture) {
  14677. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14678. }
  14679. if (material.emissiveFresnelParameters) {
  14680. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14681. }
  14682. if (material.specularTexture) {
  14683. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14684. }
  14685. if (material.bumpTexture) {
  14686. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14687. }
  14688. return serializationObject;
  14689. };
  14690. var serializeTexture = function (texture) {
  14691. var serializationObject = {};
  14692. if (!texture.name) {
  14693. return null;
  14694. }
  14695. if (texture instanceof BABYLON.CubeTexture) {
  14696. serializationObject.name = texture.name;
  14697. serializationObject.hasAlpha = texture.hasAlpha;
  14698. serializationObject.level = texture.level;
  14699. serializationObject.coordinatesMode = texture.coordinatesMode;
  14700. return serializationObject;
  14701. }
  14702. if (texture instanceof BABYLON.MirrorTexture) {
  14703. var mirrorTexture = texture;
  14704. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14705. serializationObject.renderList = [];
  14706. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14707. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14708. }
  14709. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14710. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14711. var renderTargetTexture = texture;
  14712. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14713. serializationObject.renderList = [];
  14714. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14715. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14716. }
  14717. }
  14718. var regularTexture = texture;
  14719. serializationObject.name = texture.name;
  14720. serializationObject.hasAlpha = texture.hasAlpha;
  14721. serializationObject.level = texture.level;
  14722. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14723. serializationObject.coordinatesMode = texture.coordinatesMode;
  14724. serializationObject.uOffset = regularTexture.uOffset;
  14725. serializationObject.vOffset = regularTexture.vOffset;
  14726. serializationObject.uScale = regularTexture.uScale;
  14727. serializationObject.vScale = regularTexture.vScale;
  14728. serializationObject.uAng = regularTexture.uAng;
  14729. serializationObject.vAng = regularTexture.vAng;
  14730. serializationObject.wAng = regularTexture.wAng;
  14731. serializationObject.wrapU = texture.wrapU;
  14732. serializationObject.wrapV = texture.wrapV;
  14733. appendAnimations(texture, serializationObject);
  14734. return serializationObject;
  14735. };
  14736. var serializeSkeleton = function (skeleton) {
  14737. var serializationObject = {};
  14738. serializationObject.name = skeleton.name;
  14739. serializationObject.id = skeleton.id;
  14740. serializationObject.bones = [];
  14741. for (var index = 0; index < skeleton.bones.length; index++) {
  14742. var bone = skeleton.bones[index];
  14743. var serializedBone = {
  14744. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  14745. name: bone.name,
  14746. matrix: bone.getLocalMatrix().toArray()
  14747. };
  14748. serializationObject.bones.push(serializedBone);
  14749. if (bone.animations && bone.animations.length > 0) {
  14750. serializedBone.animation = serializeAnimation(bone.animations[0]);
  14751. }
  14752. }
  14753. return serializationObject;
  14754. };
  14755. var serializeParticleSystem = function (particleSystem) {
  14756. var serializationObject = {};
  14757. serializationObject.emitterId = particleSystem.emitter.id;
  14758. serializationObject.capacity = particleSystem.getCapacity();
  14759. if (particleSystem.particleTexture) {
  14760. serializationObject.textureName = particleSystem.particleTexture.name;
  14761. }
  14762. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  14763. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  14764. serializationObject.minSize = particleSystem.minSize;
  14765. serializationObject.maxSize = particleSystem.maxSize;
  14766. serializationObject.minLifeTime = particleSystem.minLifeTime;
  14767. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  14768. serializationObject.emitRate = particleSystem.emitRate;
  14769. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  14770. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  14771. serializationObject.gravity = particleSystem.gravity.asArray();
  14772. serializationObject.direction1 = particleSystem.direction1.asArray();
  14773. serializationObject.direction2 = particleSystem.direction2.asArray();
  14774. serializationObject.color1 = particleSystem.color1.asArray();
  14775. serializationObject.color2 = particleSystem.color2.asArray();
  14776. serializationObject.colorDead = particleSystem.colorDead.asArray();
  14777. serializationObject.updateSpeed = particleSystem.updateSpeed;
  14778. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  14779. serializationObject.textureMask = particleSystem.textureMask.asArray();
  14780. serializationObject.blendMode = particleSystem.blendMode;
  14781. return serializationObject;
  14782. };
  14783. var serializeLensFlareSystem = function (lensFlareSystem) {
  14784. var serializationObject = {};
  14785. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  14786. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  14787. serializationObject.flares = [];
  14788. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  14789. var flare = lensFlareSystem.lensFlares[index];
  14790. serializationObject.flares.push({
  14791. size: flare.size,
  14792. position: flare.position,
  14793. color: flare.color.asArray(),
  14794. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  14795. });
  14796. }
  14797. return serializationObject;
  14798. };
  14799. var serializeShadowGenerator = function (light) {
  14800. var serializationObject = {};
  14801. var shadowGenerator = light.getShadowGenerator();
  14802. serializationObject.lightId = light.id;
  14803. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  14804. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  14805. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  14806. serializationObject.renderList = [];
  14807. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  14808. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  14809. serializationObject.renderList.push(mesh.id);
  14810. }
  14811. return serializationObject;
  14812. };
  14813. var serializedGeometries = [];
  14814. var serializeGeometry = function (geometry, serializationGeometries) {
  14815. if (serializedGeometries[geometry.id]) {
  14816. return;
  14817. }
  14818. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  14819. serializationGeometries.boxes.push(serializeBox(geometry));
  14820. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  14821. serializationGeometries.spheres.push(serializeSphere(geometry));
  14822. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  14823. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  14824. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  14825. serializationGeometries.toruses.push(serializeTorus(geometry));
  14826. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  14827. serializationGeometries.grounds.push(serializeGround(geometry));
  14828. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  14829. serializationGeometries.planes.push(serializePlane(geometry));
  14830. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  14831. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  14832. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  14833. throw new Error("Unknow primitive type");
  14834. } else {
  14835. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  14836. }
  14837. serializedGeometries[geometry.id] = true;
  14838. };
  14839. var serializeGeometryBase = function (geometry) {
  14840. var serializationObject = {};
  14841. serializationObject.id = geometry.id;
  14842. if (BABYLON.Tags.HasTags(geometry)) {
  14843. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  14844. }
  14845. return serializationObject;
  14846. };
  14847. var serializeVertexData = function (vertexData) {
  14848. var serializationObject = serializeGeometryBase(vertexData);
  14849. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14850. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14851. }
  14852. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14853. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14854. }
  14855. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14856. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14857. }
  14858. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14859. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  14860. }
  14861. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14862. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  14863. }
  14864. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14865. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14866. serializationObject.matricesIndices._isExpanded = true;
  14867. }
  14868. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14869. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14870. }
  14871. serializationObject.indices = vertexData.getIndices();
  14872. return serializationObject;
  14873. };
  14874. var serializePrimitive = function (primitive) {
  14875. var serializationObject = serializeGeometryBase(primitive);
  14876. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  14877. return serializationObject;
  14878. };
  14879. var serializeBox = function (box) {
  14880. var serializationObject = serializePrimitive(box);
  14881. serializationObject.size = box.size;
  14882. return serializationObject;
  14883. };
  14884. var serializeSphere = function (sphere) {
  14885. var serializationObject = serializePrimitive(sphere);
  14886. serializationObject.segments = sphere.segments;
  14887. serializationObject.diameter = sphere.diameter;
  14888. return serializationObject;
  14889. };
  14890. var serializeCylinder = function (cylinder) {
  14891. var serializationObject = serializePrimitive(cylinder);
  14892. serializationObject.height = cylinder.height;
  14893. serializationObject.diameterTop = cylinder.diameterTop;
  14894. serializationObject.diameterBottom = cylinder.diameterBottom;
  14895. serializationObject.tessellation = cylinder.tessellation;
  14896. return serializationObject;
  14897. };
  14898. var serializeTorus = function (torus) {
  14899. var serializationObject = serializePrimitive(torus);
  14900. serializationObject.diameter = torus.diameter;
  14901. serializationObject.thickness = torus.thickness;
  14902. serializationObject.tessellation = torus.tessellation;
  14903. return serializationObject;
  14904. };
  14905. var serializeGround = function (ground) {
  14906. var serializationObject = serializePrimitive(ground);
  14907. serializationObject.width = ground.width;
  14908. serializationObject.height = ground.height;
  14909. serializationObject.subdivisions = ground.subdivisions;
  14910. return serializationObject;
  14911. };
  14912. var serializePlane = function (plane) {
  14913. var serializationObject = serializePrimitive(plane);
  14914. serializationObject.size = plane.size;
  14915. return serializationObject;
  14916. };
  14917. var serializeTorusKnot = function (torusKnot) {
  14918. var serializationObject = serializePrimitive(torusKnot);
  14919. serializationObject.radius = torusKnot.radius;
  14920. serializationObject.tube = torusKnot.tube;
  14921. serializationObject.radialSegments = torusKnot.radialSegments;
  14922. serializationObject.tubularSegments = torusKnot.tubularSegments;
  14923. serializationObject.p = torusKnot.p;
  14924. serializationObject.q = torusKnot.q;
  14925. return serializationObject;
  14926. };
  14927. var serializeMesh = function (mesh, serializationScene) {
  14928. var serializationObject = {};
  14929. serializationObject.name = mesh.name;
  14930. serializationObject.id = mesh.id;
  14931. if (BABYLON.Tags.HasTags(mesh)) {
  14932. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  14933. }
  14934. serializationObject.position = mesh.position.asArray();
  14935. if (mesh.rotationQuaternion) {
  14936. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  14937. } else if (mesh.rotation) {
  14938. serializationObject.rotation = mesh.rotation.asArray();
  14939. }
  14940. serializationObject.scaling = mesh.scaling.asArray();
  14941. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  14942. serializationObject.isEnabled = mesh.isEnabled();
  14943. serializationObject.isVisible = mesh.isVisible;
  14944. serializationObject.infiniteDistance = mesh.infiniteDistance;
  14945. serializationObject.pickable = mesh.isPickable;
  14946. serializationObject.receiveShadows = mesh.receiveShadows;
  14947. serializationObject.billboardMode = mesh.billboardMode;
  14948. serializationObject.visibility = mesh.visibility;
  14949. serializationObject.checkCollisions = mesh.checkCollisions;
  14950. if (mesh.parent) {
  14951. serializationObject.parentId = mesh.parent.id;
  14952. }
  14953. var geometry = mesh._geometry;
  14954. if (geometry) {
  14955. var geometryId = geometry.id;
  14956. serializationObject.geometryId = geometryId;
  14957. if (!mesh.getScene().getGeometryByID(geometryId)) {
  14958. serializeGeometry(geometry, serializationScene.geometries);
  14959. }
  14960. serializationObject.subMeshes = [];
  14961. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  14962. var subMesh = mesh.subMeshes[subIndex];
  14963. serializationObject.subMeshes.push({
  14964. materialIndex: subMesh.materialIndex,
  14965. verticesStart: subMesh.verticesStart,
  14966. verticesCount: subMesh.verticesCount,
  14967. indexStart: subMesh.indexStart,
  14968. indexCount: subMesh.indexCount
  14969. });
  14970. }
  14971. }
  14972. if (mesh.material) {
  14973. serializationObject.materialId = mesh.material.id;
  14974. } else {
  14975. mesh.material = null;
  14976. }
  14977. if (mesh.skeleton) {
  14978. serializationObject.skeletonId = mesh.skeleton.id;
  14979. }
  14980. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  14981. serializationObject.physicsMass = mesh.getPhysicsMass();
  14982. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  14983. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  14984. switch (mesh.getPhysicsImpostor()) {
  14985. case BABYLON.PhysicsEngine.BoxImpostor:
  14986. serializationObject.physicsImpostor = 1;
  14987. break;
  14988. case BABYLON.PhysicsEngine.SphereImpostor:
  14989. serializationObject.physicsImpostor = 2;
  14990. break;
  14991. }
  14992. }
  14993. serializationObject.instances = [];
  14994. for (var index = 0; index < mesh.instances.length; index++) {
  14995. var instance = mesh.instances[index];
  14996. var serializationInstance = {
  14997. name: instance.name,
  14998. position: instance.position,
  14999. rotation: instance.rotation,
  15000. rotationQuaternion: instance.rotationQuaternion,
  15001. scaling: instance.scaling
  15002. };
  15003. serializationObject.instances.push(serializationInstance);
  15004. appendAnimations(instance, serializationInstance);
  15005. }
  15006. appendAnimations(mesh, serializationObject);
  15007. serializationObject.layerMask = mesh.layerMask;
  15008. return serializationObject;
  15009. };
  15010. var SceneSerializer = (function () {
  15011. function SceneSerializer() {
  15012. }
  15013. SceneSerializer.Serialize = function (scene) {
  15014. var serializationObject = {};
  15015. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15016. serializationObject.autoClear = scene.autoClear;
  15017. serializationObject.clearColor = scene.clearColor.asArray();
  15018. serializationObject.ambientColor = scene.ambientColor.asArray();
  15019. serializationObject.gravity = scene.gravity.asArray();
  15020. if (scene.fogMode && scene.fogMode !== 0) {
  15021. serializationObject.fogMode = scene.fogMode;
  15022. serializationObject.fogColor = scene.fogColor.asArray();
  15023. serializationObject.fogStart = scene.fogStart;
  15024. serializationObject.fogEnd = scene.fogEnd;
  15025. serializationObject.fogDensity = scene.fogDensity;
  15026. }
  15027. serializationObject.lights = [];
  15028. for (var index = 0; index < scene.lights.length; index++) {
  15029. var light = scene.lights[index];
  15030. serializationObject.lights.push(serializeLight(light));
  15031. }
  15032. serializationObject.cameras = [];
  15033. for (index = 0; index < scene.cameras.length; index++) {
  15034. var camera = scene.cameras[index];
  15035. if (camera instanceof BABYLON.FreeCamera) {
  15036. serializationObject.cameras.push(serializeCamera(camera));
  15037. }
  15038. }
  15039. if (scene.activeCamera) {
  15040. serializationObject.activeCameraID = scene.activeCamera.id;
  15041. }
  15042. serializationObject.materials = [];
  15043. serializationObject.multiMaterials = [];
  15044. for (index = 0; index < scene.materials.length; index++) {
  15045. var material = scene.materials[index];
  15046. if (material instanceof BABYLON.StandardMaterial) {
  15047. serializationObject.materials.push(serializeMaterial(material));
  15048. } else if (material instanceof BABYLON.MultiMaterial) {
  15049. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15050. }
  15051. }
  15052. serializationObject.skeletons = [];
  15053. for (index = 0; index < scene.skeletons.length; index++) {
  15054. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15055. }
  15056. serializationObject.geometries = {};
  15057. serializationObject.geometries.boxes = [];
  15058. serializationObject.geometries.spheres = [];
  15059. serializationObject.geometries.cylinders = [];
  15060. serializationObject.geometries.toruses = [];
  15061. serializationObject.geometries.grounds = [];
  15062. serializationObject.geometries.planes = [];
  15063. serializationObject.geometries.torusKnots = [];
  15064. serializationObject.geometries.vertexData = [];
  15065. serializedGeometries = [];
  15066. var geometries = scene.getGeometries();
  15067. for (var index = 0; index < geometries.length; index++) {
  15068. var geometry = geometries[index];
  15069. if (geometry.isReady()) {
  15070. serializeGeometry(geometry, serializationObject.geometries);
  15071. }
  15072. }
  15073. serializationObject.meshes = [];
  15074. for (index = 0; index < scene.meshes.length; index++) {
  15075. var abstractMesh = scene.meshes[index];
  15076. if (abstractMesh instanceof BABYLON.Mesh) {
  15077. var mesh = abstractMesh;
  15078. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  15079. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  15080. }
  15081. }
  15082. }
  15083. serializationObject.particleSystems = [];
  15084. for (index = 0; index < scene.particleSystems.length; index++) {
  15085. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  15086. }
  15087. serializationObject.lensFlareSystems = [];
  15088. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  15089. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  15090. }
  15091. serializationObject.shadowGenerators = [];
  15092. for (index = 0; index < scene.lights.length; index++) {
  15093. light = scene.lights[index];
  15094. if (light.getShadowGenerator()) {
  15095. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  15096. }
  15097. }
  15098. return serializationObject;
  15099. };
  15100. return SceneSerializer;
  15101. })();
  15102. BABYLON.SceneSerializer = SceneSerializer;
  15103. })(BABYLON || (BABYLON = {}));
  15104. var BABYLON;
  15105. (function (BABYLON) {
  15106. var SceneLoader = (function () {
  15107. function SceneLoader() {
  15108. }
  15109. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  15110. get: function () {
  15111. return SceneLoader._ForceFullSceneLoadingForIncremental;
  15112. },
  15113. set: function (value) {
  15114. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  15115. },
  15116. enumerable: true,
  15117. configurable: true
  15118. });
  15119. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  15120. get: function () {
  15121. return SceneLoader._ShowLoadingScreen;
  15122. },
  15123. set: function (value) {
  15124. SceneLoader._ShowLoadingScreen = value;
  15125. },
  15126. enumerable: true,
  15127. configurable: true
  15128. });
  15129. SceneLoader._getPluginForFilename = function (sceneFilename) {
  15130. var dotPosition = sceneFilename.lastIndexOf(".");
  15131. var queryStringPosition = sceneFilename.indexOf("?");
  15132. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  15133. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15134. var plugin = this._registeredPlugins[index];
  15135. if (plugin.extensions.indexOf(extension) !== -1) {
  15136. return plugin;
  15137. }
  15138. }
  15139. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15140. };
  15141. SceneLoader.RegisterPlugin = function (plugin) {
  15142. plugin.extensions = plugin.extensions.toLowerCase();
  15143. SceneLoader._registeredPlugins.push(plugin);
  15144. };
  15145. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15146. var manifestChecked = function (success) {
  15147. scene.database = database;
  15148. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  15149. var importMeshFromData = function (data) {
  15150. var meshes = [];
  15151. var particleSystems = [];
  15152. var skeletons = [];
  15153. try {
  15154. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  15155. if (onerror) {
  15156. onerror(scene);
  15157. }
  15158. return;
  15159. }
  15160. } catch (e) {
  15161. if (onerror) {
  15162. onerror(scene);
  15163. }
  15164. return;
  15165. }
  15166. if (onsuccess) {
  15167. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  15168. onsuccess(meshes, particleSystems, skeletons);
  15169. }
  15170. };
  15171. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15172. importMeshFromData(sceneFilename.substr(5));
  15173. return;
  15174. }
  15175. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  15176. importMeshFromData(data);
  15177. }, progressCallBack, database);
  15178. };
  15179. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15180. };
  15181. /**
  15182. * Load a scene
  15183. * @param rootUrl a string that defines the root url for scene and resources
  15184. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15185. * @param engine is the instance of BABYLON.Engine to use to create the scene
  15186. */
  15187. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  15188. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  15189. };
  15190. /**
  15191. * Append a scene
  15192. * @param rootUrl a string that defines the root url for scene and resources
  15193. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15194. * @param scene is the instance of BABYLON.Scene to append to
  15195. */
  15196. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15197. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  15198. var database;
  15199. if (SceneLoader.ShowLoadingScreen) {
  15200. scene.getEngine().displayLoadingUI();
  15201. }
  15202. var loadSceneFromData = function (data) {
  15203. scene.database = database;
  15204. if (!plugin.load(scene, data, rootUrl)) {
  15205. if (onerror) {
  15206. onerror(scene);
  15207. }
  15208. scene.getEngine().hideLoadingUI();
  15209. return;
  15210. }
  15211. if (onsuccess) {
  15212. onsuccess(scene);
  15213. }
  15214. if (SceneLoader.ShowLoadingScreen) {
  15215. scene.executeWhenReady(function () {
  15216. scene.getEngine().hideLoadingUI();
  15217. });
  15218. }
  15219. };
  15220. var manifestChecked = function (success) {
  15221. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  15222. };
  15223. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15224. loadSceneFromData(sceneFilename.substr(5));
  15225. return;
  15226. }
  15227. if (rootUrl.indexOf("file:") === -1) {
  15228. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15229. } else {
  15230. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  15231. }
  15232. };
  15233. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  15234. SceneLoader._ShowLoadingScreen = true;
  15235. SceneLoader._registeredPlugins = new Array();
  15236. return SceneLoader;
  15237. })();
  15238. BABYLON.SceneLoader = SceneLoader;
  15239. ;
  15240. })(BABYLON || (BABYLON = {}));
  15241. var BABYLON;
  15242. (function (BABYLON) {
  15243. (function (Internals) {
  15244. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  15245. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  15246. texture.name = parsedTexture.name;
  15247. texture.hasAlpha = parsedTexture.hasAlpha;
  15248. texture.level = parsedTexture.level;
  15249. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15250. return texture;
  15251. };
  15252. var loadTexture = function (rootUrl, parsedTexture, scene) {
  15253. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  15254. return null;
  15255. }
  15256. if (parsedTexture.isCube) {
  15257. return loadCubeTexture(rootUrl, parsedTexture, scene);
  15258. }
  15259. var texture;
  15260. if (parsedTexture.mirrorPlane) {
  15261. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15262. texture._waitingRenderList = parsedTexture.renderList;
  15263. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  15264. } else if (parsedTexture.isRenderTarget) {
  15265. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15266. texture._waitingRenderList = parsedTexture.renderList;
  15267. } else {
  15268. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  15269. }
  15270. texture.name = parsedTexture.name;
  15271. texture.hasAlpha = parsedTexture.hasAlpha;
  15272. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  15273. texture.level = parsedTexture.level;
  15274. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  15275. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15276. texture.uOffset = parsedTexture.uOffset;
  15277. texture.vOffset = parsedTexture.vOffset;
  15278. texture.uScale = parsedTexture.uScale;
  15279. texture.vScale = parsedTexture.vScale;
  15280. texture.uAng = parsedTexture.uAng;
  15281. texture.vAng = parsedTexture.vAng;
  15282. texture.wAng = parsedTexture.wAng;
  15283. texture.wrapU = parsedTexture.wrapU;
  15284. texture.wrapV = parsedTexture.wrapV;
  15285. if (parsedTexture.animations) {
  15286. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  15287. var parsedAnimation = parsedTexture.animations[animationIndex];
  15288. texture.animations.push(parseAnimation(parsedAnimation));
  15289. }
  15290. }
  15291. return texture;
  15292. };
  15293. var parseSkeleton = function (parsedSkeleton, scene) {
  15294. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  15295. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  15296. var parsedBone = parsedSkeleton.bones[index];
  15297. var parentBone = null;
  15298. if (parsedBone.parentBoneIndex > -1) {
  15299. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  15300. }
  15301. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  15302. if (parsedBone.animation) {
  15303. bone.animations.push(parseAnimation(parsedBone.animation));
  15304. }
  15305. }
  15306. return skeleton;
  15307. };
  15308. var parseFresnelParameters = function (parsedFresnelParameters) {
  15309. var fresnelParameters = new BABYLON.FresnelParameters();
  15310. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  15311. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  15312. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  15313. fresnelParameters.bias = parsedFresnelParameters.bias;
  15314. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  15315. return fresnelParameters;
  15316. };
  15317. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  15318. var material;
  15319. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  15320. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  15321. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  15322. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  15323. material.specularPower = parsedMaterial.specularPower;
  15324. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  15325. material.alpha = parsedMaterial.alpha;
  15326. material.id = parsedMaterial.id;
  15327. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  15328. material.backFaceCulling = parsedMaterial.backFaceCulling;
  15329. material.wireframe = parsedMaterial.wireframe;
  15330. if (parsedMaterial.diffuseTexture) {
  15331. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  15332. }
  15333. if (parsedMaterial.diffuseFresnelParameters) {
  15334. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  15335. }
  15336. if (parsedMaterial.ambientTexture) {
  15337. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  15338. }
  15339. if (parsedMaterial.opacityTexture) {
  15340. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  15341. }
  15342. if (parsedMaterial.opacityFresnelParameters) {
  15343. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  15344. }
  15345. if (parsedMaterial.reflectionTexture) {
  15346. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  15347. }
  15348. if (parsedMaterial.reflectionFresnelParameters) {
  15349. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  15350. }
  15351. if (parsedMaterial.emissiveTexture) {
  15352. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  15353. }
  15354. if (parsedMaterial.emissiveFresnelParameters) {
  15355. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  15356. }
  15357. if (parsedMaterial.specularTexture) {
  15358. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  15359. }
  15360. if (parsedMaterial.bumpTexture) {
  15361. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  15362. }
  15363. return material;
  15364. };
  15365. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  15366. for (var index = 0; index < parsedData.materials.length; index++) {
  15367. var parsedMaterial = parsedData.materials[index];
  15368. if (parsedMaterial.id === id) {
  15369. return parseMaterial(parsedMaterial, scene, rootUrl);
  15370. }
  15371. }
  15372. return null;
  15373. };
  15374. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  15375. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  15376. multiMaterial.id = parsedMultiMaterial.id;
  15377. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  15378. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15379. var subMatId = parsedMultiMaterial.materials[matIndex];
  15380. if (subMatId) {
  15381. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  15382. } else {
  15383. multiMaterial.subMaterials.push(null);
  15384. }
  15385. }
  15386. return multiMaterial;
  15387. };
  15388. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  15389. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  15390. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  15391. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  15392. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  15393. var parsedFlare = parsedLensFlareSystem.flares[index];
  15394. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  15395. }
  15396. return lensFlareSystem;
  15397. };
  15398. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  15399. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  15400. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  15401. if (parsedParticleSystem.textureName) {
  15402. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  15403. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  15404. }
  15405. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  15406. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  15407. particleSystem.minSize = parsedParticleSystem.minSize;
  15408. particleSystem.maxSize = parsedParticleSystem.maxSize;
  15409. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  15410. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  15411. particleSystem.emitter = emitter;
  15412. particleSystem.emitRate = parsedParticleSystem.emitRate;
  15413. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  15414. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  15415. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  15416. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  15417. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  15418. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  15419. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  15420. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  15421. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  15422. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  15423. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  15424. particleSystem.blendMode = parsedParticleSystem.blendMode;
  15425. particleSystem.start();
  15426. return particleSystem;
  15427. };
  15428. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  15429. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15430. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15431. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15432. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  15433. shadowGenerator.getShadowMap().renderList.push(mesh);
  15434. }
  15435. if (parsedShadowGenerator.usePoissonSampling) {
  15436. shadowGenerator.usePoissonSampling = true;
  15437. } else {
  15438. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  15439. }
  15440. return shadowGenerator;
  15441. };
  15442. var parseAnimation = function (parsedAnimation) {
  15443. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  15444. var dataType = parsedAnimation.dataType;
  15445. var keys = [];
  15446. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  15447. var key = parsedAnimation.keys[index];
  15448. var data;
  15449. switch (dataType) {
  15450. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15451. data = key.values[0];
  15452. break;
  15453. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15454. data = BABYLON.Quaternion.FromArray(key.values);
  15455. break;
  15456. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15457. data = BABYLON.Matrix.FromArray(key.values);
  15458. break;
  15459. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15460. default:
  15461. data = BABYLON.Vector3.FromArray(key.values);
  15462. break;
  15463. }
  15464. keys.push({
  15465. frame: key.frame,
  15466. value: data
  15467. });
  15468. }
  15469. animation.setKeys(keys);
  15470. return animation;
  15471. };
  15472. var parseLight = function (parsedLight, scene) {
  15473. var light;
  15474. switch (parsedLight.type) {
  15475. case 0:
  15476. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15477. break;
  15478. case 1:
  15479. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15480. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15481. break;
  15482. case 2:
  15483. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15484. break;
  15485. case 3:
  15486. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15487. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15488. break;
  15489. }
  15490. light.id = parsedLight.id;
  15491. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15492. if (parsedLight.intensity !== undefined) {
  15493. light.intensity = parsedLight.intensity;
  15494. }
  15495. if (parsedLight.range) {
  15496. light.range = parsedLight.range;
  15497. }
  15498. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15499. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15500. if (parsedLight.excludedMeshesIds) {
  15501. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15502. }
  15503. if (parsedLight.includedOnlyMeshesIds) {
  15504. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15505. }
  15506. if (parsedLight.animations) {
  15507. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15508. var parsedAnimation = parsedLight.animations[animationIndex];
  15509. light.animations.push(parseAnimation(parsedAnimation));
  15510. }
  15511. }
  15512. if (parsedLight.autoAnimate) {
  15513. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15514. }
  15515. };
  15516. var parseCamera = function (parsedCamera, scene) {
  15517. var camera;
  15518. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15519. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15520. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15521. var alpha = parsedCamera.alpha;
  15522. var beta = parsedCamera.beta;
  15523. var radius = parsedCamera.radius;
  15524. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15525. var eye_space = parsedCamera.eye_space;
  15526. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15527. } else {
  15528. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15529. }
  15530. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15531. var eye_space = parsedCamera.eye_space;
  15532. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15533. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15534. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15535. } else if (parsedCamera.type === "FollowCamera") {
  15536. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15537. camera.heightOffset = parsedCamera.heightOffset;
  15538. camera.radius = parsedCamera.radius;
  15539. camera.rotationOffset = parsedCamera.rotationOffset;
  15540. if (lockedTargetMesh)
  15541. camera.target = lockedTargetMesh;
  15542. } else if (parsedCamera.type === "GamepadCamera") {
  15543. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15544. } else if (parsedCamera.type === "OculusCamera") {
  15545. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15546. } else if (parsedCamera.type === "TouchCamera") {
  15547. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15548. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15549. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15550. } else if (parsedCamera.type === "WebVRCamera") {
  15551. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15552. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15553. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15554. } else {
  15555. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15556. }
  15557. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15558. camera.lockedTarget = lockedTargetMesh;
  15559. }
  15560. camera.id = parsedCamera.id;
  15561. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15562. if (parsedCamera.parentId) {
  15563. camera._waitingParentId = parsedCamera.parentId;
  15564. }
  15565. if (parsedCamera.target) {
  15566. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15567. } else {
  15568. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15569. }
  15570. camera.fov = parsedCamera.fov;
  15571. camera.minZ = parsedCamera.minZ;
  15572. camera.maxZ = parsedCamera.maxZ;
  15573. camera.speed = parsedCamera.speed;
  15574. camera.inertia = parsedCamera.inertia;
  15575. camera.checkCollisions = parsedCamera.checkCollisions;
  15576. camera.applyGravity = parsedCamera.applyGravity;
  15577. if (parsedCamera.ellipsoid) {
  15578. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15579. }
  15580. if (parsedCamera.animations) {
  15581. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15582. var parsedAnimation = parsedCamera.animations[animationIndex];
  15583. camera.animations.push(parseAnimation(parsedAnimation));
  15584. }
  15585. }
  15586. if (parsedCamera.autoAnimate) {
  15587. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15588. }
  15589. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15590. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15591. } else {
  15592. camera.layerMask = 0xFFFFFFFF;
  15593. }
  15594. return camera;
  15595. };
  15596. var parseGeometry = function (parsedGeometry, scene) {
  15597. var id = parsedGeometry.id;
  15598. return scene.getGeometryByID(id);
  15599. };
  15600. var parseBox = function (parsedBox, scene) {
  15601. if (parseGeometry(parsedBox, scene)) {
  15602. return null;
  15603. }
  15604. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15605. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15606. scene.pushGeometry(box, true);
  15607. return box;
  15608. };
  15609. var parseSphere = function (parsedSphere, scene) {
  15610. if (parseGeometry(parsedSphere, scene)) {
  15611. return null;
  15612. }
  15613. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15614. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15615. scene.pushGeometry(sphere, true);
  15616. return sphere;
  15617. };
  15618. var parseCylinder = function (parsedCylinder, scene) {
  15619. if (parseGeometry(parsedCylinder, scene)) {
  15620. return null;
  15621. }
  15622. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15623. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15624. scene.pushGeometry(cylinder, true);
  15625. return cylinder;
  15626. };
  15627. var parseTorus = function (parsedTorus, scene) {
  15628. if (parseGeometry(parsedTorus, scene)) {
  15629. return null;
  15630. }
  15631. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15632. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15633. scene.pushGeometry(torus, true);
  15634. return torus;
  15635. };
  15636. var parseGround = function (parsedGround, scene) {
  15637. if (parseGeometry(parsedGround, scene)) {
  15638. return null;
  15639. }
  15640. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15641. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15642. scene.pushGeometry(ground, true);
  15643. return ground;
  15644. };
  15645. var parsePlane = function (parsedPlane, scene) {
  15646. if (parseGeometry(parsedPlane, scene)) {
  15647. return null;
  15648. }
  15649. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15650. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15651. scene.pushGeometry(plane, true);
  15652. return plane;
  15653. };
  15654. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15655. if (parseGeometry(parsedTorusKnot, scene)) {
  15656. return null;
  15657. }
  15658. 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);
  15659. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15660. scene.pushGeometry(torusKnot, true);
  15661. return torusKnot;
  15662. };
  15663. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15664. if (parseGeometry(parsedVertexData, scene)) {
  15665. return null;
  15666. }
  15667. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15668. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15669. if (parsedVertexData.delayLoadingFile) {
  15670. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15671. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15672. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15673. geometry._delayInfo = [];
  15674. if (parsedVertexData.hasUVs) {
  15675. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15676. }
  15677. if (parsedVertexData.hasUVs2) {
  15678. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15679. }
  15680. if (parsedVertexData.hasColors) {
  15681. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15682. }
  15683. if (parsedVertexData.hasMatricesIndices) {
  15684. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15685. }
  15686. if (parsedVertexData.hasMatricesWeights) {
  15687. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15688. }
  15689. geometry._delayLoadingFunction = importVertexData;
  15690. } else {
  15691. importVertexData(parsedVertexData, geometry);
  15692. }
  15693. scene.pushGeometry(geometry, true);
  15694. return geometry;
  15695. };
  15696. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15697. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15698. mesh.id = parsedMesh.id;
  15699. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15700. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15701. if (parsedMesh.rotationQuaternion) {
  15702. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15703. } else if (parsedMesh.rotation) {
  15704. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15705. }
  15706. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15707. if (parsedMesh.localMatrix) {
  15708. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15709. } else if (parsedMesh.pivotMatrix) {
  15710. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15711. }
  15712. mesh.setEnabled(parsedMesh.isEnabled);
  15713. mesh.isVisible = parsedMesh.isVisible;
  15714. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15715. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15716. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15717. if (parsedMesh.pickable !== undefined) {
  15718. mesh.isPickable = parsedMesh.pickable;
  15719. }
  15720. mesh.receiveShadows = parsedMesh.receiveShadows;
  15721. mesh.billboardMode = parsedMesh.billboardMode;
  15722. if (parsedMesh.visibility !== undefined) {
  15723. mesh.visibility = parsedMesh.visibility;
  15724. }
  15725. mesh.checkCollisions = parsedMesh.checkCollisions;
  15726. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15727. if (parsedMesh.parentId) {
  15728. mesh._waitingParentId = parsedMesh.parentId;
  15729. }
  15730. if (parsedMesh.delayLoadingFile) {
  15731. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15732. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15733. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15734. if (parsedMesh._binaryInfo) {
  15735. mesh._binaryInfo = parsedMesh._binaryInfo;
  15736. }
  15737. mesh._delayInfo = [];
  15738. if (parsedMesh.hasUVs) {
  15739. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15740. }
  15741. if (parsedMesh.hasUVs2) {
  15742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15743. }
  15744. if (parsedMesh.hasColors) {
  15745. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15746. }
  15747. if (parsedMesh.hasMatricesIndices) {
  15748. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15749. }
  15750. if (parsedMesh.hasMatricesWeights) {
  15751. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15752. }
  15753. mesh._delayLoadingFunction = importGeometry;
  15754. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15755. mesh._checkDelayState();
  15756. }
  15757. } else {
  15758. importGeometry(parsedMesh, mesh);
  15759. }
  15760. if (parsedMesh.materialId) {
  15761. mesh.setMaterialByID(parsedMesh.materialId);
  15762. } else {
  15763. mesh.material = null;
  15764. }
  15765. if (parsedMesh.skeletonId > -1) {
  15766. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15767. }
  15768. if (parsedMesh.physicsImpostor) {
  15769. if (!scene.isPhysicsEnabled()) {
  15770. scene.enablePhysics();
  15771. }
  15772. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15773. }
  15774. if (parsedMesh.animations) {
  15775. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15776. var parsedAnimation = parsedMesh.animations[animationIndex];
  15777. mesh.animations.push(parseAnimation(parsedAnimation));
  15778. }
  15779. }
  15780. if (parsedMesh.autoAnimate) {
  15781. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15782. }
  15783. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15784. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15785. } else {
  15786. mesh.layerMask = 0xFFFFFFFF;
  15787. }
  15788. if (parsedMesh.instances) {
  15789. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15790. var parsedInstance = parsedMesh.instances[index];
  15791. var instance = mesh.createInstance(parsedInstance.name);
  15792. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15793. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15794. if (parsedInstance.rotationQuaternion) {
  15795. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15796. } else if (parsedInstance.rotation) {
  15797. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15798. }
  15799. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15800. instance.checkCollisions = mesh.checkCollisions;
  15801. if (parsedMesh.animations) {
  15802. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15803. parsedAnimation = parsedMesh.animations[animationIndex];
  15804. instance.animations.push(parseAnimation(parsedAnimation));
  15805. }
  15806. }
  15807. }
  15808. }
  15809. return mesh;
  15810. };
  15811. var isDescendantOf = function (mesh, names, hierarchyIds) {
  15812. names = (names instanceof Array) ? names : [names];
  15813. for (var i in names) {
  15814. if (mesh.name === names[i]) {
  15815. hierarchyIds.push(mesh.id);
  15816. return true;
  15817. }
  15818. }
  15819. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  15820. hierarchyIds.push(mesh.id);
  15821. return true;
  15822. }
  15823. return false;
  15824. };
  15825. var importVertexData = function (parsedVertexData, geometry) {
  15826. var vertexData = new BABYLON.VertexData();
  15827. var positions = parsedVertexData.positions;
  15828. if (positions) {
  15829. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  15830. }
  15831. var normals = parsedVertexData.normals;
  15832. if (normals) {
  15833. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  15834. }
  15835. var uvs = parsedVertexData.uvs;
  15836. if (uvs) {
  15837. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  15838. }
  15839. var uv2s = parsedVertexData.uv2s;
  15840. if (uv2s) {
  15841. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  15842. }
  15843. var colors = parsedVertexData.colors;
  15844. if (colors) {
  15845. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  15846. }
  15847. var matricesIndices = parsedVertexData.matricesIndices;
  15848. if (matricesIndices) {
  15849. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  15850. }
  15851. var matricesWeights = parsedVertexData.matricesWeights;
  15852. if (matricesWeights) {
  15853. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  15854. }
  15855. var indices = parsedVertexData.indices;
  15856. if (indices) {
  15857. vertexData.indices = indices;
  15858. }
  15859. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  15860. };
  15861. var importGeometry = function (parsedGeometry, mesh) {
  15862. var scene = mesh.getScene();
  15863. var geometryId = parsedGeometry.geometryId;
  15864. if (geometryId) {
  15865. var geometry = scene.getGeometryByID(geometryId);
  15866. if (geometry) {
  15867. geometry.applyToMesh(mesh);
  15868. }
  15869. } else if (parsedGeometry instanceof ArrayBuffer) {
  15870. var binaryInfo = mesh._binaryInfo;
  15871. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  15872. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  15873. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  15874. }
  15875. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  15876. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  15877. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  15878. }
  15879. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  15880. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  15881. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  15882. }
  15883. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  15884. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  15885. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  15886. }
  15887. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  15888. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  15889. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  15890. }
  15891. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  15892. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  15893. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  15894. }
  15895. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  15896. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  15897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  15898. }
  15899. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  15900. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  15901. mesh.setIndices(indicesData);
  15902. }
  15903. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  15904. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  15905. mesh.subMeshes = [];
  15906. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  15907. var materialIndex = subMeshesData[(i * 5) + 0];
  15908. var verticesStart = subMeshesData[(i * 5) + 1];
  15909. var verticesCount = subMeshesData[(i * 5) + 2];
  15910. var indexStart = subMeshesData[(i * 5) + 3];
  15911. var indexCount = subMeshesData[(i * 5) + 4];
  15912. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  15913. }
  15914. }
  15915. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  15916. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  15917. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  15918. if (parsedGeometry.uvs) {
  15919. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  15920. }
  15921. if (parsedGeometry.uvs2) {
  15922. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  15923. }
  15924. if (parsedGeometry.colors) {
  15925. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  15926. }
  15927. if (parsedGeometry.matricesIndices) {
  15928. if (!parsedGeometry.matricesIndices._isExpanded) {
  15929. var floatIndices = [];
  15930. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  15931. var matricesIndex = parsedGeometry.matricesIndices[i];
  15932. floatIndices.push(matricesIndex & 0x000000FF);
  15933. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  15934. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  15935. floatIndices.push(matricesIndex >> 24);
  15936. }
  15937. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  15938. } else {
  15939. delete parsedGeometry.matricesIndices._isExpanded;
  15940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  15941. }
  15942. }
  15943. if (parsedGeometry.matricesWeights) {
  15944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  15945. }
  15946. mesh.setIndices(parsedGeometry.indices);
  15947. if (parsedGeometry.subMeshes) {
  15948. mesh.subMeshes = [];
  15949. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  15950. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  15951. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  15952. }
  15953. }
  15954. }
  15955. if (mesh._shouldGenerateFlatShading) {
  15956. mesh.convertToFlatShadedMesh();
  15957. delete mesh._shouldGenerateFlatShading;
  15958. }
  15959. mesh.computeWorldMatrix(true);
  15960. if (scene._selectionOctree) {
  15961. scene._selectionOctree.addMesh(mesh);
  15962. }
  15963. };
  15964. BABYLON.SceneLoader.RegisterPlugin({
  15965. extensions: ".babylon",
  15966. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  15967. var parsedData = JSON.parse(data);
  15968. var loadedSkeletonsIds = [];
  15969. var loadedMaterialsIds = [];
  15970. var hierarchyIds = [];
  15971. for (var index = 0; index < parsedData.meshes.length; index++) {
  15972. var parsedMesh = parsedData.meshes[index];
  15973. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  15974. if (meshesNames instanceof Array) {
  15975. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  15976. }
  15977. if (parsedMesh.materialId) {
  15978. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  15979. if (!materialFound) {
  15980. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  15981. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  15982. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  15983. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15984. var subMatId = parsedMultiMaterial.materials[matIndex];
  15985. loadedMaterialsIds.push(subMatId);
  15986. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  15987. }
  15988. loadedMaterialsIds.push(parsedMultiMaterial.id);
  15989. parseMultiMaterial(parsedMultiMaterial, scene);
  15990. materialFound = true;
  15991. break;
  15992. }
  15993. }
  15994. }
  15995. if (!materialFound) {
  15996. loadedMaterialsIds.push(parsedMesh.materialId);
  15997. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  15998. }
  15999. }
  16000. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  16001. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  16002. if (!skeletonAlreadyLoaded) {
  16003. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  16004. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  16005. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  16006. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  16007. loadedSkeletonsIds.push(parsedSkeleton.id);
  16008. }
  16009. }
  16010. }
  16011. }
  16012. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  16013. meshes.push(mesh);
  16014. }
  16015. }
  16016. for (index = 0; index < scene.meshes.length; index++) {
  16017. var currentMesh = scene.meshes[index];
  16018. if (currentMesh._waitingParentId) {
  16019. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  16020. currentMesh._waitingParentId = undefined;
  16021. }
  16022. }
  16023. if (parsedData.particleSystems) {
  16024. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16025. var parsedParticleSystem = parsedData.particleSystems[index];
  16026. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  16027. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  16028. }
  16029. }
  16030. }
  16031. return true;
  16032. },
  16033. load: function (scene, data, rootUrl) {
  16034. var parsedData = JSON.parse(data);
  16035. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  16036. scene.autoClear = parsedData.autoClear;
  16037. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  16038. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  16039. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  16040. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  16041. scene.fogMode = parsedData.fogMode;
  16042. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  16043. scene.fogStart = parsedData.fogStart;
  16044. scene.fogEnd = parsedData.fogEnd;
  16045. scene.fogDensity = parsedData.fogDensity;
  16046. }
  16047. for (var index = 0; index < parsedData.lights.length; index++) {
  16048. var parsedLight = parsedData.lights[index];
  16049. parseLight(parsedLight, scene);
  16050. }
  16051. if (parsedData.materials) {
  16052. for (index = 0; index < parsedData.materials.length; index++) {
  16053. var parsedMaterial = parsedData.materials[index];
  16054. parseMaterial(parsedMaterial, scene, rootUrl);
  16055. }
  16056. }
  16057. if (parsedData.multiMaterials) {
  16058. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  16059. var parsedMultiMaterial = parsedData.multiMaterials[index];
  16060. parseMultiMaterial(parsedMultiMaterial, scene);
  16061. }
  16062. }
  16063. if (parsedData.skeletons) {
  16064. for (index = 0; index < parsedData.skeletons.length; index++) {
  16065. var parsedSkeleton = parsedData.skeletons[index];
  16066. parseSkeleton(parsedSkeleton, scene);
  16067. }
  16068. }
  16069. var geometries = parsedData.geometries;
  16070. if (geometries) {
  16071. var boxes = geometries.boxes;
  16072. if (boxes) {
  16073. for (index = 0; index < boxes.length; index++) {
  16074. var parsedBox = boxes[index];
  16075. parseBox(parsedBox, scene);
  16076. }
  16077. }
  16078. var spheres = geometries.spheres;
  16079. if (spheres) {
  16080. for (index = 0; index < spheres.length; index++) {
  16081. var parsedSphere = spheres[index];
  16082. parseSphere(parsedSphere, scene);
  16083. }
  16084. }
  16085. var cylinders = geometries.cylinders;
  16086. if (cylinders) {
  16087. for (index = 0; index < cylinders.length; index++) {
  16088. var parsedCylinder = cylinders[index];
  16089. parseCylinder(parsedCylinder, scene);
  16090. }
  16091. }
  16092. var toruses = geometries.toruses;
  16093. if (toruses) {
  16094. for (index = 0; index < toruses.length; index++) {
  16095. var parsedTorus = toruses[index];
  16096. parseTorus(parsedTorus, scene);
  16097. }
  16098. }
  16099. var grounds = geometries.grounds;
  16100. if (grounds) {
  16101. for (index = 0; index < grounds.length; index++) {
  16102. var parsedGround = grounds[index];
  16103. parseGround(parsedGround, scene);
  16104. }
  16105. }
  16106. var planes = geometries.planes;
  16107. if (planes) {
  16108. for (index = 0; index < planes.length; index++) {
  16109. var parsedPlane = planes[index];
  16110. parsePlane(parsedPlane, scene);
  16111. }
  16112. }
  16113. var torusKnots = geometries.torusKnots;
  16114. if (torusKnots) {
  16115. for (index = 0; index < torusKnots.length; index++) {
  16116. var parsedTorusKnot = torusKnots[index];
  16117. parseTorusKnot(parsedTorusKnot, scene);
  16118. }
  16119. }
  16120. var vertexData = geometries.vertexData;
  16121. if (vertexData) {
  16122. for (index = 0; index < vertexData.length; index++) {
  16123. var parsedVertexData = vertexData[index];
  16124. parseVertexData(parsedVertexData, scene, rootUrl);
  16125. }
  16126. }
  16127. }
  16128. for (index = 0; index < parsedData.meshes.length; index++) {
  16129. var parsedMesh = parsedData.meshes[index];
  16130. parseMesh(parsedMesh, scene, rootUrl);
  16131. }
  16132. for (index = 0; index < parsedData.cameras.length; index++) {
  16133. var parsedCamera = parsedData.cameras[index];
  16134. parseCamera(parsedCamera, scene);
  16135. }
  16136. if (parsedData.activeCameraID) {
  16137. scene.setActiveCameraByID(parsedData.activeCameraID);
  16138. }
  16139. for (index = 0; index < scene.cameras.length; index++) {
  16140. var camera = scene.cameras[index];
  16141. if (camera._waitingParentId) {
  16142. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  16143. camera._waitingParentId = undefined;
  16144. }
  16145. }
  16146. for (index = 0; index < scene.meshes.length; index++) {
  16147. var mesh = scene.meshes[index];
  16148. if (mesh._waitingParentId) {
  16149. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  16150. mesh._waitingParentId = undefined;
  16151. }
  16152. }
  16153. if (parsedData.particleSystems) {
  16154. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16155. var parsedParticleSystem = parsedData.particleSystems[index];
  16156. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  16157. }
  16158. }
  16159. if (parsedData.lensFlareSystems) {
  16160. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  16161. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  16162. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  16163. }
  16164. }
  16165. if (parsedData.shadowGenerators) {
  16166. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  16167. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  16168. parseShadowGenerator(parsedShadowGenerator, scene);
  16169. }
  16170. }
  16171. return true;
  16172. }
  16173. });
  16174. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16175. var Internals = BABYLON.Internals;
  16176. })(BABYLON || (BABYLON = {}));
  16177. var BABYLON;
  16178. (function (BABYLON) {
  16179. var currentCSGMeshId = 0;
  16180. var Vertex = (function () {
  16181. function Vertex(pos, normal, uv) {
  16182. this.pos = pos;
  16183. this.normal = normal;
  16184. this.uv = uv;
  16185. }
  16186. Vertex.prototype.clone = function () {
  16187. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16188. };
  16189. Vertex.prototype.flip = function () {
  16190. this.normal = this.normal.scale(-1);
  16191. };
  16192. Vertex.prototype.interpolate = function (other, t) {
  16193. 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));
  16194. };
  16195. return Vertex;
  16196. })();
  16197. var Plane = (function () {
  16198. function Plane(normal, w) {
  16199. this.normal = normal;
  16200. this.w = w;
  16201. }
  16202. Plane.FromPoints = function (a, b, c) {
  16203. var v0 = c.subtract(a);
  16204. var v1 = b.subtract(a);
  16205. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16206. return null;
  16207. }
  16208. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16209. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16210. };
  16211. Plane.prototype.clone = function () {
  16212. return new Plane(this.normal.clone(), this.w);
  16213. };
  16214. Plane.prototype.flip = function () {
  16215. this.normal.scaleInPlace(-1);
  16216. this.w = -this.w;
  16217. };
  16218. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16219. var COPLANAR = 0;
  16220. var FRONT = 1;
  16221. var BACK = 2;
  16222. var SPANNING = 3;
  16223. var polygonType = 0;
  16224. var types = [];
  16225. for (var i = 0; i < polygon.vertices.length; i++) {
  16226. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16227. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16228. polygonType |= type;
  16229. types.push(type);
  16230. }
  16231. switch (polygonType) {
  16232. case COPLANAR:
  16233. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16234. break;
  16235. case FRONT:
  16236. front.push(polygon);
  16237. break;
  16238. case BACK:
  16239. back.push(polygon);
  16240. break;
  16241. case SPANNING:
  16242. var f = [], b = [];
  16243. for (i = 0; i < polygon.vertices.length; i++) {
  16244. var j = (i + 1) % polygon.vertices.length;
  16245. var ti = types[i], tj = types[j];
  16246. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16247. if (ti != BACK)
  16248. f.push(vi);
  16249. if (ti != FRONT)
  16250. b.push(ti != BACK ? vi.clone() : vi);
  16251. if ((ti | tj) == SPANNING) {
  16252. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16253. var v = vi.interpolate(vj, t);
  16254. f.push(v);
  16255. b.push(v.clone());
  16256. }
  16257. }
  16258. if (f.length >= 3) {
  16259. var poly = new Polygon(f, polygon.shared);
  16260. if (poly.plane)
  16261. front.push(poly);
  16262. }
  16263. if (b.length >= 3) {
  16264. poly = new Polygon(b, polygon.shared);
  16265. if (poly.plane)
  16266. back.push(poly);
  16267. }
  16268. break;
  16269. }
  16270. };
  16271. Plane.EPSILON = 1e-5;
  16272. return Plane;
  16273. })();
  16274. var Polygon = (function () {
  16275. function Polygon(vertices, shared) {
  16276. this.vertices = vertices;
  16277. this.shared = shared;
  16278. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16279. }
  16280. Polygon.prototype.clone = function () {
  16281. var vertices = this.vertices.map(function (v) {
  16282. return v.clone();
  16283. });
  16284. return new Polygon(vertices, this.shared);
  16285. };
  16286. Polygon.prototype.flip = function () {
  16287. this.vertices.reverse().map(function (v) {
  16288. v.flip();
  16289. });
  16290. this.plane.flip();
  16291. };
  16292. return Polygon;
  16293. })();
  16294. var Node = (function () {
  16295. function Node(polygons) {
  16296. this.plane = null;
  16297. this.front = null;
  16298. this.back = null;
  16299. this.polygons = [];
  16300. if (polygons) {
  16301. this.build(polygons);
  16302. }
  16303. }
  16304. Node.prototype.clone = function () {
  16305. var node = new Node();
  16306. node.plane = this.plane && this.plane.clone();
  16307. node.front = this.front && this.front.clone();
  16308. node.back = this.back && this.back.clone();
  16309. node.polygons = this.polygons.map(function (p) {
  16310. return p.clone();
  16311. });
  16312. return node;
  16313. };
  16314. Node.prototype.invert = function () {
  16315. for (var i = 0; i < this.polygons.length; i++) {
  16316. this.polygons[i].flip();
  16317. }
  16318. if (this.plane) {
  16319. this.plane.flip();
  16320. }
  16321. if (this.front) {
  16322. this.front.invert();
  16323. }
  16324. if (this.back) {
  16325. this.back.invert();
  16326. }
  16327. var temp = this.front;
  16328. this.front = this.back;
  16329. this.back = temp;
  16330. };
  16331. Node.prototype.clipPolygons = function (polygons) {
  16332. if (!this.plane)
  16333. return polygons.slice();
  16334. var front = [], back = [];
  16335. for (var i = 0; i < polygons.length; i++) {
  16336. this.plane.splitPolygon(polygons[i], front, back, front, back);
  16337. }
  16338. if (this.front) {
  16339. front = this.front.clipPolygons(front);
  16340. }
  16341. if (this.back) {
  16342. back = this.back.clipPolygons(back);
  16343. } else {
  16344. back = [];
  16345. }
  16346. return front.concat(back);
  16347. };
  16348. Node.prototype.clipTo = function (bsp) {
  16349. this.polygons = bsp.clipPolygons(this.polygons);
  16350. if (this.front)
  16351. this.front.clipTo(bsp);
  16352. if (this.back)
  16353. this.back.clipTo(bsp);
  16354. };
  16355. Node.prototype.allPolygons = function () {
  16356. var polygons = this.polygons.slice();
  16357. if (this.front)
  16358. polygons = polygons.concat(this.front.allPolygons());
  16359. if (this.back)
  16360. polygons = polygons.concat(this.back.allPolygons());
  16361. return polygons;
  16362. };
  16363. Node.prototype.build = function (polygons) {
  16364. if (!polygons.length)
  16365. return;
  16366. if (!this.plane)
  16367. this.plane = polygons[0].plane.clone();
  16368. var front = [], back = [];
  16369. for (var i = 0; i < polygons.length; i++) {
  16370. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  16371. }
  16372. if (front.length) {
  16373. if (!this.front)
  16374. this.front = new Node();
  16375. this.front.build(front);
  16376. }
  16377. if (back.length) {
  16378. if (!this.back)
  16379. this.back = new Node();
  16380. this.back.build(back);
  16381. }
  16382. };
  16383. return Node;
  16384. })();
  16385. var CSG = (function () {
  16386. function CSG() {
  16387. this.polygons = new Array();
  16388. }
  16389. CSG.FromMesh = function (mesh) {
  16390. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  16391. if (mesh instanceof BABYLON.Mesh) {
  16392. mesh.computeWorldMatrix(true);
  16393. var matrix = mesh.getWorldMatrix();
  16394. var meshPosition = mesh.position.clone();
  16395. var meshRotation = mesh.rotation.clone();
  16396. var meshScaling = mesh.scaling.clone();
  16397. } else {
  16398. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  16399. }
  16400. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16401. var subMeshes = mesh.subMeshes;
  16402. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  16403. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  16404. vertices = [];
  16405. for (var j = 0; j < 3; j++) {
  16406. normal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  16407. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  16408. position = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  16409. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, position);
  16410. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16411. vertex = new Vertex(position, normal, uv);
  16412. vertices.push(vertex);
  16413. }
  16414. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  16415. if (polygon.plane)
  16416. polygons.push(polygon);
  16417. }
  16418. }
  16419. var csg = CSG.FromPolygons(polygons);
  16420. csg.matrix = matrix;
  16421. csg.position = meshPosition;
  16422. csg.rotation = meshRotation;
  16423. csg.scaling = meshScaling;
  16424. currentCSGMeshId++;
  16425. return csg;
  16426. };
  16427. CSG.FromPolygons = function (polygons) {
  16428. var csg = new BABYLON.CSG();
  16429. csg.polygons = polygons;
  16430. return csg;
  16431. };
  16432. CSG.prototype.clone = function () {
  16433. var csg = new BABYLON.CSG();
  16434. csg.polygons = this.polygons.map(function (p) {
  16435. return p.clone();
  16436. });
  16437. csg.copyTransformAttributes(this);
  16438. return csg;
  16439. };
  16440. CSG.prototype.toPolygons = function () {
  16441. return this.polygons;
  16442. };
  16443. CSG.prototype.union = function (csg) {
  16444. var a = new Node(this.clone().polygons);
  16445. var b = new Node(csg.clone().polygons);
  16446. a.clipTo(b);
  16447. b.clipTo(a);
  16448. b.invert();
  16449. b.clipTo(a);
  16450. b.invert();
  16451. a.build(b.allPolygons());
  16452. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16453. };
  16454. CSG.prototype.unionInPlace = function (csg) {
  16455. var a = new Node(this.polygons);
  16456. var b = new Node(csg.polygons);
  16457. a.clipTo(b);
  16458. b.clipTo(a);
  16459. b.invert();
  16460. b.clipTo(a);
  16461. b.invert();
  16462. a.build(b.allPolygons());
  16463. this.polygons = a.allPolygons();
  16464. };
  16465. CSG.prototype.subtract = function (csg) {
  16466. var a = new Node(this.clone().polygons);
  16467. var b = new Node(csg.clone().polygons);
  16468. a.invert();
  16469. a.clipTo(b);
  16470. b.clipTo(a);
  16471. b.invert();
  16472. b.clipTo(a);
  16473. b.invert();
  16474. a.build(b.allPolygons());
  16475. a.invert();
  16476. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16477. };
  16478. CSG.prototype.subtractInPlace = function (csg) {
  16479. var a = new Node(this.polygons);
  16480. var b = new Node(csg.polygons);
  16481. a.invert();
  16482. a.clipTo(b);
  16483. b.clipTo(a);
  16484. b.invert();
  16485. b.clipTo(a);
  16486. b.invert();
  16487. a.build(b.allPolygons());
  16488. a.invert();
  16489. this.polygons = a.allPolygons();
  16490. };
  16491. CSG.prototype.intersect = function (csg) {
  16492. var a = new Node(this.clone().polygons);
  16493. var b = new Node(csg.clone().polygons);
  16494. a.invert();
  16495. b.clipTo(a);
  16496. b.invert();
  16497. a.clipTo(b);
  16498. b.clipTo(a);
  16499. a.build(b.allPolygons());
  16500. a.invert();
  16501. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16502. };
  16503. CSG.prototype.intersectInPlace = function (csg) {
  16504. var a = new Node(this.polygons);
  16505. var b = new Node(csg.polygons);
  16506. a.invert();
  16507. b.clipTo(a);
  16508. b.invert();
  16509. a.clipTo(b);
  16510. b.clipTo(a);
  16511. a.build(b.allPolygons());
  16512. a.invert();
  16513. this.polygons = a.allPolygons();
  16514. };
  16515. CSG.prototype.inverse = function () {
  16516. var csg = this.clone();
  16517. csg.inverseInPlace();
  16518. return csg;
  16519. };
  16520. CSG.prototype.inverseInPlace = function () {
  16521. this.polygons.map(function (p) {
  16522. p.flip();
  16523. });
  16524. };
  16525. CSG.prototype.copyTransformAttributes = function (csg) {
  16526. this.matrix = csg.matrix;
  16527. this.position = csg.position;
  16528. this.rotation = csg.rotation;
  16529. this.scaling = csg.scaling;
  16530. return this;
  16531. };
  16532. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16533. var matrix = this.matrix.clone();
  16534. matrix.invert();
  16535. 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;
  16536. if (keepSubMeshes) {
  16537. polygons.sort(function (a, b) {
  16538. if (a.shared.meshId === b.shared.meshId) {
  16539. return a.shared.subMeshId - b.shared.subMeshId;
  16540. } else {
  16541. return a.shared.meshId - b.shared.meshId;
  16542. }
  16543. });
  16544. }
  16545. for (var i = 0, il = polygons.length; i < il; i++) {
  16546. polygon = polygons[i];
  16547. if (!subMesh_dict[polygon.shared.meshId]) {
  16548. subMesh_dict[polygon.shared.meshId] = {};
  16549. }
  16550. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16551. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16552. indexStart: +Infinity,
  16553. indexEnd: -Infinity,
  16554. materialIndex: polygon.shared.materialIndex
  16555. };
  16556. }
  16557. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16558. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16559. polygonIndices[0] = 0;
  16560. polygonIndices[1] = j - 1;
  16561. polygonIndices[2] = j;
  16562. for (var k = 0; k < 3; k++) {
  16563. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16564. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16565. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16566. BABYLON.Vector3.TransformCoordinatesToRef(vertex, matrix, vertex);
  16567. BABYLON.Vector3.TransformNormalToRef(normal, matrix, normal);
  16568. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z];
  16569. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === normal.x && normals[vertex_idx * 3 + 1] === normal.y && normals[vertex_idx * 3 + 2] === normal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16570. vertices.push(vertex.x, vertex.y, vertex.z);
  16571. uvs.push(uv.x, uv.y);
  16572. normals.push(normal.x, normal.y, normal.z);
  16573. vertex_idx = vertice_dict[vertex.x + ',' + vertex.y + ',' + vertex.z] = (vertices.length / 3) - 1;
  16574. }
  16575. indices.push(vertex_idx);
  16576. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16577. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16578. currentIndex++;
  16579. }
  16580. }
  16581. }
  16582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16583. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16584. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16585. mesh.setIndices(indices);
  16586. if (keepSubMeshes) {
  16587. var materialIndexOffset = 0, materialMaxIndex;
  16588. mesh.subMeshes.length = 0;
  16589. for (var m in subMesh_dict) {
  16590. materialMaxIndex = -1;
  16591. for (var sm in subMesh_dict[m]) {
  16592. subMesh_obj = subMesh_dict[m][sm];
  16593. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16594. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16595. }
  16596. materialIndexOffset += ++materialMaxIndex;
  16597. }
  16598. }
  16599. return mesh;
  16600. };
  16601. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16602. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16603. mesh.material = material;
  16604. mesh.position.copyFrom(this.position);
  16605. mesh.rotation.copyFrom(this.rotation);
  16606. mesh.scaling.copyFrom(this.scaling);
  16607. mesh.computeWorldMatrix(true);
  16608. return mesh;
  16609. };
  16610. return CSG;
  16611. })();
  16612. BABYLON.CSG = CSG;
  16613. })(BABYLON || (BABYLON = {}));
  16614. var __extends = this.__extends || function (d, b) {
  16615. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16616. function __() { this.constructor = d; }
  16617. __.prototype = b.prototype;
  16618. d.prototype = new __();
  16619. };
  16620. var BABYLON;
  16621. (function (BABYLON) {
  16622. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16623. __extends(OculusDistortionCorrectionPostProcess, _super);
  16624. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16625. var _this = this;
  16626. _super.call(this, name, "oculusDistortionCorrection", [
  16627. 'LensCenter',
  16628. 'Scale',
  16629. 'ScaleIn',
  16630. 'HmdWarpParam'
  16631. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16632. this._isRightEye = isRightEye;
  16633. this._distortionFactors = cameraSettings.DistortionK;
  16634. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16635. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16636. this.onSizeChanged = function () {
  16637. _this.aspectRatio = _this.width * .5 / _this.height;
  16638. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16639. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16640. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16641. };
  16642. this.onApply = function (effect) {
  16643. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16644. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16645. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16646. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16647. };
  16648. }
  16649. return OculusDistortionCorrectionPostProcess;
  16650. })(BABYLON.PostProcess);
  16651. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16652. })(BABYLON || (BABYLON = {}));
  16653. var BABYLON;
  16654. (function (BABYLON) {
  16655. (function (JoystickAxis) {
  16656. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16657. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16658. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16659. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16660. var JoystickAxis = BABYLON.JoystickAxis;
  16661. var VirtualJoystick = (function () {
  16662. function VirtualJoystick(leftJoystick) {
  16663. var _this = this;
  16664. if (leftJoystick) {
  16665. this._leftJoystick = true;
  16666. } else {
  16667. this._leftJoystick = false;
  16668. }
  16669. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16670. VirtualJoystick._globalJoystickIndex++;
  16671. this._axisTargetedByLeftAndRight = 0 /* X */;
  16672. this._axisTargetedByUpAndDown = 1 /* Y */;
  16673. this.reverseLeftRight = false;
  16674. this.reverseUpDown = false;
  16675. this._touches = new BABYLON.VirtualJoystick.Collection();
  16676. this.deltaPosition = BABYLON.Vector3.Zero();
  16677. this._joystickSensibility = 25;
  16678. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16679. this._rotationSpeed = 25;
  16680. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16681. this._rotateOnAxisRelativeToMesh = false;
  16682. if (!VirtualJoystick.vjCanvas) {
  16683. window.addEventListener("resize", function () {
  16684. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16685. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16686. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16687. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16688. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16689. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16690. }, false);
  16691. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16692. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16693. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16694. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16695. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16696. VirtualJoystick.vjCanvas.style.width = "100%";
  16697. VirtualJoystick.vjCanvas.style.height = "100%";
  16698. VirtualJoystick.vjCanvas.style.position = "absolute";
  16699. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16700. VirtualJoystick.vjCanvas.style.top = "0px";
  16701. VirtualJoystick.vjCanvas.style.left = "0px";
  16702. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16703. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16704. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16705. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16706. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16707. document.body.appendChild(VirtualJoystick.vjCanvas);
  16708. }
  16709. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16710. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16711. this.pressed = false;
  16712. this._joystickColor = "cyan";
  16713. this._joystickPointerID = -1;
  16714. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16715. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16716. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16717. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16718. _this._onPointerDown(evt);
  16719. }, false);
  16720. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16721. _this._onPointerMove(evt);
  16722. }, false);
  16723. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16724. _this._onPointerUp(evt);
  16725. }, false);
  16726. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16727. _this._onPointerUp(evt);
  16728. }, false);
  16729. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16730. evt.preventDefault();
  16731. }, false);
  16732. requestAnimationFrame(function () {
  16733. _this._drawVirtualJoystick();
  16734. });
  16735. }
  16736. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  16737. this._joystickSensibility = newJoystickSensibility;
  16738. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16739. };
  16740. VirtualJoystick.prototype._onPointerDown = function (e) {
  16741. var positionOnScreenCondition;
  16742. e.preventDefault();
  16743. if (this._leftJoystick === true) {
  16744. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  16745. } else {
  16746. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  16747. }
  16748. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  16749. this._joystickPointerID = e.pointerId;
  16750. this._joystickPointerStartPos.x = e.clientX;
  16751. this._joystickPointerStartPos.y = e.clientY;
  16752. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  16753. this._deltaJoystickVector.x = 0;
  16754. this._deltaJoystickVector.y = 0;
  16755. this.pressed = true;
  16756. this._touches.add(e.pointerId.toString(), e);
  16757. } else {
  16758. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  16759. this._action();
  16760. this._touches.add(e.pointerId.toString(), e);
  16761. }
  16762. }
  16763. };
  16764. VirtualJoystick.prototype._onPointerMove = function (e) {
  16765. if (this._joystickPointerID == e.pointerId) {
  16766. this._joystickPointerPos.x = e.clientX;
  16767. this._joystickPointerPos.y = e.clientY;
  16768. this._deltaJoystickVector = this._joystickPointerPos.clone();
  16769. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  16770. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  16771. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  16772. switch (this._axisTargetedByLeftAndRight) {
  16773. case 0 /* X */:
  16774. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  16775. break;
  16776. case 1 /* Y */:
  16777. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  16778. break;
  16779. case 2 /* Z */:
  16780. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  16781. break;
  16782. }
  16783. var directionUpDown = this.reverseUpDown ? 1 : -1;
  16784. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  16785. switch (this._axisTargetedByUpAndDown) {
  16786. case 0 /* X */:
  16787. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  16788. break;
  16789. case 1 /* Y */:
  16790. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  16791. break;
  16792. case 2 /* Z */:
  16793. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  16794. break;
  16795. }
  16796. } else {
  16797. if (this._touches.item(e.pointerId.toString())) {
  16798. this._touches.item(e.pointerId.toString()).x = e.clientX;
  16799. this._touches.item(e.pointerId.toString()).y = e.clientY;
  16800. }
  16801. }
  16802. };
  16803. VirtualJoystick.prototype._onPointerUp = function (e) {
  16804. this._clearCanvas();
  16805. if (this._joystickPointerID == e.pointerId) {
  16806. this._joystickPointerID = -1;
  16807. this.pressed = false;
  16808. }
  16809. this._deltaJoystickVector.x = 0;
  16810. this._deltaJoystickVector.y = 0;
  16811. this._touches.remove(e.pointerId.toString());
  16812. };
  16813. /**
  16814. * Change the color of the virtual joystick
  16815. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  16816. */
  16817. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  16818. this._joystickColor = newColor;
  16819. };
  16820. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  16821. this._action = action;
  16822. };
  16823. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  16824. switch (axis) {
  16825. case 0 /* X */:
  16826. case 1 /* Y */:
  16827. case 2 /* Z */:
  16828. this._axisTargetedByLeftAndRight = axis;
  16829. break;
  16830. default:
  16831. this._axisTargetedByLeftAndRight = 0 /* X */;
  16832. break;
  16833. }
  16834. };
  16835. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  16836. switch (axis) {
  16837. case 0 /* X */:
  16838. case 1 /* Y */:
  16839. case 2 /* Z */:
  16840. this._axisTargetedByUpAndDown = axis;
  16841. break;
  16842. default:
  16843. this._axisTargetedByUpAndDown = 1 /* Y */;
  16844. break;
  16845. }
  16846. };
  16847. VirtualJoystick.prototype._clearCanvas = function () {
  16848. if (this._leftJoystick) {
  16849. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  16850. } else {
  16851. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  16852. }
  16853. };
  16854. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  16855. var _this = this;
  16856. if (this.pressed) {
  16857. this._clearCanvas();
  16858. this._touches.forEach(function (touch) {
  16859. if (touch.pointerId === _this._joystickPointerID) {
  16860. VirtualJoystick.vjCanvasContext.beginPath();
  16861. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16862. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16863. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  16864. VirtualJoystick.vjCanvasContext.stroke();
  16865. VirtualJoystick.vjCanvasContext.beginPath();
  16866. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16867. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16868. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  16869. VirtualJoystick.vjCanvasContext.stroke();
  16870. VirtualJoystick.vjCanvasContext.beginPath();
  16871. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  16872. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  16873. VirtualJoystick.vjCanvasContext.stroke();
  16874. } else {
  16875. VirtualJoystick.vjCanvasContext.beginPath();
  16876. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  16877. VirtualJoystick.vjCanvasContext.beginPath();
  16878. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  16879. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  16880. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  16881. VirtualJoystick.vjCanvasContext.stroke();
  16882. }
  16883. ;
  16884. });
  16885. }
  16886. requestAnimationFrame(function () {
  16887. _this._drawVirtualJoystick();
  16888. });
  16889. };
  16890. VirtualJoystick.prototype.releaseCanvas = function () {
  16891. if (VirtualJoystick.vjCanvas) {
  16892. document.body.removeChild(VirtualJoystick.vjCanvas);
  16893. VirtualJoystick.vjCanvas = null;
  16894. }
  16895. };
  16896. VirtualJoystick._globalJoystickIndex = 0;
  16897. return VirtualJoystick;
  16898. })();
  16899. BABYLON.VirtualJoystick = VirtualJoystick;
  16900. })(BABYLON || (BABYLON = {}));
  16901. var BABYLON;
  16902. (function (BABYLON) {
  16903. (function (VirtualJoystick) {
  16904. var Collection = (function () {
  16905. function Collection() {
  16906. this._count = 0;
  16907. this._collection = new Array();
  16908. }
  16909. Collection.prototype.Count = function () {
  16910. return this._count;
  16911. };
  16912. Collection.prototype.add = function (key, item) {
  16913. if (this._collection[key] != undefined) {
  16914. return undefined;
  16915. }
  16916. this._collection[key] = item;
  16917. return ++this._count;
  16918. };
  16919. Collection.prototype.remove = function (key) {
  16920. if (this._collection[key] == undefined) {
  16921. return undefined;
  16922. }
  16923. delete this._collection[key];
  16924. return --this._count;
  16925. };
  16926. Collection.prototype.item = function (key) {
  16927. return this._collection[key];
  16928. };
  16929. Collection.prototype.forEach = function (block) {
  16930. var key;
  16931. for (key in this._collection) {
  16932. if (this._collection.hasOwnProperty(key)) {
  16933. block(this._collection[key]);
  16934. }
  16935. }
  16936. };
  16937. return Collection;
  16938. })();
  16939. VirtualJoystick.Collection = Collection;
  16940. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  16941. var VirtualJoystick = BABYLON.VirtualJoystick;
  16942. })(BABYLON || (BABYLON = {}));
  16943. var __extends = this.__extends || function (d, b) {
  16944. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16945. function __() { this.constructor = d; }
  16946. __.prototype = b.prototype;
  16947. d.prototype = new __();
  16948. };
  16949. var BABYLON;
  16950. (function (BABYLON) {
  16951. var OculusRiftDevKit2013_Metric = {
  16952. HResolution: 1280,
  16953. VResolution: 800,
  16954. HScreenSize: 0.149759993,
  16955. VScreenSize: 0.0935999975,
  16956. VScreenCenter: 0.0467999987,
  16957. EyeToScreenDistance: 0.0410000011,
  16958. LensSeparationDistance: 0.0635000020,
  16959. InterpupillaryDistance: 0.0640000030,
  16960. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  16961. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  16962. PostProcessScaleFactor: 1.714605507808412,
  16963. LensCenterOffset: 0.151976421
  16964. };
  16965. var _OculusInnerCamera = (function (_super) {
  16966. __extends(_OculusInnerCamera, _super);
  16967. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  16968. _super.call(this, name, position, scene);
  16969. this._workMatrix = new BABYLON.Matrix();
  16970. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  16971. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  16972. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  16973. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  16974. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  16975. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  16976. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  16977. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  16978. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  16979. }
  16980. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  16981. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  16982. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  16983. return this._projectionMatrix;
  16984. };
  16985. _OculusInnerCamera.prototype._getViewMatrix = function () {
  16986. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  16987. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  16988. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  16989. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  16990. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  16991. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  16992. return this._viewMatrix;
  16993. };
  16994. return _OculusInnerCamera;
  16995. })(BABYLON.FreeCamera);
  16996. var OculusCamera = (function (_super) {
  16997. __extends(OculusCamera, _super);
  16998. function OculusCamera(name, position, scene) {
  16999. _super.call(this, name, position, scene);
  17000. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  17001. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  17002. this.subCameras.push(this._leftCamera);
  17003. this.subCameras.push(this._rightCamera);
  17004. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17005. }
  17006. OculusCamera.prototype._update = function () {
  17007. this._leftCamera.position.copyFrom(this.position);
  17008. this._rightCamera.position.copyFrom(this.position);
  17009. this._updateCamera(this._leftCamera);
  17010. this._updateCamera(this._rightCamera);
  17011. _super.prototype._update.call(this);
  17012. };
  17013. OculusCamera.prototype._updateCamera = function (camera) {
  17014. camera.minZ = this.minZ;
  17015. camera.maxZ = this.maxZ;
  17016. camera.rotation.x = this.rotation.x;
  17017. camera.rotation.y = this.rotation.y;
  17018. camera.rotation.z = this.rotation.z;
  17019. };
  17020. OculusCamera.prototype._onOrientationEvent = function (evt) {
  17021. var yaw = evt.alpha / 180 * Math.PI;
  17022. var pitch = evt.beta / 180 * Math.PI;
  17023. var roll = evt.gamma / 180 * Math.PI;
  17024. if (!this._offsetOrientation) {
  17025. this._offsetOrientation = {
  17026. yaw: yaw,
  17027. pitch: pitch,
  17028. roll: roll
  17029. };
  17030. return;
  17031. } else {
  17032. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17033. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17034. this.rotation.z += this._offsetOrientation.roll - roll;
  17035. this._offsetOrientation.yaw = yaw;
  17036. this._offsetOrientation.pitch = pitch;
  17037. this._offsetOrientation.roll = roll;
  17038. }
  17039. };
  17040. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  17041. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17042. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17043. };
  17044. OculusCamera.prototype.detachControl = function (element) {
  17045. _super.prototype.detachControl.call(this, element);
  17046. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17047. };
  17048. return OculusCamera;
  17049. })(BABYLON.FreeCamera);
  17050. BABYLON.OculusCamera = OculusCamera;
  17051. })(BABYLON || (BABYLON = {}));
  17052. var __extends = this.__extends || function (d, b) {
  17053. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17054. function __() { this.constructor = d; }
  17055. __.prototype = b.prototype;
  17056. d.prototype = new __();
  17057. };
  17058. var BABYLON;
  17059. (function (BABYLON) {
  17060. var OculusRiftDevKit2013_Metric = {
  17061. HResolution: 1280,
  17062. VResolution: 800,
  17063. HScreenSize: 0.149759993,
  17064. VScreenSize: 0.0935999975,
  17065. VScreenCenter: 0.0467999987,
  17066. EyeToScreenDistance: 0.0410000011,
  17067. LensSeparationDistance: 0.0635000020,
  17068. InterpupillaryDistance: 0.0640000030,
  17069. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17070. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17071. PostProcessScaleFactor: 1.714605507808412,
  17072. LensCenterOffset: 0.151976421
  17073. };
  17074. var _OculusInnerGamepadCamera = (function (_super) {
  17075. __extends(_OculusInnerGamepadCamera, _super);
  17076. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  17077. _super.call(this, name, position, scene);
  17078. this._workMatrix = new BABYLON.Matrix();
  17079. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17080. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17081. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17082. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17083. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17084. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17085. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17086. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17087. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17088. }
  17089. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  17090. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17091. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17092. return this._projectionMatrix;
  17093. };
  17094. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  17095. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17096. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17097. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17098. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17099. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17100. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17101. return this._viewMatrix;
  17102. };
  17103. return _OculusInnerGamepadCamera;
  17104. })(BABYLON.FreeCamera);
  17105. var OculusGamepadCamera = (function (_super) {
  17106. __extends(OculusGamepadCamera, _super);
  17107. function OculusGamepadCamera(name, position, scene) {
  17108. var _this = this;
  17109. _super.call(this, name, position, scene);
  17110. this.angularSensibility = 200;
  17111. this.moveSensibility = 75;
  17112. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  17113. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  17114. this.subCameras.push(this._leftCamera);
  17115. this.subCameras.push(this._rightCamera);
  17116. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17117. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  17118. _this._onNewGameConnected(gamepad);
  17119. });
  17120. }
  17121. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  17122. if (gamepad.index === 0) {
  17123. this._gamepad = gamepad;
  17124. }
  17125. };
  17126. OculusGamepadCamera.prototype._update = function () {
  17127. this._leftCamera.position.copyFrom(this.position);
  17128. this._rightCamera.position.copyFrom(this.position);
  17129. this._updateCamera(this._leftCamera);
  17130. this._updateCamera(this._rightCamera);
  17131. _super.prototype._update.call(this);
  17132. };
  17133. OculusGamepadCamera.prototype._checkInputs = function () {
  17134. if (!this._gamepad) {
  17135. return;
  17136. }
  17137. var LSValues = this._gamepad.leftStick;
  17138. var normalizedLX = LSValues.x / this.moveSensibility;
  17139. var normalizedLY = LSValues.y / this.moveSensibility;
  17140. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17141. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17142. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17143. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  17144. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17145. };
  17146. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  17147. camera.minZ = this.minZ;
  17148. camera.maxZ = this.maxZ;
  17149. camera.rotation.x = this.rotation.x;
  17150. camera.rotation.y = this.rotation.y;
  17151. camera.rotation.z = this.rotation.z;
  17152. };
  17153. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  17154. var yaw = evt.alpha / 180 * Math.PI;
  17155. var pitch = evt.beta / 180 * Math.PI;
  17156. var roll = evt.gamma / 180 * Math.PI;
  17157. if (!this._offsetOrientation) {
  17158. this._offsetOrientation = {
  17159. yaw: yaw,
  17160. pitch: pitch,
  17161. roll: roll
  17162. };
  17163. return;
  17164. } else {
  17165. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17166. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17167. this.rotation.z += this._offsetOrientation.roll - roll;
  17168. this._offsetOrientation.yaw = yaw;
  17169. this._offsetOrientation.pitch = pitch;
  17170. this._offsetOrientation.roll = roll;
  17171. }
  17172. };
  17173. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  17174. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17175. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17176. };
  17177. OculusGamepadCamera.prototype.detachControl = function (element) {
  17178. _super.prototype.detachControl.call(this, element);
  17179. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17180. };
  17181. OculusGamepadCamera.prototype.dispose = function () {
  17182. this._gamepads.dispose();
  17183. _super.prototype.dispose.call(this);
  17184. };
  17185. return OculusGamepadCamera;
  17186. })(BABYLON.FreeCamera);
  17187. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  17188. })(BABYLON || (BABYLON = {}));
  17189. var __extends = this.__extends || function (d, b) {
  17190. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17191. function __() { this.constructor = d; }
  17192. __.prototype = b.prototype;
  17193. d.prototype = new __();
  17194. };
  17195. var BABYLON;
  17196. (function (BABYLON) {
  17197. var VirtualJoysticksCamera = (function (_super) {
  17198. __extends(VirtualJoysticksCamera, _super);
  17199. function VirtualJoysticksCamera(name, position, scene) {
  17200. _super.call(this, name, position, scene);
  17201. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  17202. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  17203. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  17204. this._leftjoystick.setJoystickSensibility(0.15);
  17205. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  17206. this._rightjoystick.setAxisForUpDown(0 /* X */);
  17207. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  17208. this._rightjoystick.reverseUpDown = true;
  17209. this._rightjoystick.setJoystickSensibility(0.05);
  17210. this._rightjoystick.setJoystickColor("yellow");
  17211. }
  17212. VirtualJoysticksCamera.prototype._checkInputs = function () {
  17213. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17214. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  17215. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17216. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  17217. if (!this._leftjoystick.pressed) {
  17218. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  17219. }
  17220. if (!this._rightjoystick.pressed) {
  17221. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  17222. }
  17223. };
  17224. VirtualJoysticksCamera.prototype.dispose = function () {
  17225. this._leftjoystick.releaseCanvas();
  17226. _super.prototype.dispose.call(this);
  17227. };
  17228. return VirtualJoysticksCamera;
  17229. })(BABYLON.FreeCamera);
  17230. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  17231. })(BABYLON || (BABYLON = {}));
  17232. var __extends = this.__extends || function (d, b) {
  17233. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17234. function __() { this.constructor = d; }
  17235. __.prototype = b.prototype;
  17236. d.prototype = new __();
  17237. };
  17238. var BABYLON;
  17239. (function (BABYLON) {
  17240. var ShaderMaterial = (function (_super) {
  17241. __extends(ShaderMaterial, _super);
  17242. function ShaderMaterial(name, scene, shaderPath, options) {
  17243. _super.call(this, name, scene);
  17244. this._textures = new Array();
  17245. this._floats = new Array();
  17246. this._floatsArrays = {};
  17247. this._colors3 = new Array();
  17248. this._colors4 = new Array();
  17249. this._vectors2 = new Array();
  17250. this._vectors3 = new Array();
  17251. this._matrices = new Array();
  17252. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  17253. this._shaderPath = shaderPath;
  17254. options.needAlphaBlending = options.needAlphaBlending || false;
  17255. options.needAlphaTesting = options.needAlphaTesting || false;
  17256. options.attributes = options.attributes || ["position", "normal", "uv"];
  17257. options.uniforms = options.uniforms || ["worldViewProjection"];
  17258. options.samplers = options.samplers || [];
  17259. this._options = options;
  17260. }
  17261. ShaderMaterial.prototype.needAlphaBlending = function () {
  17262. return this._options.needAlphaBlending;
  17263. };
  17264. ShaderMaterial.prototype.needAlphaTesting = function () {
  17265. return this._options.needAlphaTesting;
  17266. };
  17267. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  17268. if (this._options.uniforms.indexOf(uniformName) === -1) {
  17269. this._options.uniforms.push(uniformName);
  17270. }
  17271. };
  17272. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17273. if (this._options.samplers.indexOf(name) === -1) {
  17274. this._options.samplers.push(name);
  17275. }
  17276. this._textures[name] = texture;
  17277. return this;
  17278. };
  17279. ShaderMaterial.prototype.setFloat = function (name, value) {
  17280. this._checkUniform(name);
  17281. this._floats[name] = value;
  17282. return this;
  17283. };
  17284. ShaderMaterial.prototype.setFloats = function (name, value) {
  17285. this._checkUniform(name);
  17286. this._floatsArrays[name] = value;
  17287. return this;
  17288. };
  17289. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17290. this._checkUniform(name);
  17291. this._colors3[name] = value;
  17292. return this;
  17293. };
  17294. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17295. this._checkUniform(name);
  17296. this._colors4[name] = value;
  17297. return this;
  17298. };
  17299. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17300. this._checkUniform(name);
  17301. this._vectors2[name] = value;
  17302. return this;
  17303. };
  17304. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17305. this._checkUniform(name);
  17306. this._vectors3[name] = value;
  17307. return this;
  17308. };
  17309. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17310. this._checkUniform(name);
  17311. this._matrices[name] = value;
  17312. return this;
  17313. };
  17314. ShaderMaterial.prototype.isReady = function () {
  17315. var engine = this.getScene().getEngine();
  17316. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17317. if (!this._effect.isReady()) {
  17318. return false;
  17319. }
  17320. return true;
  17321. };
  17322. ShaderMaterial.prototype.bind = function (world) {
  17323. if (this._options.uniforms.indexOf("world") !== -1) {
  17324. this._effect.setMatrix("world", world);
  17325. }
  17326. if (this._options.uniforms.indexOf("view") !== -1) {
  17327. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17328. }
  17329. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17330. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17331. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17332. }
  17333. if (this._options.uniforms.indexOf("projection") !== -1) {
  17334. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17335. }
  17336. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  17337. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  17338. }
  17339. for (var name in this._textures) {
  17340. this._effect.setTexture(name, this._textures[name]);
  17341. }
  17342. for (name in this._floats) {
  17343. this._effect.setFloat(name, this._floats[name]);
  17344. }
  17345. for (name in this._floatsArrays) {
  17346. this._effect.setArray(name, this._floatsArrays[name]);
  17347. }
  17348. for (name in this._colors3) {
  17349. this._effect.setColor3(name, this._colors3[name]);
  17350. }
  17351. for (name in this._colors4) {
  17352. var color = this._colors4[name];
  17353. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17354. }
  17355. for (name in this._vectors2) {
  17356. this._effect.setVector2(name, this._vectors2[name]);
  17357. }
  17358. for (name in this._vectors3) {
  17359. this._effect.setVector3(name, this._vectors3[name]);
  17360. }
  17361. for (name in this._matrices) {
  17362. this._effect.setMatrix(name, this._matrices[name]);
  17363. }
  17364. };
  17365. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  17366. for (var name in this._textures) {
  17367. this._textures[name].dispose();
  17368. }
  17369. this._textures = [];
  17370. _super.prototype.dispose.call(this, forceDisposeEffect);
  17371. };
  17372. return ShaderMaterial;
  17373. })(BABYLON.Material);
  17374. BABYLON.ShaderMaterial = ShaderMaterial;
  17375. })(BABYLON || (BABYLON = {}));
  17376. var BABYLON;
  17377. (function (BABYLON) {
  17378. var VertexData = (function () {
  17379. function VertexData() {
  17380. }
  17381. VertexData.prototype.set = function (data, kind) {
  17382. switch (kind) {
  17383. case BABYLON.VertexBuffer.PositionKind:
  17384. this.positions = data;
  17385. break;
  17386. case BABYLON.VertexBuffer.NormalKind:
  17387. this.normals = data;
  17388. break;
  17389. case BABYLON.VertexBuffer.UVKind:
  17390. this.uvs = data;
  17391. break;
  17392. case BABYLON.VertexBuffer.UV2Kind:
  17393. this.uv2s = data;
  17394. break;
  17395. case BABYLON.VertexBuffer.ColorKind:
  17396. this.colors = data;
  17397. break;
  17398. case BABYLON.VertexBuffer.MatricesIndicesKind:
  17399. this.matricesIndices = data;
  17400. break;
  17401. case BABYLON.VertexBuffer.MatricesWeightsKind:
  17402. this.matricesWeights = data;
  17403. break;
  17404. }
  17405. };
  17406. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  17407. this._applyTo(mesh, updatable);
  17408. };
  17409. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  17410. this._applyTo(geometry, updatable);
  17411. };
  17412. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  17413. this._update(mesh);
  17414. };
  17415. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  17416. this._update(geometry);
  17417. };
  17418. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  17419. if (this.positions) {
  17420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  17421. }
  17422. if (this.normals) {
  17423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  17424. }
  17425. if (this.uvs) {
  17426. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  17427. }
  17428. if (this.uv2s) {
  17429. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  17430. }
  17431. if (this.colors) {
  17432. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  17433. }
  17434. if (this.matricesIndices) {
  17435. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  17436. }
  17437. if (this.matricesWeights) {
  17438. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  17439. }
  17440. if (this.indices) {
  17441. meshOrGeometry.setIndices(this.indices);
  17442. }
  17443. };
  17444. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  17445. if (this.positions) {
  17446. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  17447. }
  17448. if (this.normals) {
  17449. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  17450. }
  17451. if (this.uvs) {
  17452. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  17453. }
  17454. if (this.uv2s) {
  17455. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  17456. }
  17457. if (this.colors) {
  17458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  17459. }
  17460. if (this.matricesIndices) {
  17461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17462. }
  17463. if (this.matricesWeights) {
  17464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17465. }
  17466. if (this.indices) {
  17467. meshOrGeometry.setIndices(this.indices);
  17468. }
  17469. };
  17470. VertexData.prototype.transform = function (matrix) {
  17471. var transformed = BABYLON.Vector3.Zero();
  17472. if (this.positions) {
  17473. var position = BABYLON.Vector3.Zero();
  17474. for (var index = 0; index < this.positions.length; index += 3) {
  17475. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17476. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17477. this.positions[index] = transformed.x;
  17478. this.positions[index + 1] = transformed.y;
  17479. this.positions[index + 2] = transformed.z;
  17480. }
  17481. }
  17482. if (this.normals) {
  17483. var normal = BABYLON.Vector3.Zero();
  17484. for (index = 0; index < this.normals.length; index += 3) {
  17485. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17486. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17487. this.normals[index] = transformed.x;
  17488. this.normals[index + 1] = transformed.y;
  17489. this.normals[index + 2] = transformed.z;
  17490. }
  17491. }
  17492. };
  17493. VertexData.prototype.merge = function (other) {
  17494. if (other.indices) {
  17495. if (!this.indices) {
  17496. this.indices = [];
  17497. }
  17498. var offset = this.positions ? this.positions.length / 3 : 0;
  17499. for (var index = 0; index < other.indices.length; index++) {
  17500. this.indices.push(other.indices[index] + offset);
  17501. }
  17502. }
  17503. if (other.positions) {
  17504. if (!this.positions) {
  17505. this.positions = [];
  17506. }
  17507. for (index = 0; index < other.positions.length; index++) {
  17508. this.positions.push(other.positions[index]);
  17509. }
  17510. }
  17511. if (other.normals) {
  17512. if (!this.normals) {
  17513. this.normals = [];
  17514. }
  17515. for (index = 0; index < other.normals.length; index++) {
  17516. this.normals.push(other.normals[index]);
  17517. }
  17518. }
  17519. if (other.uvs) {
  17520. if (!this.uvs) {
  17521. this.uvs = [];
  17522. }
  17523. for (index = 0; index < other.uvs.length; index++) {
  17524. this.uvs.push(other.uvs[index]);
  17525. }
  17526. }
  17527. if (other.uv2s) {
  17528. if (!this.uv2s) {
  17529. this.uv2s = [];
  17530. }
  17531. for (index = 0; index < other.uv2s.length; index++) {
  17532. this.uv2s.push(other.uv2s[index]);
  17533. }
  17534. }
  17535. if (other.matricesIndices) {
  17536. if (!this.matricesIndices) {
  17537. this.matricesIndices = [];
  17538. }
  17539. for (index = 0; index < other.matricesIndices.length; index++) {
  17540. this.matricesIndices.push(other.matricesIndices[index]);
  17541. }
  17542. }
  17543. if (other.matricesWeights) {
  17544. if (!this.matricesWeights) {
  17545. this.matricesWeights = [];
  17546. }
  17547. for (index = 0; index < other.matricesWeights.length; index++) {
  17548. this.matricesWeights.push(other.matricesWeights[index]);
  17549. }
  17550. }
  17551. if (other.colors) {
  17552. if (!this.colors) {
  17553. this.colors = [];
  17554. }
  17555. for (index = 0; index < other.colors.length; index++) {
  17556. this.colors.push(other.colors[index]);
  17557. }
  17558. }
  17559. };
  17560. VertexData.ExtractFromMesh = function (mesh) {
  17561. return VertexData._ExtractFrom(mesh);
  17562. };
  17563. VertexData.ExtractFromGeometry = function (geometry) {
  17564. return VertexData._ExtractFrom(geometry);
  17565. };
  17566. VertexData._ExtractFrom = function (meshOrGeometry) {
  17567. var result = new BABYLON.VertexData();
  17568. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17569. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17570. }
  17571. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17572. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17573. }
  17574. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17575. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17576. }
  17577. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17578. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17579. }
  17580. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17581. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17582. }
  17583. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17584. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17585. }
  17586. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17587. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17588. }
  17589. result.indices = meshOrGeometry.getIndices();
  17590. return result;
  17591. };
  17592. VertexData.CreateBox = function (size) {
  17593. var normalsSource = [
  17594. new BABYLON.Vector3(0, 0, 1),
  17595. new BABYLON.Vector3(0, 0, -1),
  17596. new BABYLON.Vector3(1, 0, 0),
  17597. new BABYLON.Vector3(-1, 0, 0),
  17598. new BABYLON.Vector3(0, 1, 0),
  17599. new BABYLON.Vector3(0, -1, 0)
  17600. ];
  17601. var indices = [];
  17602. var positions = [];
  17603. var normals = [];
  17604. var uvs = [];
  17605. size = size || 1;
  17606. for (var index = 0; index < normalsSource.length; index++) {
  17607. var normal = normalsSource[index];
  17608. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17609. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17610. var verticesLength = positions.length / 3;
  17611. indices.push(verticesLength);
  17612. indices.push(verticesLength + 1);
  17613. indices.push(verticesLength + 2);
  17614. indices.push(verticesLength);
  17615. indices.push(verticesLength + 2);
  17616. indices.push(verticesLength + 3);
  17617. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17618. positions.push(vertex.x, vertex.y, vertex.z);
  17619. normals.push(normal.x, normal.y, normal.z);
  17620. uvs.push(1.0, 1.0);
  17621. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17622. positions.push(vertex.x, vertex.y, vertex.z);
  17623. normals.push(normal.x, normal.y, normal.z);
  17624. uvs.push(0.0, 1.0);
  17625. vertex = normal.add(side1).add(side2).scale(size / 2);
  17626. positions.push(vertex.x, vertex.y, vertex.z);
  17627. normals.push(normal.x, normal.y, normal.z);
  17628. uvs.push(0.0, 0.0);
  17629. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17630. positions.push(vertex.x, vertex.y, vertex.z);
  17631. normals.push(normal.x, normal.y, normal.z);
  17632. uvs.push(1.0, 0.0);
  17633. }
  17634. var vertexData = new BABYLON.VertexData();
  17635. vertexData.indices = indices;
  17636. vertexData.positions = positions;
  17637. vertexData.normals = normals;
  17638. vertexData.uvs = uvs;
  17639. return vertexData;
  17640. };
  17641. VertexData.CreateSphere = function (segments, diameter) {
  17642. segments = segments || 32;
  17643. diameter = diameter || 1;
  17644. var radius = diameter / 2;
  17645. var totalZRotationSteps = 2 + segments;
  17646. var totalYRotationSteps = 2 * totalZRotationSteps;
  17647. var indices = [];
  17648. var positions = [];
  17649. var normals = [];
  17650. var uvs = [];
  17651. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17652. var normalizedZ = zRotationStep / totalZRotationSteps;
  17653. var angleZ = (normalizedZ * Math.PI);
  17654. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17655. var normalizedY = yRotationStep / totalYRotationSteps;
  17656. var angleY = normalizedY * Math.PI * 2;
  17657. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17658. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17659. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17660. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17661. var vertex = complete.scale(radius);
  17662. var normal = BABYLON.Vector3.Normalize(vertex);
  17663. positions.push(vertex.x, vertex.y, vertex.z);
  17664. normals.push(normal.x, normal.y, normal.z);
  17665. uvs.push(normalizedZ, normalizedY);
  17666. }
  17667. if (zRotationStep > 0) {
  17668. var verticesCount = positions.length / 3;
  17669. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17670. indices.push((firstIndex));
  17671. indices.push((firstIndex + 1));
  17672. indices.push(firstIndex + totalYRotationSteps + 1);
  17673. indices.push((firstIndex + totalYRotationSteps + 1));
  17674. indices.push((firstIndex + 1));
  17675. indices.push((firstIndex + totalYRotationSteps + 2));
  17676. }
  17677. }
  17678. }
  17679. var vertexData = new BABYLON.VertexData();
  17680. vertexData.indices = indices;
  17681. vertexData.positions = positions;
  17682. vertexData.normals = normals;
  17683. vertexData.uvs = uvs;
  17684. return vertexData;
  17685. };
  17686. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17687. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17688. var radiusTop = diameterTop / 2;
  17689. var radiusBottom = diameterBottom / 2;
  17690. var indices = [];
  17691. var positions = [];
  17692. var normals = [];
  17693. var uvs = [];
  17694. height = height || 1;
  17695. diameterTop = diameterTop || 0.5;
  17696. diameterBottom = diameterBottom || 1;
  17697. tessellation = tessellation || 16;
  17698. subdivisions = subdivisions || 1;
  17699. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17700. var getCircleVector = function (i) {
  17701. var angle = (i * 2.0 * Math.PI / tessellation);
  17702. var dx = Math.cos(angle);
  17703. var dz = Math.sin(angle);
  17704. return new BABYLON.Vector3(dx, 0, dz);
  17705. };
  17706. var createCylinderCap = function (isTop) {
  17707. var radius = isTop ? radiusTop : radiusBottom;
  17708. if (radius == 0) {
  17709. return;
  17710. }
  17711. var vbase = positions.length / 3;
  17712. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17713. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17714. if (!isTop) {
  17715. offset.scaleInPlace(-1);
  17716. textureScale.x = -textureScale.x;
  17717. }
  17718. for (i = 0; i < tessellation; i++) {
  17719. var circleVector = getCircleVector(i);
  17720. var position = circleVector.scale(radius).add(offset);
  17721. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17722. positions.push(position.x, position.y, position.z);
  17723. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17724. }
  17725. for (var i = 0; i < tessellation - 2; i++) {
  17726. if (!isTop) {
  17727. indices.push(vbase);
  17728. indices.push(vbase + (i + 2) % tessellation);
  17729. indices.push(vbase + (i + 1) % tessellation);
  17730. } else {
  17731. indices.push(vbase);
  17732. indices.push(vbase + (i + 1) % tessellation);
  17733. indices.push(vbase + (i + 2) % tessellation);
  17734. }
  17735. }
  17736. };
  17737. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  17738. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  17739. var stride = tessellation + 1;
  17740. for (var i = 0; i <= tessellation; i++) {
  17741. var circleVector = getCircleVector(i);
  17742. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  17743. var position, radius = radiusBottom;
  17744. for (var s = 0; s <= subdivisions; s++) {
  17745. position = circleVector.scale(radius);
  17746. position.addInPlace(base.add(offset.scale(s)));
  17747. textureCoordinate.y += 1 / subdivisions;
  17748. radius += (radiusTop - radiusBottom) / subdivisions;
  17749. positions.push(position.x, position.y, position.z);
  17750. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17751. }
  17752. }
  17753. subdivisions += 1;
  17754. for (var s = 0; s < subdivisions - 1; s++) {
  17755. for (var i = 0; i <= tessellation; i++) {
  17756. indices.push(i * subdivisions + s);
  17757. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17758. indices.push(i * subdivisions + (s + 1));
  17759. indices.push(i * subdivisions + (s + 1));
  17760. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  17761. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  17762. }
  17763. }
  17764. createCylinderCap(true);
  17765. createCylinderCap(false);
  17766. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17767. var vertexData = new BABYLON.VertexData();
  17768. vertexData.indices = indices;
  17769. vertexData.positions = positions;
  17770. vertexData.normals = normals;
  17771. vertexData.uvs = uvs;
  17772. return vertexData;
  17773. };
  17774. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  17775. var indices = [];
  17776. var positions = [];
  17777. var normals = [];
  17778. var uvs = [];
  17779. diameter = diameter || 1;
  17780. thickness = thickness || 0.5;
  17781. tessellation = tessellation || 16;
  17782. var stride = tessellation + 1;
  17783. for (var i = 0; i <= tessellation; i++) {
  17784. var u = i / tessellation;
  17785. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  17786. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  17787. for (var j = 0; j <= tessellation; j++) {
  17788. var v = 1 - j / tessellation;
  17789. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  17790. var dx = Math.cos(innerAngle);
  17791. var dy = Math.sin(innerAngle);
  17792. var normal = new BABYLON.Vector3(dx, dy, 0);
  17793. var position = normal.scale(thickness / 2);
  17794. var textureCoordinate = new BABYLON.Vector2(u, v);
  17795. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  17796. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  17797. positions.push(position.x, position.y, position.z);
  17798. normals.push(normal.x, normal.y, normal.z);
  17799. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17800. var nextI = (i + 1) % stride;
  17801. var nextJ = (j + 1) % stride;
  17802. indices.push(i * stride + j);
  17803. indices.push(i * stride + nextJ);
  17804. indices.push(nextI * stride + j);
  17805. indices.push(i * stride + nextJ);
  17806. indices.push(nextI * stride + nextJ);
  17807. indices.push(nextI * stride + j);
  17808. }
  17809. }
  17810. var vertexData = new BABYLON.VertexData();
  17811. vertexData.indices = indices;
  17812. vertexData.positions = positions;
  17813. vertexData.normals = normals;
  17814. vertexData.uvs = uvs;
  17815. return vertexData;
  17816. };
  17817. VertexData.CreateLines = function (points) {
  17818. var indices = [];
  17819. var positions = [];
  17820. for (var index = 0; index < points.length; index++) {
  17821. positions.push(points[index].x, points[index].y, points[index].z);
  17822. if (index > 0) {
  17823. indices.push(index - 1);
  17824. indices.push(index);
  17825. }
  17826. }
  17827. var vertexData = new BABYLON.VertexData();
  17828. vertexData.indices = indices;
  17829. vertexData.positions = positions;
  17830. return vertexData;
  17831. };
  17832. VertexData.CreateGround = function (width, height, subdivisions) {
  17833. var indices = [];
  17834. var positions = [];
  17835. var normals = [];
  17836. var uvs = [];
  17837. var row, col;
  17838. width = width || 1;
  17839. height = height || 1;
  17840. subdivisions = subdivisions || 1;
  17841. for (row = 0; row <= subdivisions; row++) {
  17842. for (col = 0; col <= subdivisions; col++) {
  17843. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17844. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17845. positions.push(position.x, position.y, position.z);
  17846. normals.push(normal.x, normal.y, normal.z);
  17847. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17848. }
  17849. }
  17850. for (row = 0; row < subdivisions; row++) {
  17851. for (col = 0; col < subdivisions; col++) {
  17852. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17853. indices.push(col + 1 + row * (subdivisions + 1));
  17854. indices.push(col + row * (subdivisions + 1));
  17855. indices.push(col + (row + 1) * (subdivisions + 1));
  17856. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17857. indices.push(col + row * (subdivisions + 1));
  17858. }
  17859. }
  17860. var vertexData = new BABYLON.VertexData();
  17861. vertexData.indices = indices;
  17862. vertexData.positions = positions;
  17863. vertexData.normals = normals;
  17864. vertexData.uvs = uvs;
  17865. return vertexData;
  17866. };
  17867. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  17868. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  17869. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  17870. var indices = [];
  17871. var positions = [];
  17872. var normals = [];
  17873. var uvs = [];
  17874. var row, col, tileRow, tileCol;
  17875. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  17876. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  17877. precision.w = (precision.w < 1) ? 1 : precision.w;
  17878. precision.h = (precision.h < 1) ? 1 : precision.h;
  17879. var tileSize = {
  17880. 'w': (xmax - xmin) / subdivisions.w,
  17881. 'h': (zmax - zmin) / subdivisions.h
  17882. };
  17883. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  17884. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  17885. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  17886. }
  17887. }
  17888. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  17889. var base = positions.length / 3;
  17890. var rowLength = precision.w + 1;
  17891. for (row = 0; row < precision.h; row++) {
  17892. for (col = 0; col < precision.w; col++) {
  17893. var square = [
  17894. base + col + row * rowLength,
  17895. base + (col + 1) + row * rowLength,
  17896. base + (col + 1) + (row + 1) * rowLength,
  17897. base + col + (row + 1) * rowLength
  17898. ];
  17899. indices.push(square[1]);
  17900. indices.push(square[2]);
  17901. indices.push(square[3]);
  17902. indices.push(square[0]);
  17903. indices.push(square[1]);
  17904. indices.push(square[3]);
  17905. }
  17906. }
  17907. var position = BABYLON.Vector3.Zero();
  17908. var normal = new BABYLON.Vector3(0, 1.0, 0);
  17909. for (row = 0; row <= precision.h; row++) {
  17910. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  17911. for (col = 0; col <= precision.w; col++) {
  17912. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  17913. position.y = 0;
  17914. positions.push(position.x, position.y, position.z);
  17915. normals.push(normal.x, normal.y, normal.z);
  17916. uvs.push(col / precision.w, row / precision.h);
  17917. }
  17918. }
  17919. }
  17920. var vertexData = new BABYLON.VertexData();
  17921. vertexData.indices = indices;
  17922. vertexData.positions = positions;
  17923. vertexData.normals = normals;
  17924. vertexData.uvs = uvs;
  17925. return vertexData;
  17926. };
  17927. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  17928. var indices = [];
  17929. var positions = [];
  17930. var normals = [];
  17931. var uvs = [];
  17932. var row, col;
  17933. for (row = 0; row <= subdivisions; row++) {
  17934. for (col = 0; col <= subdivisions; col++) {
  17935. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  17936. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  17937. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  17938. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  17939. var r = buffer[pos] / 255.0;
  17940. var g = buffer[pos + 1] / 255.0;
  17941. var b = buffer[pos + 2] / 255.0;
  17942. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17943. position.y = minHeight + (maxHeight - minHeight) * gradient;
  17944. positions.push(position.x, position.y, position.z);
  17945. normals.push(0, 0, 0);
  17946. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  17947. }
  17948. }
  17949. for (row = 0; row < subdivisions; row++) {
  17950. for (col = 0; col < subdivisions; col++) {
  17951. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17952. indices.push(col + 1 + row * (subdivisions + 1));
  17953. indices.push(col + row * (subdivisions + 1));
  17954. indices.push(col + (row + 1) * (subdivisions + 1));
  17955. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  17956. indices.push(col + row * (subdivisions + 1));
  17957. }
  17958. }
  17959. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17960. var vertexData = new BABYLON.VertexData();
  17961. vertexData.indices = indices;
  17962. vertexData.positions = positions;
  17963. vertexData.normals = normals;
  17964. vertexData.uvs = uvs;
  17965. return vertexData;
  17966. };
  17967. VertexData.CreatePlane = function (size) {
  17968. var indices = [];
  17969. var positions = [];
  17970. var normals = [];
  17971. var uvs = [];
  17972. size = size || 1;
  17973. var halfSize = size / 2.0;
  17974. positions.push(-halfSize, -halfSize, 0);
  17975. normals.push(0, 0, -1.0);
  17976. uvs.push(0.0, 0.0);
  17977. positions.push(halfSize, -halfSize, 0);
  17978. normals.push(0, 0, -1.0);
  17979. uvs.push(1.0, 0.0);
  17980. positions.push(halfSize, halfSize, 0);
  17981. normals.push(0, 0, -1.0);
  17982. uvs.push(1.0, 1.0);
  17983. positions.push(-halfSize, halfSize, 0);
  17984. normals.push(0, 0, -1.0);
  17985. uvs.push(0.0, 1.0);
  17986. indices.push(0);
  17987. indices.push(1);
  17988. indices.push(2);
  17989. indices.push(0);
  17990. indices.push(2);
  17991. indices.push(3);
  17992. var vertexData = new BABYLON.VertexData();
  17993. vertexData.indices = indices;
  17994. vertexData.positions = positions;
  17995. vertexData.normals = normals;
  17996. vertexData.uvs = uvs;
  17997. return vertexData;
  17998. };
  17999. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  18000. var indices = [];
  18001. var positions = [];
  18002. var normals = [];
  18003. var uvs = [];
  18004. radius = radius || 2;
  18005. tube = tube || 0.5;
  18006. radialSegments = radialSegments || 32;
  18007. tubularSegments = tubularSegments || 32;
  18008. p = p || 2;
  18009. q = q || 3;
  18010. var getPos = function (angle) {
  18011. var cu = Math.cos(angle);
  18012. var su = Math.sin(angle);
  18013. var quOverP = q / p * angle;
  18014. var cs = Math.cos(quOverP);
  18015. var tx = radius * (2 + cs) * 0.5 * cu;
  18016. var ty = radius * (2 + cs) * su * 0.5;
  18017. var tz = radius * Math.sin(quOverP) * 0.5;
  18018. return new BABYLON.Vector3(tx, ty, tz);
  18019. };
  18020. for (var i = 0; i <= radialSegments; i++) {
  18021. var modI = i % radialSegments;
  18022. var u = modI / radialSegments * 2 * p * Math.PI;
  18023. var p1 = getPos(u);
  18024. var p2 = getPos(u + 0.01);
  18025. var tang = p2.subtract(p1);
  18026. var n = p2.add(p1);
  18027. var bitan = BABYLON.Vector3.Cross(tang, n);
  18028. n = BABYLON.Vector3.Cross(bitan, tang);
  18029. bitan.normalize();
  18030. n.normalize();
  18031. for (var j = 0; j < tubularSegments; j++) {
  18032. var modJ = j % tubularSegments;
  18033. var v = modJ / tubularSegments * 2 * Math.PI;
  18034. var cx = -tube * Math.cos(v);
  18035. var cy = tube * Math.sin(v);
  18036. positions.push(p1.x + cx * n.x + cy * bitan.x);
  18037. positions.push(p1.y + cx * n.y + cy * bitan.y);
  18038. positions.push(p1.z + cx * n.z + cy * bitan.z);
  18039. uvs.push(i / radialSegments);
  18040. uvs.push(j / tubularSegments);
  18041. }
  18042. }
  18043. for (i = 0; i < radialSegments; i++) {
  18044. for (j = 0; j < tubularSegments; j++) {
  18045. var jNext = (j + 1) % tubularSegments;
  18046. var a = i * tubularSegments + j;
  18047. var b = (i + 1) * tubularSegments + j;
  18048. var c = (i + 1) * tubularSegments + jNext;
  18049. var d = i * tubularSegments + jNext;
  18050. indices.push(d);
  18051. indices.push(b);
  18052. indices.push(a);
  18053. indices.push(d);
  18054. indices.push(c);
  18055. indices.push(b);
  18056. }
  18057. }
  18058. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18059. var vertexData = new BABYLON.VertexData();
  18060. vertexData.indices = indices;
  18061. vertexData.positions = positions;
  18062. vertexData.normals = normals;
  18063. vertexData.uvs = uvs;
  18064. return vertexData;
  18065. };
  18066. VertexData.ComputeNormals = function (positions, indices, normals) {
  18067. var positionVectors = [];
  18068. var facesOfVertices = [];
  18069. var index;
  18070. for (index = 0; index < positions.length; index += 3) {
  18071. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  18072. positionVectors.push(vector3);
  18073. facesOfVertices.push([]);
  18074. }
  18075. var facesNormals = [];
  18076. for (index = 0; index < indices.length / 3; index++) {
  18077. var i1 = indices[index * 3];
  18078. var i2 = indices[index * 3 + 1];
  18079. var i3 = indices[index * 3 + 2];
  18080. var p1 = positionVectors[i1];
  18081. var p2 = positionVectors[i2];
  18082. var p3 = positionVectors[i3];
  18083. var p1p2 = p1.subtract(p2);
  18084. var p3p2 = p3.subtract(p2);
  18085. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18086. facesOfVertices[i1].push(index);
  18087. facesOfVertices[i2].push(index);
  18088. facesOfVertices[i3].push(index);
  18089. }
  18090. for (index = 0; index < positionVectors.length; index++) {
  18091. var faces = facesOfVertices[index];
  18092. var normal = BABYLON.Vector3.Zero();
  18093. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  18094. normal.addInPlace(facesNormals[faces[faceIndex]]);
  18095. }
  18096. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  18097. normals[index * 3] = normal.x;
  18098. normals[index * 3 + 1] = normal.y;
  18099. normals[index * 3 + 2] = normal.z;
  18100. }
  18101. };
  18102. return VertexData;
  18103. })();
  18104. BABYLON.VertexData = VertexData;
  18105. })(BABYLON || (BABYLON = {}));
  18106. var __extends = this.__extends || function (d, b) {
  18107. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18108. function __() { this.constructor = d; }
  18109. __.prototype = b.prototype;
  18110. d.prototype = new __();
  18111. };
  18112. var BABYLON;
  18113. (function (BABYLON) {
  18114. var buildCamera = function (that, name) {
  18115. that._leftCamera.isIntermediate = true;
  18116. that.subCameras.push(that._leftCamera);
  18117. that.subCameras.push(that._rightCamera);
  18118. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  18119. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  18120. that._anaglyphPostProcess.onApply = function (effect) {
  18121. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  18122. };
  18123. that._update();
  18124. };
  18125. var AnaglyphArcRotateCamera = (function (_super) {
  18126. __extends(AnaglyphArcRotateCamera, _super);
  18127. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  18128. _super.call(this, name, alpha, beta, radius, target, scene);
  18129. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18130. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  18131. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  18132. buildCamera(this, name);
  18133. }
  18134. AnaglyphArcRotateCamera.prototype._update = function () {
  18135. this._updateCamera(this._leftCamera);
  18136. this._updateCamera(this._rightCamera);
  18137. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  18138. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  18139. _super.prototype._update.call(this);
  18140. };
  18141. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  18142. camera.beta = this.beta;
  18143. camera.radius = this.radius;
  18144. camera.minZ = this.minZ;
  18145. camera.maxZ = this.maxZ;
  18146. camera.fov = this.fov;
  18147. camera.target = this.target;
  18148. };
  18149. return AnaglyphArcRotateCamera;
  18150. })(BABYLON.ArcRotateCamera);
  18151. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  18152. var AnaglyphFreeCamera = (function (_super) {
  18153. __extends(AnaglyphFreeCamera, _super);
  18154. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  18155. _super.call(this, name, position, scene);
  18156. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18157. this._transformMatrix = new BABYLON.Matrix();
  18158. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  18159. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  18160. buildCamera(this, name);
  18161. }
  18162. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  18163. var target = this.getTarget();
  18164. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  18165. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18166. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  18167. };
  18168. AnaglyphFreeCamera.prototype._update = function () {
  18169. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  18170. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  18171. this._updateCamera(this._leftCamera);
  18172. this._updateCamera(this._rightCamera);
  18173. _super.prototype._update.call(this);
  18174. };
  18175. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  18176. camera.minZ = this.minZ;
  18177. camera.maxZ = this.maxZ;
  18178. camera.fov = this.fov;
  18179. camera.viewport = this.viewport;
  18180. camera.setTarget(this.getTarget());
  18181. };
  18182. return AnaglyphFreeCamera;
  18183. })(BABYLON.FreeCamera);
  18184. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  18185. })(BABYLON || (BABYLON = {}));
  18186. var __extends = this.__extends || function (d, b) {
  18187. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18188. function __() { this.constructor = d; }
  18189. __.prototype = b.prototype;
  18190. d.prototype = new __();
  18191. };
  18192. var BABYLON;
  18193. (function (BABYLON) {
  18194. var AnaglyphPostProcess = (function (_super) {
  18195. __extends(AnaglyphPostProcess, _super);
  18196. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18197. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  18198. }
  18199. return AnaglyphPostProcess;
  18200. })(BABYLON.PostProcess);
  18201. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  18202. })(BABYLON || (BABYLON = {}));
  18203. var BABYLON;
  18204. (function (BABYLON) {
  18205. var Tags = (function () {
  18206. function Tags() {
  18207. }
  18208. Tags.EnableFor = function (obj) {
  18209. obj._tags = obj._tags || {};
  18210. obj.hasTags = function () {
  18211. return Tags.HasTags(obj);
  18212. };
  18213. obj.addTags = function (tagsString) {
  18214. return Tags.AddTagsTo(obj, tagsString);
  18215. };
  18216. obj.removeTags = function (tagsString) {
  18217. return Tags.RemoveTagsFrom(obj, tagsString);
  18218. };
  18219. obj.matchesTagsQuery = function (tagsQuery) {
  18220. return Tags.MatchesQuery(obj, tagsQuery);
  18221. };
  18222. };
  18223. Tags.DisableFor = function (obj) {
  18224. delete obj._tags;
  18225. delete obj.hasTags;
  18226. delete obj.addTags;
  18227. delete obj.removeTags;
  18228. delete obj.matchesTagsQuery;
  18229. };
  18230. Tags.HasTags = function (obj) {
  18231. if (!obj._tags) {
  18232. return false;
  18233. }
  18234. return !BABYLON.Tools.IsEmpty(obj._tags);
  18235. };
  18236. Tags.GetTags = function (obj) {
  18237. if (!obj._tags) {
  18238. return null;
  18239. }
  18240. return obj._tags;
  18241. };
  18242. Tags.AddTagsTo = function (obj, tagsString) {
  18243. if (!tagsString) {
  18244. return;
  18245. }
  18246. var tags = tagsString.split(" ");
  18247. for (var t in tags) {
  18248. Tags._AddTagTo(obj, tags[t]);
  18249. }
  18250. };
  18251. Tags._AddTagTo = function (obj, tag) {
  18252. tag = tag.trim();
  18253. if (tag === "" || tag === "true" || tag === "false") {
  18254. return;
  18255. }
  18256. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  18257. return;
  18258. }
  18259. Tags.EnableFor(obj);
  18260. obj._tags[tag] = true;
  18261. };
  18262. Tags.RemoveTagsFrom = function (obj, tagsString) {
  18263. if (!Tags.HasTags(obj)) {
  18264. return;
  18265. }
  18266. var tags = tagsString.split(" ");
  18267. for (var t in tags) {
  18268. Tags._RemoveTagFrom(obj, tags[t]);
  18269. }
  18270. };
  18271. Tags._RemoveTagFrom = function (obj, tag) {
  18272. delete obj._tags[tag];
  18273. };
  18274. Tags.MatchesQuery = function (obj, tagsQuery) {
  18275. if (tagsQuery === undefined) {
  18276. return true;
  18277. }
  18278. if (tagsQuery === "") {
  18279. return Tags.HasTags(obj);
  18280. }
  18281. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18282. return Tags.HasTags(obj) && obj._tags[r];
  18283. });
  18284. };
  18285. return Tags;
  18286. })();
  18287. BABYLON.Tags = Tags;
  18288. })(BABYLON || (BABYLON = {}));
  18289. var BABYLON;
  18290. (function (BABYLON) {
  18291. (function (Internals) {
  18292. var AndOrNotEvaluator = (function () {
  18293. function AndOrNotEvaluator() {
  18294. }
  18295. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18296. if (!query.match(/\([^\(\)]*\)/g)) {
  18297. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18298. } else {
  18299. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18300. r = r.slice(1, r.length - 1);
  18301. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18302. });
  18303. }
  18304. if (query === "true") {
  18305. return true;
  18306. }
  18307. if (query === "false") {
  18308. return false;
  18309. }
  18310. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18311. };
  18312. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18313. evaluateCallback = evaluateCallback || (function (r) {
  18314. return r === "true" ? true : false;
  18315. });
  18316. var result;
  18317. var or = parenthesisContent.split("||");
  18318. for (var i in or) {
  18319. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18320. var and = ori.split("&&");
  18321. if (and.length > 1) {
  18322. for (var j = 0; j < and.length; ++j) {
  18323. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18324. if (andj !== "true" && andj !== "false") {
  18325. if (andj[0] === "!") {
  18326. result = !evaluateCallback(andj.substring(1));
  18327. } else {
  18328. result = evaluateCallback(andj);
  18329. }
  18330. } else {
  18331. result = andj === "true" ? true : false;
  18332. }
  18333. if (!result) {
  18334. ori = "false";
  18335. break;
  18336. }
  18337. }
  18338. }
  18339. if (result || ori === "true") {
  18340. result = true;
  18341. break;
  18342. }
  18343. if (ori !== "true" && ori !== "false") {
  18344. if (ori[0] === "!") {
  18345. result = !evaluateCallback(ori.substring(1));
  18346. } else {
  18347. result = evaluateCallback(ori);
  18348. }
  18349. } else {
  18350. result = ori === "true" ? true : false;
  18351. }
  18352. }
  18353. return result ? "true" : "false";
  18354. };
  18355. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  18356. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  18357. r = r.replace(/[\s]/g, function () {
  18358. return "";
  18359. });
  18360. return r.length % 2 ? "!" : "";
  18361. });
  18362. booleanString = booleanString.trim();
  18363. if (booleanString === "!true") {
  18364. booleanString = "false";
  18365. } else if (booleanString === "!false") {
  18366. booleanString = "true";
  18367. }
  18368. return booleanString;
  18369. };
  18370. return AndOrNotEvaluator;
  18371. })();
  18372. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  18373. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18374. var Internals = BABYLON.Internals;
  18375. })(BABYLON || (BABYLON = {}));
  18376. var BABYLON;
  18377. (function (BABYLON) {
  18378. var PostProcessRenderPass = (function () {
  18379. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  18380. this._enabled = true;
  18381. this._refCount = 0;
  18382. this._name = name;
  18383. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  18384. this.setRenderList(renderList);
  18385. this._renderTexture.onBeforeRender = beforeRender;
  18386. this._renderTexture.onAfterRender = afterRender;
  18387. this._scene = scene;
  18388. }
  18389. PostProcessRenderPass.prototype._incRefCount = function () {
  18390. if (this._refCount === 0) {
  18391. this._scene.customRenderTargets.push(this._renderTexture);
  18392. }
  18393. return ++this._refCount;
  18394. };
  18395. PostProcessRenderPass.prototype._decRefCount = function () {
  18396. this._refCount--;
  18397. if (this._refCount <= 0) {
  18398. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  18399. }
  18400. return this._refCount;
  18401. };
  18402. PostProcessRenderPass.prototype._update = function () {
  18403. this.setRenderList(this._renderList);
  18404. };
  18405. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  18406. this._renderTexture.renderList = renderList;
  18407. };
  18408. PostProcessRenderPass.prototype.getRenderTexture = function () {
  18409. return this._renderTexture;
  18410. };
  18411. return PostProcessRenderPass;
  18412. })();
  18413. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  18414. })(BABYLON || (BABYLON = {}));
  18415. var BABYLON;
  18416. (function (BABYLON) {
  18417. var PostProcessRenderEffect = (function () {
  18418. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  18419. this._engine = engine;
  18420. this._name = name;
  18421. this._singleInstance = singleInstance || true;
  18422. this._getPostProcess = getPostProcess;
  18423. this._cameras = [];
  18424. this._postProcesses = [];
  18425. this._indicesForCamera = [];
  18426. this._renderPasses = [];
  18427. this._renderEffectAsPasses = [];
  18428. }
  18429. PostProcessRenderEffect.prototype._update = function () {
  18430. for (var renderPassName in this._renderPasses) {
  18431. this._renderPasses[renderPassName]._update();
  18432. }
  18433. };
  18434. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  18435. this._renderPasses[renderPass._name] = renderPass;
  18436. this._linkParameters();
  18437. };
  18438. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  18439. delete this._renderPasses[renderPass._name];
  18440. this._linkParameters();
  18441. };
  18442. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  18443. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  18444. this._linkParameters();
  18445. };
  18446. PostProcessRenderEffect.prototype.getPass = function (passName) {
  18447. for (var renderPassName in this._renderPasses) {
  18448. if (renderPassName === passName) {
  18449. return this._renderPasses[passName];
  18450. }
  18451. }
  18452. };
  18453. PostProcessRenderEffect.prototype.emptyPasses = function () {
  18454. this._renderPasses.length = 0;
  18455. this._linkParameters();
  18456. };
  18457. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  18458. var cameraKey;
  18459. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18460. for (var i = 0; i < _cam.length; i++) {
  18461. var camera = _cam[i];
  18462. var cameraName = camera.name;
  18463. if (this._singleInstance) {
  18464. cameraKey = 0;
  18465. } else {
  18466. cameraKey = cameraName;
  18467. }
  18468. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18469. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18470. if (!this._indicesForCamera[cameraName]) {
  18471. this._indicesForCamera[cameraName] = [];
  18472. }
  18473. this._indicesForCamera[cameraName].push(index);
  18474. if (this._cameras.indexOf(camera) === -1) {
  18475. this._cameras[cameraName] = camera;
  18476. }
  18477. for (var passName in this._renderPasses) {
  18478. this._renderPasses[passName]._incRefCount();
  18479. }
  18480. }
  18481. this._linkParameters();
  18482. };
  18483. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18485. for (var i = 0; i < _cam.length; i++) {
  18486. var camera = _cam[i];
  18487. var cameraName = camera.name;
  18488. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18489. var index = this._cameras.indexOf(cameraName);
  18490. this._indicesForCamera.splice(index, 1);
  18491. this._cameras.splice(index, 1);
  18492. for (var passName in this._renderPasses) {
  18493. this._renderPasses[passName]._decRefCount();
  18494. }
  18495. }
  18496. };
  18497. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18498. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18499. for (var i = 0; i < _cam.length; i++) {
  18500. var camera = _cam[i];
  18501. var cameraName = camera.name;
  18502. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18503. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18504. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18505. }
  18506. }
  18507. for (var passName in this._renderPasses) {
  18508. this._renderPasses[passName]._incRefCount();
  18509. }
  18510. }
  18511. };
  18512. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18513. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18514. for (var i = 0; i < _cam.length; i++) {
  18515. var camera = _cam[i];
  18516. var cameraName = camera.Name;
  18517. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18518. for (var passName in this._renderPasses) {
  18519. this._renderPasses[passName]._decRefCount();
  18520. }
  18521. }
  18522. };
  18523. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18524. if (this._singleInstance) {
  18525. return this._postProcesses[0];
  18526. } else {
  18527. return this._postProcesses[camera.name];
  18528. }
  18529. };
  18530. PostProcessRenderEffect.prototype._linkParameters = function () {
  18531. var _this = this;
  18532. for (var index in this._postProcesses) {
  18533. if (this.applyParameters) {
  18534. this.applyParameters(this._postProcesses[index]);
  18535. }
  18536. this._postProcesses[index].onBeforeRender = function (effect) {
  18537. _this._linkTextures(effect);
  18538. };
  18539. }
  18540. };
  18541. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18542. for (var renderPassName in this._renderPasses) {
  18543. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18544. }
  18545. for (var renderEffectName in this._renderEffectAsPasses) {
  18546. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18547. }
  18548. };
  18549. return PostProcessRenderEffect;
  18550. })();
  18551. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18552. })(BABYLON || (BABYLON = {}));
  18553. var BABYLON;
  18554. (function (BABYLON) {
  18555. var PostProcessRenderPipeline = (function () {
  18556. function PostProcessRenderPipeline(engine, name) {
  18557. this._engine = engine;
  18558. this._name = name;
  18559. this._renderEffects = [];
  18560. this._renderEffectsForIsolatedPass = [];
  18561. this._cameras = [];
  18562. }
  18563. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18564. this._renderEffects[renderEffect._name] = renderEffect;
  18565. };
  18566. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18567. var renderEffects = this._renderEffects[renderEffectName];
  18568. if (!renderEffects) {
  18569. return;
  18570. }
  18571. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18572. };
  18573. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18574. var renderEffects = this._renderEffects[renderEffectName];
  18575. if (!renderEffects) {
  18576. return;
  18577. }
  18578. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18579. };
  18580. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18581. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18582. var indicesToDelete = [];
  18583. for (var i = 0; i < _cam.length; i++) {
  18584. var camera = _cam[i];
  18585. var cameraName = camera.name;
  18586. if (this._cameras.indexOf(camera) === -1) {
  18587. this._cameras[cameraName] = camera;
  18588. } else if (unique) {
  18589. indicesToDelete.push(i);
  18590. }
  18591. }
  18592. for (var i = 0; i < indicesToDelete.length; i++) {
  18593. cameras.splice(indicesToDelete[i], 1);
  18594. }
  18595. for (var renderEffectName in this._renderEffects) {
  18596. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18597. }
  18598. };
  18599. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18600. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18601. for (var renderEffectName in this._renderEffects) {
  18602. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18603. }
  18604. for (var i = 0; i < _cam.length; i++) {
  18605. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18606. }
  18607. };
  18608. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18609. var _this = this;
  18610. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18611. var pass = null;
  18612. for (var renderEffectName in this._renderEffects) {
  18613. pass = this._renderEffects[renderEffectName].getPass(passName);
  18614. if (pass != null) {
  18615. break;
  18616. }
  18617. }
  18618. if (pass === null) {
  18619. return;
  18620. }
  18621. for (var renderEffectName in this._renderEffects) {
  18622. this._renderEffects[renderEffectName]._disable(_cam);
  18623. }
  18624. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18625. for (var i = 0; i < _cam.length; i++) {
  18626. var camera = _cam[i];
  18627. var cameraName = camera.name;
  18628. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18629. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18630. });
  18631. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18632. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18633. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18634. }
  18635. };
  18636. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18637. var _this = this;
  18638. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18639. for (var i = 0; i < _cam.length; i++) {
  18640. var camera = _cam[i];
  18641. var cameraName = camera.name;
  18642. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18643. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18644. });
  18645. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18646. }
  18647. for (var renderEffectName in this._renderEffects) {
  18648. this._renderEffects[renderEffectName]._enable(_cam);
  18649. }
  18650. };
  18651. PostProcessRenderPipeline.prototype._update = function () {
  18652. for (var renderEffectName in this._renderEffects) {
  18653. this._renderEffects[renderEffectName]._update();
  18654. }
  18655. for (var i = 0; i < this._cameras.length; i++) {
  18656. var cameraName = this._cameras[i].name;
  18657. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18658. this._renderEffectsForIsolatedPass[cameraName]._update();
  18659. }
  18660. }
  18661. };
  18662. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18663. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18664. return PostProcessRenderPipeline;
  18665. })();
  18666. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18667. })(BABYLON || (BABYLON = {}));
  18668. var BABYLON;
  18669. (function (BABYLON) {
  18670. var PostProcessRenderPipelineManager = (function () {
  18671. function PostProcessRenderPipelineManager() {
  18672. this._renderPipelines = new Array();
  18673. }
  18674. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18675. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18676. };
  18677. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18678. var renderPipeline = this._renderPipelines[renderPipelineName];
  18679. if (!renderPipeline) {
  18680. return;
  18681. }
  18682. renderPipeline._attachCameras(cameras, unique);
  18683. };
  18684. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18685. var renderPipeline = this._renderPipelines[renderPipelineName];
  18686. if (!renderPipeline) {
  18687. return;
  18688. }
  18689. renderPipeline._detachCameras(cameras);
  18690. };
  18691. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18692. var renderPipeline = this._renderPipelines[renderPipelineName];
  18693. if (!renderPipeline) {
  18694. return;
  18695. }
  18696. renderPipeline._enableEffect(renderEffectName, cameras);
  18697. };
  18698. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18699. var renderPipeline = this._renderPipelines[renderPipelineName];
  18700. if (!renderPipeline) {
  18701. return;
  18702. }
  18703. renderPipeline._disableEffect(renderEffectName, cameras);
  18704. };
  18705. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18706. var renderPipeline = this._renderPipelines[renderPipelineName];
  18707. if (!renderPipeline) {
  18708. return;
  18709. }
  18710. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18711. };
  18712. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18713. var renderPipeline = this._renderPipelines[renderPipelineName];
  18714. if (!renderPipeline) {
  18715. return;
  18716. }
  18717. renderPipeline._disableDisplayOnlyPass(cameras);
  18718. };
  18719. PostProcessRenderPipelineManager.prototype.update = function () {
  18720. for (var renderPipelineName in this._renderPipelines) {
  18721. this._renderPipelines[renderPipelineName]._update();
  18722. }
  18723. };
  18724. return PostProcessRenderPipelineManager;
  18725. })();
  18726. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18727. })(BABYLON || (BABYLON = {}));
  18728. var __extends = this.__extends || function (d, b) {
  18729. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18730. function __() { this.constructor = d; }
  18731. __.prototype = b.prototype;
  18732. d.prototype = new __();
  18733. };
  18734. var BABYLON;
  18735. (function (BABYLON) {
  18736. var DisplayPassPostProcess = (function (_super) {
  18737. __extends(DisplayPassPostProcess, _super);
  18738. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18739. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  18740. }
  18741. return DisplayPassPostProcess;
  18742. })(BABYLON.PostProcess);
  18743. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  18744. })(BABYLON || (BABYLON = {}));
  18745. var BABYLON;
  18746. (function (BABYLON) {
  18747. var BoundingBoxRenderer = (function () {
  18748. function BoundingBoxRenderer(scene) {
  18749. this.frontColor = new BABYLON.Color3(1, 1, 1);
  18750. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  18751. this.showBackLines = true;
  18752. this.renderList = new BABYLON.SmartArray(32);
  18753. this._scene = scene;
  18754. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  18755. attributes: ["position"],
  18756. uniforms: ["worldViewProjection", "color"]
  18757. });
  18758. var engine = this._scene.getEngine();
  18759. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  18760. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  18761. 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]);
  18762. }
  18763. BoundingBoxRenderer.prototype.reset = function () {
  18764. this.renderList.reset();
  18765. };
  18766. BoundingBoxRenderer.prototype.render = function () {
  18767. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  18768. return;
  18769. }
  18770. var engine = this._scene.getEngine();
  18771. engine.setDepthWrite(false);
  18772. this._colorShader._preBind();
  18773. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  18774. var boundingBox = this.renderList.data[boundingBoxIndex];
  18775. var min = boundingBox.minimum;
  18776. var max = boundingBox.maximum;
  18777. var diff = max.subtract(min);
  18778. var median = min.add(diff.scale(0.5));
  18779. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  18780. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  18781. if (this.showBackLines) {
  18782. engine.setDepthFunctionToGreaterOrEqual();
  18783. this._colorShader.setColor4("color", this.backColor.toColor4());
  18784. this._colorShader.bind(worldMatrix);
  18785. engine.draw(false, 0, 24);
  18786. }
  18787. engine.setDepthFunctionToLess();
  18788. this._colorShader.setColor4("color", this.frontColor.toColor4());
  18789. this._colorShader.bind(worldMatrix);
  18790. engine.draw(false, 0, 24);
  18791. }
  18792. this._colorShader.unbind();
  18793. engine.setDepthFunctionToLessOrEqual();
  18794. engine.setDepthWrite(true);
  18795. };
  18796. BoundingBoxRenderer.prototype.dispose = function () {
  18797. this._colorShader.dispose();
  18798. this._vb.dispose();
  18799. this._scene.getEngine()._releaseBuffer(this._ib);
  18800. };
  18801. return BoundingBoxRenderer;
  18802. })();
  18803. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  18804. })(BABYLON || (BABYLON = {}));
  18805. /**
  18806. * Based on jsTGALoader - Javascript loader for TGA file
  18807. * By Vincent Thibault
  18808. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  18809. */
  18810. var BABYLON;
  18811. (function (BABYLON) {
  18812. (function (Internals) {
  18813. var TGATools = (function () {
  18814. function TGATools() {
  18815. }
  18816. TGATools.GetTGAHeader = function (data) {
  18817. var offset = 0;
  18818. var header = {
  18819. id_length: data[offset++],
  18820. colormap_type: data[offset++],
  18821. image_type: data[offset++],
  18822. colormap_index: data[offset++] | data[offset++] << 8,
  18823. colormap_length: data[offset++] | data[offset++] << 8,
  18824. colormap_size: data[offset++],
  18825. origin: [
  18826. data[offset++] | data[offset++] << 8,
  18827. data[offset++] | data[offset++] << 8
  18828. ],
  18829. width: data[offset++] | data[offset++] << 8,
  18830. height: data[offset++] | data[offset++] << 8,
  18831. pixel_size: data[offset++],
  18832. flags: data[offset++]
  18833. };
  18834. return header;
  18835. };
  18836. TGATools.UploadContent = function (gl, data) {
  18837. if (data.length < 19) {
  18838. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  18839. return;
  18840. }
  18841. var offset = 18;
  18842. var header = TGATools.GetTGAHeader(data);
  18843. if (header.id_length + offset > data.length) {
  18844. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  18845. return;
  18846. }
  18847. offset += header.id_length;
  18848. var use_rle = false;
  18849. var use_pal = false;
  18850. var use_rgb = false;
  18851. var use_grey = false;
  18852. switch (header.image_type) {
  18853. case TGATools._TYPE_RLE_INDEXED:
  18854. use_rle = true;
  18855. case TGATools._TYPE_INDEXED:
  18856. use_pal = true;
  18857. break;
  18858. case TGATools._TYPE_RLE_RGB:
  18859. use_rle = true;
  18860. case TGATools._TYPE_RGB:
  18861. use_rgb = true;
  18862. break;
  18863. case TGATools._TYPE_RLE_GREY:
  18864. use_rle = true;
  18865. case TGATools._TYPE_GREY:
  18866. use_grey = true;
  18867. break;
  18868. }
  18869. var pixel_data;
  18870. var numAlphaBits = header.flags & 0xf;
  18871. var pixel_size = header.pixel_size >> 3;
  18872. var pixel_total = header.width * header.height * pixel_size;
  18873. var palettes;
  18874. if (use_pal) {
  18875. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  18876. }
  18877. if (use_rle) {
  18878. pixel_data = new Uint8Array(pixel_total);
  18879. var c, count, i;
  18880. var localOffset = 0;
  18881. var pixels = new Uint8Array(pixel_size);
  18882. while (offset < pixel_total && localOffset < pixel_total) {
  18883. c = data[offset++];
  18884. count = (c & 0x7f) + 1;
  18885. if (c & 0x80) {
  18886. for (i = 0; i < pixel_size; ++i) {
  18887. pixels[i] = data[offset++];
  18888. }
  18889. for (i = 0; i < count; ++i) {
  18890. pixel_data.set(pixels, localOffset + i * pixel_size);
  18891. }
  18892. localOffset += pixel_size * count;
  18893. } else {
  18894. count *= pixel_size;
  18895. for (i = 0; i < count; ++i) {
  18896. pixel_data[localOffset + i] = data[offset++];
  18897. }
  18898. localOffset += count;
  18899. }
  18900. }
  18901. } else {
  18902. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  18903. }
  18904. var x_start, y_start, x_step, y_step, y_end, x_end;
  18905. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  18906. default:
  18907. case TGATools._ORIGIN_UL:
  18908. x_start = 0;
  18909. x_step = 1;
  18910. x_end = header.width;
  18911. y_start = 0;
  18912. y_step = 1;
  18913. y_end = header.height;
  18914. break;
  18915. case TGATools._ORIGIN_BL:
  18916. x_start = 0;
  18917. x_step = 1;
  18918. x_end = header.width;
  18919. y_start = header.height - 1;
  18920. y_step = -1;
  18921. y_end = -1;
  18922. break;
  18923. case TGATools._ORIGIN_UR:
  18924. x_start = header.width - 1;
  18925. x_step = -1;
  18926. x_end = -1;
  18927. y_start = 0;
  18928. y_step = 1;
  18929. y_end = header.height;
  18930. break;
  18931. case TGATools._ORIGIN_BR:
  18932. x_start = header.width - 1;
  18933. x_step = -1;
  18934. x_end = -1;
  18935. y_start = header.height - 1;
  18936. y_step = -1;
  18937. y_end = -1;
  18938. break;
  18939. }
  18940. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  18941. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  18942. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  18943. };
  18944. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18945. var image = pixel_data, colormap = palettes;
  18946. var width = header.width, height = header.height;
  18947. var color, i = 0, x, y;
  18948. var imageData = new Uint8Array(width * height * 4);
  18949. for (y = y_start; y !== y_end; y += y_step) {
  18950. for (x = x_start; x !== x_end; x += x_step, i++) {
  18951. color = image[i];
  18952. imageData[(x + width * y) * 4 + 3] = 255;
  18953. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  18954. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  18955. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  18956. }
  18957. }
  18958. return imageData;
  18959. };
  18960. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18961. var image = pixel_data;
  18962. var width = header.width, height = header.height;
  18963. var color, i = 0, x, y;
  18964. var imageData = new Uint8Array(width * height * 4);
  18965. for (y = y_start; y !== y_end; y += y_step) {
  18966. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  18967. color = image[i + 0] + (image[i + 1] << 8);
  18968. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  18969. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  18970. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  18971. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  18972. }
  18973. }
  18974. return imageData;
  18975. };
  18976. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18977. var image = pixel_data;
  18978. var width = header.width, height = header.height;
  18979. var i = 0, x, y;
  18980. var imageData = new Uint8Array(width * height * 4);
  18981. for (y = y_start; y !== y_end; y += y_step) {
  18982. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  18983. imageData[(x + width * y) * 4 + 3] = 255;
  18984. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18985. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  18986. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  18987. }
  18988. }
  18989. return imageData;
  18990. };
  18991. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  18992. var image = pixel_data;
  18993. var width = header.width, height = header.height;
  18994. var i = 0, x, y;
  18995. var imageData = new Uint8Array(width * height * 4);
  18996. for (y = y_start; y !== y_end; y += y_step) {
  18997. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  18998. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  18999. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19000. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19001. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  19002. }
  19003. }
  19004. return imageData;
  19005. };
  19006. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19007. var image = pixel_data;
  19008. var width = header.width, height = header.height;
  19009. var color, i = 0, x, y;
  19010. var imageData = new Uint8Array(width * height * 4);
  19011. for (y = y_start; y !== y_end; y += y_step) {
  19012. for (x = x_start; x !== x_end; x += x_step, i++) {
  19013. color = image[i];
  19014. imageData[(x + width * y) * 4 + 0] = color;
  19015. imageData[(x + width * y) * 4 + 1] = color;
  19016. imageData[(x + width * y) * 4 + 2] = color;
  19017. imageData[(x + width * y) * 4 + 3] = 255;
  19018. }
  19019. }
  19020. return imageData;
  19021. };
  19022. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19023. var image = pixel_data;
  19024. var width = header.width, height = header.height;
  19025. var i = 0, x, y;
  19026. var imageData = new Uint8Array(width * height * 4);
  19027. for (y = y_start; y !== y_end; y += y_step) {
  19028. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19029. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  19030. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  19031. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19032. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  19033. }
  19034. }
  19035. return imageData;
  19036. };
  19037. TGATools._TYPE_NO_DATA = 0;
  19038. TGATools._TYPE_INDEXED = 1;
  19039. TGATools._TYPE_RGB = 2;
  19040. TGATools._TYPE_GREY = 3;
  19041. TGATools._TYPE_RLE_INDEXED = 9;
  19042. TGATools._TYPE_RLE_RGB = 10;
  19043. TGATools._TYPE_RLE_GREY = 11;
  19044. TGATools._ORIGIN_MASK = 0x30;
  19045. TGATools._ORIGIN_SHIFT = 0x04;
  19046. TGATools._ORIGIN_BL = 0x00;
  19047. TGATools._ORIGIN_BR = 0x01;
  19048. TGATools._ORIGIN_UL = 0x02;
  19049. TGATools._ORIGIN_UR = 0x03;
  19050. return TGATools;
  19051. })();
  19052. Internals.TGATools = TGATools;
  19053. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19054. var Internals = BABYLON.Internals;
  19055. })(BABYLON || (BABYLON = {}));
  19056. var BABYLON;
  19057. (function (BABYLON) {
  19058. (function (Internals) {
  19059. var DDS_MAGIC = 0x20534444;
  19060. 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;
  19061. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  19062. 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;
  19063. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  19064. function FourCCToInt32(value) {
  19065. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  19066. }
  19067. function Int32ToFourCC(value) {
  19068. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  19069. }
  19070. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  19071. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  19072. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  19073. var headerLengthInt = 31;
  19074. var off_magic = 0;
  19075. var off_size = 1;
  19076. var off_flags = 2;
  19077. var off_height = 3;
  19078. var off_width = 4;
  19079. var off_mipmapCount = 7;
  19080. var off_pfFlags = 20;
  19081. var off_pfFourCC = 21;
  19082. var off_RGBbpp = 22;
  19083. var off_RMask = 23;
  19084. var off_GMask = 24;
  19085. var off_BMask = 25;
  19086. var off_AMask = 26;
  19087. var off_caps1 = 27;
  19088. var off_caps2 = 28;
  19089. ;
  19090. var DDSTools = (function () {
  19091. function DDSTools() {
  19092. }
  19093. DDSTools.GetDDSInfo = function (arrayBuffer) {
  19094. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  19095. var mipmapCount = 1;
  19096. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  19097. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19098. }
  19099. return {
  19100. width: header[off_width],
  19101. height: header[off_height],
  19102. mipmapCount: mipmapCount,
  19103. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  19104. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  19105. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  19106. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  19107. };
  19108. };
  19109. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19110. var byteArray = new Uint8Array(dataLength);
  19111. var srcData = new Uint8Array(arrayBuffer);
  19112. var index = 0;
  19113. for (var y = height - 1; y >= 0; y--) {
  19114. for (var x = 0; x < width; x++) {
  19115. var srcPos = dataOffset + (x + y * width) * 4;
  19116. byteArray[index + 2] = srcData[srcPos];
  19117. byteArray[index + 1] = srcData[srcPos + 1];
  19118. byteArray[index] = srcData[srcPos + 2];
  19119. byteArray[index + 3] = srcData[srcPos + 3];
  19120. index += 4;
  19121. }
  19122. }
  19123. return byteArray;
  19124. };
  19125. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19126. var byteArray = new Uint8Array(dataLength);
  19127. var srcData = new Uint8Array(arrayBuffer);
  19128. var index = 0;
  19129. for (var y = height - 1; y >= 0; y--) {
  19130. for (var x = 0; x < width; x++) {
  19131. var srcPos = dataOffset + (x + y * width) * 3;
  19132. byteArray[index + 2] = srcData[srcPos];
  19133. byteArray[index + 1] = srcData[srcPos + 1];
  19134. byteArray[index] = srcData[srcPos + 2];
  19135. index += 3;
  19136. }
  19137. }
  19138. return byteArray;
  19139. };
  19140. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19141. var byteArray = new Uint8Array(dataLength);
  19142. var srcData = new Uint8Array(arrayBuffer);
  19143. var index = 0;
  19144. for (var y = height - 1; y >= 0; y--) {
  19145. for (var x = 0; x < width; x++) {
  19146. var srcPos = dataOffset + (x + y * width);
  19147. byteArray[index] = srcData[srcPos];
  19148. index++;
  19149. }
  19150. }
  19151. return byteArray;
  19152. };
  19153. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  19154. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  19155. if (header[off_magic] != DDS_MAGIC) {
  19156. BABYLON.Tools.Error("Invalid magic number in DDS header");
  19157. return;
  19158. }
  19159. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  19160. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  19161. return;
  19162. }
  19163. if (info.isFourCC) {
  19164. fourCC = header[off_pfFourCC];
  19165. switch (fourCC) {
  19166. case FOURCC_DXT1:
  19167. blockBytes = 8;
  19168. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19169. break;
  19170. case FOURCC_DXT3:
  19171. blockBytes = 16;
  19172. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19173. break;
  19174. case FOURCC_DXT5:
  19175. blockBytes = 16;
  19176. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19177. break;
  19178. default:
  19179. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  19180. return;
  19181. }
  19182. }
  19183. mipmapCount = 1;
  19184. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  19185. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19186. }
  19187. var bpp = header[off_RGBbpp];
  19188. for (var face = 0; face < faces; face++) {
  19189. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  19190. width = header[off_width];
  19191. height = header[off_height];
  19192. dataOffset = header[off_size] + 4;
  19193. for (i = 0; i < mipmapCount; ++i) {
  19194. if (info.isRGB) {
  19195. if (bpp == 24) {
  19196. dataLength = width * height * 3;
  19197. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19198. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  19199. } else {
  19200. dataLength = width * height * 4;
  19201. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19202. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  19203. }
  19204. } else if (info.isLuminance) {
  19205. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  19206. var unpaddedRowSize = width;
  19207. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  19208. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  19209. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19210. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  19211. } else {
  19212. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  19213. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  19214. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  19215. }
  19216. dataOffset += dataLength;
  19217. width *= 0.5;
  19218. height *= 0.5;
  19219. width = Math.max(1.0, width);
  19220. height = Math.max(1.0, height);
  19221. }
  19222. }
  19223. };
  19224. return DDSTools;
  19225. })();
  19226. Internals.DDSTools = DDSTools;
  19227. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19228. var Internals = BABYLON.Internals;
  19229. })(BABYLON || (BABYLON = {}));
  19230. var BABYLON;
  19231. (function (BABYLON) {
  19232. var SmartArray = (function () {
  19233. function SmartArray(capacity) {
  19234. this.length = 0;
  19235. this._duplicateId = 0;
  19236. this.data = new Array(capacity);
  19237. this._id = SmartArray._GlobalId++;
  19238. }
  19239. SmartArray.prototype.push = function (value) {
  19240. this.data[this.length++] = value;
  19241. if (this.length > this.data.length) {
  19242. this.data.length *= 2;
  19243. }
  19244. if (!value.__smartArrayFlags) {
  19245. value.__smartArrayFlags = {};
  19246. }
  19247. value.__smartArrayFlags[this._id] = this._duplicateId;
  19248. };
  19249. SmartArray.prototype.pushNoDuplicate = function (value) {
  19250. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  19251. return;
  19252. }
  19253. this.push(value);
  19254. };
  19255. SmartArray.prototype.sort = function (compareFn) {
  19256. this.data.sort(compareFn);
  19257. };
  19258. SmartArray.prototype.reset = function () {
  19259. this.length = 0;
  19260. this._duplicateId++;
  19261. };
  19262. SmartArray.prototype.concat = function (array) {
  19263. if (array.length === 0) {
  19264. return;
  19265. }
  19266. if (this.length + array.length > this.data.length) {
  19267. this.data.length = (this.length + array.length) * 2;
  19268. }
  19269. for (var index = 0; index < array.length; index++) {
  19270. this.data[this.length++] = (array.data || array)[index];
  19271. }
  19272. };
  19273. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  19274. if (array.length === 0) {
  19275. return;
  19276. }
  19277. if (this.length + array.length > this.data.length) {
  19278. this.data.length = (this.length + array.length) * 2;
  19279. }
  19280. for (var index = 0; index < array.length; index++) {
  19281. var item = (array.data || array)[index];
  19282. this.pushNoDuplicate(item);
  19283. }
  19284. };
  19285. SmartArray.prototype.indexOf = function (value) {
  19286. var position = this.data.indexOf(value);
  19287. if (position >= this.length) {
  19288. return -1;
  19289. }
  19290. return position;
  19291. };
  19292. SmartArray._GlobalId = 0;
  19293. return SmartArray;
  19294. })();
  19295. BABYLON.SmartArray = SmartArray;
  19296. })(BABYLON || (BABYLON = {}));
  19297. var BABYLON;
  19298. (function (BABYLON) {
  19299. var CannonJSPlugin = (function () {
  19300. function CannonJSPlugin() {
  19301. this._registeredMeshes = [];
  19302. this._physicsMaterials = [];
  19303. this.updateBodyPosition = function (mesh) {
  19304. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19305. var registeredMesh = this._registeredMeshes[index];
  19306. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  19307. var body = registeredMesh.body;
  19308. var center = mesh.getBoundingInfo().boundingBox.center;
  19309. body.position.set(center.x, center.z, center.y);
  19310. body.quaternion.x = mesh.rotationQuaternion.x;
  19311. body.quaternion.z = mesh.rotationQuaternion.y;
  19312. body.quaternion.y = mesh.rotationQuaternion.z;
  19313. body.quaternion.w = -mesh.rotationQuaternion.w;
  19314. return;
  19315. }
  19316. }
  19317. };
  19318. }
  19319. CannonJSPlugin.prototype.initialize = function (iterations) {
  19320. if (typeof iterations === "undefined") { iterations = 10; }
  19321. this._world = new CANNON.World();
  19322. this._world.broadphase = new CANNON.NaiveBroadphase();
  19323. this._world.solver.iterations = iterations;
  19324. };
  19325. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  19326. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  19327. };
  19328. CannonJSPlugin.prototype.runOneStep = function (delta) {
  19329. this._world.step(delta);
  19330. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19331. var registeredMesh = this._registeredMeshes[index];
  19332. if (registeredMesh.isChild) {
  19333. continue;
  19334. }
  19335. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  19336. var deltaPos = registeredMesh.delta;
  19337. if (deltaPos) {
  19338. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  19339. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  19340. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  19341. } else {
  19342. registeredMesh.mesh.position.x = bodyX;
  19343. registeredMesh.mesh.position.y = bodyZ;
  19344. registeredMesh.mesh.position.z = bodyY;
  19345. }
  19346. if (!registeredMesh.mesh.rotationQuaternion) {
  19347. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19348. }
  19349. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  19350. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  19351. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  19352. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  19353. }
  19354. };
  19355. CannonJSPlugin.prototype.setGravity = function (gravity) {
  19356. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  19357. };
  19358. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  19359. this.unregisterMesh(mesh);
  19360. mesh.computeWorldMatrix(true);
  19361. switch (impostor) {
  19362. case BABYLON.PhysicsEngine.SphereImpostor:
  19363. var bbox = mesh.getBoundingInfo().boundingBox;
  19364. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  19365. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  19366. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  19367. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  19368. case BABYLON.PhysicsEngine.BoxImpostor:
  19369. bbox = mesh.getBoundingInfo().boundingBox;
  19370. var min = bbox.minimumWorld;
  19371. var max = bbox.maximumWorld;
  19372. var box = max.subtract(min).scale(0.5);
  19373. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  19374. case BABYLON.PhysicsEngine.PlaneImpostor:
  19375. return this._createPlane(mesh, options);
  19376. case BABYLON.PhysicsEngine.MeshImpostor:
  19377. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19378. var rawFaces = mesh.getIndices();
  19379. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  19380. }
  19381. return null;
  19382. };
  19383. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  19384. var shape = new CANNON.Sphere(radius);
  19385. if (!options) {
  19386. return shape;
  19387. }
  19388. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19389. };
  19390. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  19391. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  19392. if (!options) {
  19393. return shape;
  19394. }
  19395. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19396. };
  19397. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  19398. var shape = new CANNON.Plane();
  19399. if (!options) {
  19400. return shape;
  19401. }
  19402. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19403. };
  19404. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  19405. var verts = [], faces = [];
  19406. mesh.computeWorldMatrix(true);
  19407. for (var i = 0; i < rawVerts.length; i += 3) {
  19408. var transformed = BABYLON.Vector3.Zero();
  19409. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  19410. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  19411. }
  19412. for (var j = 0; j < rawFaces.length; j += 3) {
  19413. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  19414. }
  19415. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  19416. if (!options) {
  19417. return shape;
  19418. }
  19419. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19420. };
  19421. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  19422. var index;
  19423. var mat;
  19424. for (index = 0; index < this._physicsMaterials.length; index++) {
  19425. mat = this._physicsMaterials[index];
  19426. if (mat.friction === friction && mat.restitution === restitution) {
  19427. return mat;
  19428. }
  19429. }
  19430. var currentMat = new CANNON.Material();
  19431. currentMat.friction = friction;
  19432. currentMat.restitution = restitution;
  19433. this._physicsMaterials.push(currentMat);
  19434. for (index = 0; index < this._physicsMaterials.length; index++) {
  19435. mat = this._physicsMaterials[index];
  19436. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  19437. contactMaterial.contactEquationStiffness = 1e10;
  19438. contactMaterial.contactEquationRegularizationTime = 10;
  19439. this._world.addContactMaterial(contactMaterial);
  19440. }
  19441. return currentMat;
  19442. };
  19443. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  19444. var initialRotation = null;
  19445. if (mesh.rotationQuaternion) {
  19446. initialRotation = mesh.rotationQuaternion.clone();
  19447. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19448. }
  19449. var bbox = mesh.getBoundingInfo().boundingBox;
  19450. var deltaPosition = mesh.position.subtract(bbox.center);
  19451. var material = this._addMaterial(friction, restitution);
  19452. var body = new CANNON.RigidBody(mass, shape, material);
  19453. if (initialRotation) {
  19454. body.quaternion.x = initialRotation.x;
  19455. body.quaternion.z = initialRotation.y;
  19456. body.quaternion.y = initialRotation.z;
  19457. body.quaternion.w = -initialRotation.w;
  19458. }
  19459. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  19460. this._world.add(body);
  19461. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  19462. return body;
  19463. };
  19464. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  19465. var compoundShape = new CANNON.Compound();
  19466. for (var index = 0; index < parts.length; index++) {
  19467. var mesh = parts[index].mesh;
  19468. var shape = this.registerMesh(mesh, parts[index].impostor);
  19469. if (index == 0) {
  19470. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  19471. } else {
  19472. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  19473. }
  19474. }
  19475. var initialMesh = parts[0].mesh;
  19476. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19477. body.parts = parts;
  19478. return body;
  19479. };
  19480. CannonJSPlugin.prototype._unbindBody = function (body) {
  19481. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19482. var registeredMesh = this._registeredMeshes[index];
  19483. if (registeredMesh.body === body) {
  19484. registeredMesh.body = null;
  19485. registeredMesh.delta = 0;
  19486. }
  19487. }
  19488. };
  19489. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19490. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19491. var registeredMesh = this._registeredMeshes[index];
  19492. if (registeredMesh.mesh === mesh) {
  19493. if (registeredMesh.body) {
  19494. this._world.remove(registeredMesh.body);
  19495. this._unbindBody(registeredMesh.body);
  19496. }
  19497. this._registeredMeshes.splice(index, 1);
  19498. return;
  19499. }
  19500. }
  19501. };
  19502. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19503. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19504. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19505. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19506. var registeredMesh = this._registeredMeshes[index];
  19507. if (registeredMesh.mesh === mesh) {
  19508. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19509. return;
  19510. }
  19511. }
  19512. };
  19513. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19514. var body1 = null, body2 = null;
  19515. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19516. var registeredMesh = this._registeredMeshes[index];
  19517. if (registeredMesh.mesh === mesh1) {
  19518. body1 = registeredMesh.body;
  19519. } else if (registeredMesh.mesh === mesh2) {
  19520. body2 = registeredMesh.body;
  19521. }
  19522. }
  19523. if (!body1 || !body2) {
  19524. return false;
  19525. }
  19526. 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));
  19527. this._world.addConstraint(constraint);
  19528. return true;
  19529. };
  19530. CannonJSPlugin.prototype.dispose = function () {
  19531. while (this._registeredMeshes.length) {
  19532. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19533. }
  19534. };
  19535. CannonJSPlugin.prototype.isSupported = function () {
  19536. return window.CANNON !== undefined;
  19537. };
  19538. return CannonJSPlugin;
  19539. })();
  19540. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19541. })(BABYLON || (BABYLON = {}));
  19542. var __extends = this.__extends || function (d, b) {
  19543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19544. function __() { this.constructor = d; }
  19545. __.prototype = b.prototype;
  19546. d.prototype = new __();
  19547. };
  19548. var BABYLON;
  19549. (function (BABYLON) {
  19550. var Condition = (function () {
  19551. function Condition(actionManager) {
  19552. this._actionManager = actionManager;
  19553. }
  19554. Condition.prototype.isValid = function () {
  19555. return true;
  19556. };
  19557. Condition.prototype._getProperty = function (propertyPath) {
  19558. return this._actionManager._getProperty(propertyPath);
  19559. };
  19560. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19561. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19562. };
  19563. return Condition;
  19564. })();
  19565. BABYLON.Condition = Condition;
  19566. var ValueCondition = (function (_super) {
  19567. __extends(ValueCondition, _super);
  19568. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19569. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19570. _super.call(this, actionManager);
  19571. this.propertyPath = propertyPath;
  19572. this.value = value;
  19573. this.operator = operator;
  19574. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19575. this._property = this._getProperty(this.propertyPath);
  19576. }
  19577. Object.defineProperty(ValueCondition, "IsEqual", {
  19578. get: function () {
  19579. return ValueCondition._IsEqual;
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(ValueCondition, "IsDifferent", {
  19585. get: function () {
  19586. return ValueCondition._IsDifferent;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Object.defineProperty(ValueCondition, "IsGreater", {
  19592. get: function () {
  19593. return ValueCondition._IsGreater;
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(ValueCondition, "IsLesser", {
  19599. get: function () {
  19600. return ValueCondition._IsLesser;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. ValueCondition.prototype.isValid = function () {
  19606. switch (this.operator) {
  19607. case ValueCondition.IsGreater:
  19608. return this._target[this._property] > this.value;
  19609. case ValueCondition.IsLesser:
  19610. return this._target[this._property] < this.value;
  19611. case ValueCondition.IsEqual:
  19612. case ValueCondition.IsDifferent:
  19613. var check;
  19614. if (this.value.equals) {
  19615. check = this.value.equals(this._target[this._property]);
  19616. } else {
  19617. check = this.value === this._target[this._property];
  19618. }
  19619. return this.operator === ValueCondition.IsEqual ? check : !check;
  19620. }
  19621. return false;
  19622. };
  19623. ValueCondition._IsEqual = 0;
  19624. ValueCondition._IsDifferent = 1;
  19625. ValueCondition._IsGreater = 2;
  19626. ValueCondition._IsLesser = 3;
  19627. return ValueCondition;
  19628. })(Condition);
  19629. BABYLON.ValueCondition = ValueCondition;
  19630. var PredicateCondition = (function (_super) {
  19631. __extends(PredicateCondition, _super);
  19632. function PredicateCondition(actionManager, predicate) {
  19633. _super.call(this, actionManager);
  19634. this.predicate = predicate;
  19635. }
  19636. PredicateCondition.prototype.isValid = function () {
  19637. return this.predicate();
  19638. };
  19639. return PredicateCondition;
  19640. })(Condition);
  19641. BABYLON.PredicateCondition = PredicateCondition;
  19642. var StateCondition = (function (_super) {
  19643. __extends(StateCondition, _super);
  19644. function StateCondition(actionManager, target, value) {
  19645. _super.call(this, actionManager);
  19646. this.value = value;
  19647. this._target = target;
  19648. }
  19649. StateCondition.prototype.isValid = function () {
  19650. return this._target.state === this.value;
  19651. };
  19652. return StateCondition;
  19653. })(Condition);
  19654. BABYLON.StateCondition = StateCondition;
  19655. })(BABYLON || (BABYLON = {}));
  19656. var BABYLON;
  19657. (function (BABYLON) {
  19658. var Action = (function () {
  19659. function Action(triggerOptions, condition) {
  19660. this.triggerOptions = triggerOptions;
  19661. if (triggerOptions.parameter) {
  19662. this.trigger = triggerOptions.trigger;
  19663. this._triggerParameter = triggerOptions.parameter;
  19664. } else {
  19665. this.trigger = triggerOptions;
  19666. }
  19667. this._nextActiveAction = this;
  19668. this._condition = condition;
  19669. }
  19670. Action.prototype._prepare = function () {
  19671. };
  19672. Action.prototype.getTriggerParameter = function () {
  19673. return this._triggerParameter;
  19674. };
  19675. Action.prototype._executeCurrent = function (evt) {
  19676. if (this._condition) {
  19677. var currentRenderId = this._actionManager.getScene().getRenderId();
  19678. if (this._condition._evaluationId === currentRenderId) {
  19679. if (!this._condition._currentResult) {
  19680. return;
  19681. }
  19682. } else {
  19683. this._condition._evaluationId = currentRenderId;
  19684. if (!this._condition.isValid()) {
  19685. this._condition._currentResult = false;
  19686. return;
  19687. }
  19688. this._condition._currentResult = true;
  19689. }
  19690. }
  19691. this._nextActiveAction.execute(evt);
  19692. if (this._nextActiveAction._child) {
  19693. if (!this._nextActiveAction._child._actionManager) {
  19694. this._nextActiveAction._child._actionManager = this._actionManager;
  19695. }
  19696. this._nextActiveAction = this._nextActiveAction._child;
  19697. } else {
  19698. this._nextActiveAction = this;
  19699. }
  19700. };
  19701. Action.prototype.execute = function (evt) {
  19702. };
  19703. Action.prototype.then = function (action) {
  19704. this._child = action;
  19705. action._actionManager = this._actionManager;
  19706. action._prepare();
  19707. return action;
  19708. };
  19709. Action.prototype._getProperty = function (propertyPath) {
  19710. return this._actionManager._getProperty(propertyPath);
  19711. };
  19712. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19713. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19714. };
  19715. return Action;
  19716. })();
  19717. BABYLON.Action = Action;
  19718. })(BABYLON || (BABYLON = {}));
  19719. var BABYLON;
  19720. (function (BABYLON) {
  19721. var ActionEvent = (function () {
  19722. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19723. this.source = source;
  19724. this.pointerX = pointerX;
  19725. this.pointerY = pointerY;
  19726. this.meshUnderPointer = meshUnderPointer;
  19727. this.sourceEvent = sourceEvent;
  19728. }
  19729. ActionEvent.CreateNew = function (source) {
  19730. var scene = source.getScene();
  19731. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19732. };
  19733. ActionEvent.CreateNewFromScene = function (scene, evt) {
  19734. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  19735. };
  19736. return ActionEvent;
  19737. })();
  19738. BABYLON.ActionEvent = ActionEvent;
  19739. var ActionManager = (function () {
  19740. function ActionManager(scene) {
  19741. this.actions = new Array();
  19742. this._scene = scene;
  19743. scene._actionManagers.push(this);
  19744. }
  19745. Object.defineProperty(ActionManager, "NothingTrigger", {
  19746. get: function () {
  19747. return ActionManager._NothingTrigger;
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(ActionManager, "OnPickTrigger", {
  19753. get: function () {
  19754. return ActionManager._OnPickTrigger;
  19755. },
  19756. enumerable: true,
  19757. configurable: true
  19758. });
  19759. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  19760. get: function () {
  19761. return ActionManager._OnLeftPickTrigger;
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  19767. get: function () {
  19768. return ActionManager._OnRightPickTrigger;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  19774. get: function () {
  19775. return ActionManager._OnCenterPickTrigger;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  19781. get: function () {
  19782. return ActionManager._OnPointerOverTrigger;
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  19788. get: function () {
  19789. return ActionManager._OnPointerOutTrigger;
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  19795. get: function () {
  19796. return ActionManager._OnEveryFrameTrigger;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  19802. get: function () {
  19803. return ActionManager._OnIntersectionEnterTrigger;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  19809. get: function () {
  19810. return ActionManager._OnIntersectionExitTrigger;
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  19816. get: function () {
  19817. return ActionManager._OnKeyDownTrigger;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  19823. get: function () {
  19824. return ActionManager._OnKeyUpTrigger;
  19825. },
  19826. enumerable: true,
  19827. configurable: true
  19828. });
  19829. ActionManager.prototype.dispose = function () {
  19830. var index = this._scene._actionManagers.indexOf(this);
  19831. if (index > -1) {
  19832. this._scene._actionManagers.splice(index, 1);
  19833. }
  19834. };
  19835. ActionManager.prototype.getScene = function () {
  19836. return this._scene;
  19837. };
  19838. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  19839. for (var index = 0; index < this.actions.length; index++) {
  19840. var action = this.actions[index];
  19841. if (triggers.indexOf(action.trigger) > -1) {
  19842. return true;
  19843. }
  19844. }
  19845. return false;
  19846. };
  19847. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  19848. get: function () {
  19849. for (var index = 0; index < this.actions.length; index++) {
  19850. var action = this.actions[index];
  19851. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  19852. return true;
  19853. }
  19854. }
  19855. return false;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  19861. get: function () {
  19862. for (var index = 0; index < this.actions.length; index++) {
  19863. var action = this.actions[index];
  19864. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  19865. return true;
  19866. }
  19867. }
  19868. return false;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. ActionManager.prototype.registerAction = function (action) {
  19874. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  19875. if (this.getScene().actionManager !== this) {
  19876. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  19877. return null;
  19878. }
  19879. }
  19880. this.actions.push(action);
  19881. action._actionManager = this;
  19882. action._prepare();
  19883. return action;
  19884. };
  19885. ActionManager.prototype.processTrigger = function (trigger, evt) {
  19886. for (var index = 0; index < this.actions.length; index++) {
  19887. var action = this.actions[index];
  19888. if (action.trigger === trigger) {
  19889. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  19890. var parameter = action.getTriggerParameter();
  19891. if (parameter) {
  19892. if (evt.sourceEvent.key !== parameter) {
  19893. continue;
  19894. }
  19895. }
  19896. }
  19897. action._executeCurrent(evt);
  19898. }
  19899. }
  19900. };
  19901. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  19902. var properties = propertyPath.split(".");
  19903. for (var index = 0; index < properties.length - 1; index++) {
  19904. target = target[properties[index]];
  19905. }
  19906. return target;
  19907. };
  19908. ActionManager.prototype._getProperty = function (propertyPath) {
  19909. var properties = propertyPath.split(".");
  19910. return properties[properties.length - 1];
  19911. };
  19912. ActionManager._NothingTrigger = 0;
  19913. ActionManager._OnPickTrigger = 1;
  19914. ActionManager._OnLeftPickTrigger = 2;
  19915. ActionManager._OnRightPickTrigger = 3;
  19916. ActionManager._OnCenterPickTrigger = 4;
  19917. ActionManager._OnPointerOverTrigger = 5;
  19918. ActionManager._OnPointerOutTrigger = 6;
  19919. ActionManager._OnEveryFrameTrigger = 7;
  19920. ActionManager._OnIntersectionEnterTrigger = 8;
  19921. ActionManager._OnIntersectionExitTrigger = 9;
  19922. ActionManager._OnKeyDownTrigger = 10;
  19923. ActionManager._OnKeyUpTrigger = 11;
  19924. return ActionManager;
  19925. })();
  19926. BABYLON.ActionManager = ActionManager;
  19927. })(BABYLON || (BABYLON = {}));
  19928. var __extends = this.__extends || function (d, b) {
  19929. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19930. function __() { this.constructor = d; }
  19931. __.prototype = b.prototype;
  19932. d.prototype = new __();
  19933. };
  19934. var BABYLON;
  19935. (function (BABYLON) {
  19936. var InterpolateValueAction = (function (_super) {
  19937. __extends(InterpolateValueAction, _super);
  19938. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  19939. if (typeof duration === "undefined") { duration = 1000; }
  19940. _super.call(this, triggerOptions, condition);
  19941. this.propertyPath = propertyPath;
  19942. this.value = value;
  19943. this.duration = duration;
  19944. this.stopOtherAnimations = stopOtherAnimations;
  19945. this._target = target;
  19946. }
  19947. InterpolateValueAction.prototype._prepare = function () {
  19948. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  19949. this._property = this._getProperty(this.propertyPath);
  19950. };
  19951. InterpolateValueAction.prototype.execute = function () {
  19952. var scene = this._actionManager.getScene();
  19953. var keys = [
  19954. {
  19955. frame: 0,
  19956. value: this._target[this._property]
  19957. }, {
  19958. frame: 100,
  19959. value: this.value
  19960. }
  19961. ];
  19962. var dataType;
  19963. if (typeof this.value === "number") {
  19964. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  19965. } else if (this.value instanceof BABYLON.Color3) {
  19966. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  19967. } else if (this.value instanceof BABYLON.Vector3) {
  19968. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  19969. } else if (this.value instanceof BABYLON.Matrix) {
  19970. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  19971. } else if (this.value instanceof BABYLON.Quaternion) {
  19972. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  19973. } else {
  19974. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  19975. return;
  19976. }
  19977. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  19978. animation.setKeys(keys);
  19979. if (this.stopOtherAnimations) {
  19980. scene.stopAnimation(this._target);
  19981. }
  19982. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  19983. };
  19984. return InterpolateValueAction;
  19985. })(BABYLON.Action);
  19986. BABYLON.InterpolateValueAction = InterpolateValueAction;
  19987. })(BABYLON || (BABYLON = {}));
  19988. var __extends = this.__extends || function (d, b) {
  19989. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19990. function __() { this.constructor = d; }
  19991. __.prototype = b.prototype;
  19992. d.prototype = new __();
  19993. };
  19994. var BABYLON;
  19995. (function (BABYLON) {
  19996. var SwitchBooleanAction = (function (_super) {
  19997. __extends(SwitchBooleanAction, _super);
  19998. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  19999. _super.call(this, triggerOptions, condition);
  20000. this.propertyPath = propertyPath;
  20001. this._target = target;
  20002. }
  20003. SwitchBooleanAction.prototype._prepare = function () {
  20004. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20005. this._property = this._getProperty(this.propertyPath);
  20006. };
  20007. SwitchBooleanAction.prototype.execute = function () {
  20008. this._target[this._property] = !this._target[this._property];
  20009. };
  20010. return SwitchBooleanAction;
  20011. })(BABYLON.Action);
  20012. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  20013. var SetStateAction = (function (_super) {
  20014. __extends(SetStateAction, _super);
  20015. function SetStateAction(triggerOptions, target, value, condition) {
  20016. _super.call(this, triggerOptions, condition);
  20017. this.value = value;
  20018. this._target = target;
  20019. }
  20020. SetStateAction.prototype.execute = function () {
  20021. this._target.state = this.value;
  20022. };
  20023. return SetStateAction;
  20024. })(BABYLON.Action);
  20025. BABYLON.SetStateAction = SetStateAction;
  20026. var SetValueAction = (function (_super) {
  20027. __extends(SetValueAction, _super);
  20028. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  20029. _super.call(this, triggerOptions, condition);
  20030. this.propertyPath = propertyPath;
  20031. this.value = value;
  20032. this._target = target;
  20033. }
  20034. SetValueAction.prototype._prepare = function () {
  20035. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20036. this._property = this._getProperty(this.propertyPath);
  20037. };
  20038. SetValueAction.prototype.execute = function () {
  20039. this._target[this._property] = this.value;
  20040. };
  20041. return SetValueAction;
  20042. })(BABYLON.Action);
  20043. BABYLON.SetValueAction = SetValueAction;
  20044. var IncrementValueAction = (function (_super) {
  20045. __extends(IncrementValueAction, _super);
  20046. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  20047. _super.call(this, triggerOptions, condition);
  20048. this.propertyPath = propertyPath;
  20049. this.value = value;
  20050. this._target = target;
  20051. }
  20052. IncrementValueAction.prototype._prepare = function () {
  20053. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20054. this._property = this._getProperty(this.propertyPath);
  20055. if (typeof this._target[this._property] !== "number") {
  20056. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  20057. }
  20058. };
  20059. IncrementValueAction.prototype.execute = function () {
  20060. this._target[this._property] += this.value;
  20061. };
  20062. return IncrementValueAction;
  20063. })(BABYLON.Action);
  20064. BABYLON.IncrementValueAction = IncrementValueAction;
  20065. var PlayAnimationAction = (function (_super) {
  20066. __extends(PlayAnimationAction, _super);
  20067. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  20068. _super.call(this, triggerOptions, condition);
  20069. this.from = from;
  20070. this.to = to;
  20071. this.loop = loop;
  20072. this._target = target;
  20073. }
  20074. PlayAnimationAction.prototype._prepare = function () {
  20075. };
  20076. PlayAnimationAction.prototype.execute = function () {
  20077. var scene = this._actionManager.getScene();
  20078. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  20079. };
  20080. return PlayAnimationAction;
  20081. })(BABYLON.Action);
  20082. BABYLON.PlayAnimationAction = PlayAnimationAction;
  20083. var StopAnimationAction = (function (_super) {
  20084. __extends(StopAnimationAction, _super);
  20085. function StopAnimationAction(triggerOptions, target, condition) {
  20086. _super.call(this, triggerOptions, condition);
  20087. this._target = target;
  20088. }
  20089. StopAnimationAction.prototype._prepare = function () {
  20090. };
  20091. StopAnimationAction.prototype.execute = function () {
  20092. var scene = this._actionManager.getScene();
  20093. scene.stopAnimation(this._target);
  20094. };
  20095. return StopAnimationAction;
  20096. })(BABYLON.Action);
  20097. BABYLON.StopAnimationAction = StopAnimationAction;
  20098. var DoNothingAction = (function (_super) {
  20099. __extends(DoNothingAction, _super);
  20100. function DoNothingAction(triggerOptions, condition) {
  20101. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  20102. _super.call(this, triggerOptions, condition);
  20103. }
  20104. DoNothingAction.prototype.execute = function () {
  20105. };
  20106. return DoNothingAction;
  20107. })(BABYLON.Action);
  20108. BABYLON.DoNothingAction = DoNothingAction;
  20109. var CombineAction = (function (_super) {
  20110. __extends(CombineAction, _super);
  20111. function CombineAction(triggerOptions, children, condition) {
  20112. _super.call(this, triggerOptions, condition);
  20113. this.children = children;
  20114. }
  20115. CombineAction.prototype._prepare = function () {
  20116. for (var index = 0; index < this.children.length; index++) {
  20117. this.children[index]._actionManager = this._actionManager;
  20118. this.children[index]._prepare();
  20119. }
  20120. };
  20121. CombineAction.prototype.execute = function (evt) {
  20122. for (var index = 0; index < this.children.length; index++) {
  20123. this.children[index].execute(evt);
  20124. }
  20125. };
  20126. return CombineAction;
  20127. })(BABYLON.Action);
  20128. BABYLON.CombineAction = CombineAction;
  20129. var ExecuteCodeAction = (function (_super) {
  20130. __extends(ExecuteCodeAction, _super);
  20131. function ExecuteCodeAction(triggerOptions, func, condition) {
  20132. _super.call(this, triggerOptions, condition);
  20133. this.func = func;
  20134. }
  20135. ExecuteCodeAction.prototype.execute = function (evt) {
  20136. this.func(evt);
  20137. };
  20138. return ExecuteCodeAction;
  20139. })(BABYLON.Action);
  20140. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  20141. var SetParentAction = (function (_super) {
  20142. __extends(SetParentAction, _super);
  20143. function SetParentAction(triggerOptions, target, parent, condition) {
  20144. _super.call(this, triggerOptions, condition);
  20145. this._target = target;
  20146. this._parent = parent;
  20147. }
  20148. SetParentAction.prototype._prepare = function () {
  20149. };
  20150. SetParentAction.prototype.execute = function () {
  20151. if (this._target.parent === this._parent) {
  20152. return;
  20153. }
  20154. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  20155. invertParentWorldMatrix.invert();
  20156. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  20157. this._target.parent = this._parent;
  20158. };
  20159. return SetParentAction;
  20160. })(BABYLON.Action);
  20161. BABYLON.SetParentAction = SetParentAction;
  20162. })(BABYLON || (BABYLON = {}));
  20163. var __extends = this.__extends || function (d, b) {
  20164. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20165. function __() { this.constructor = d; }
  20166. __.prototype = b.prototype;
  20167. d.prototype = new __();
  20168. };
  20169. var BABYLON;
  20170. (function (BABYLON) {
  20171. var Geometry = (function () {
  20172. function Geometry(id, scene, vertexData, updatable, mesh) {
  20173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20174. this._totalVertices = 0;
  20175. this._indices = [];
  20176. this.id = id;
  20177. this._engine = scene.getEngine();
  20178. this._meshes = [];
  20179. this._scene = scene;
  20180. if (vertexData) {
  20181. this.setAllVerticesData(vertexData, updatable);
  20182. } else {
  20183. this._totalVertices = 0;
  20184. this._indices = [];
  20185. }
  20186. if (mesh) {
  20187. this.applyToMesh(mesh);
  20188. }
  20189. }
  20190. Geometry.prototype.getScene = function () {
  20191. return this._scene;
  20192. };
  20193. Geometry.prototype.getEngine = function () {
  20194. return this._engine;
  20195. };
  20196. Geometry.prototype.isReady = function () {
  20197. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  20198. };
  20199. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  20200. vertexData.applyToGeometry(this, updatable);
  20201. };
  20202. Geometry.prototype.setVerticesData = function (kind, data, updatable) {
  20203. this._vertexBuffers = this._vertexBuffers || {};
  20204. if (this._vertexBuffers[kind]) {
  20205. this._vertexBuffers[kind].dispose();
  20206. }
  20207. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0);
  20208. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20209. var stride = this._vertexBuffers[kind].getStrideSize();
  20210. this._totalVertices = data.length / stride;
  20211. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20212. var meshes = this._meshes;
  20213. var numOfMeshes = meshes.length;
  20214. for (var index = 0; index < numOfMeshes; index++) {
  20215. var mesh = meshes[index];
  20216. mesh._resetPointsArrayCache();
  20217. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20218. mesh._createGlobalSubMesh();
  20219. mesh.computeWorldMatrix(true);
  20220. }
  20221. }
  20222. };
  20223. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  20224. var vertexBuffer = this.getVertexBuffer(kind);
  20225. if (!vertexBuffer) {
  20226. return;
  20227. }
  20228. vertexBuffer.updateDirectly(data);
  20229. };
  20230. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  20231. var vertexBuffer = this.getVertexBuffer(kind);
  20232. if (!vertexBuffer) {
  20233. return;
  20234. }
  20235. vertexBuffer.update(data);
  20236. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20237. var extend;
  20238. if (updateExtends) {
  20239. var stride = vertexBuffer.getStrideSize();
  20240. this._totalVertices = data.length / stride;
  20241. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20242. }
  20243. var meshes = this._meshes;
  20244. var numOfMeshes = meshes.length;
  20245. for (var index = 0; index < numOfMeshes; index++) {
  20246. var mesh = meshes[index];
  20247. mesh._resetPointsArrayCache();
  20248. if (updateExtends) {
  20249. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20250. }
  20251. }
  20252. }
  20253. };
  20254. Geometry.prototype.getTotalVertices = function () {
  20255. if (!this.isReady()) {
  20256. return 0;
  20257. }
  20258. return this._totalVertices;
  20259. };
  20260. Geometry.prototype.getVerticesData = function (kind) {
  20261. var vertexBuffer = this.getVertexBuffer(kind);
  20262. if (!vertexBuffer) {
  20263. return null;
  20264. }
  20265. return vertexBuffer.getData();
  20266. };
  20267. Geometry.prototype.getVertexBuffer = function (kind) {
  20268. if (!this.isReady()) {
  20269. return null;
  20270. }
  20271. return this._vertexBuffers[kind];
  20272. };
  20273. Geometry.prototype.getVertexBuffers = function () {
  20274. if (!this.isReady()) {
  20275. return null;
  20276. }
  20277. return this._vertexBuffers;
  20278. };
  20279. Geometry.prototype.isVerticesDataPresent = function (kind) {
  20280. if (!this._vertexBuffers) {
  20281. if (this._delayInfo) {
  20282. return this._delayInfo.indexOf(kind) !== -1;
  20283. }
  20284. return false;
  20285. }
  20286. return this._vertexBuffers[kind] !== undefined;
  20287. };
  20288. Geometry.prototype.getVerticesDataKinds = function () {
  20289. var result = [];
  20290. if (!this._vertexBuffers && this._delayInfo) {
  20291. for (var kind in this._delayInfo) {
  20292. result.push(kind);
  20293. }
  20294. } else {
  20295. for (kind in this._vertexBuffers) {
  20296. result.push(kind);
  20297. }
  20298. }
  20299. return result;
  20300. };
  20301. Geometry.prototype.setIndices = function (indices) {
  20302. if (this._indexBuffer) {
  20303. this._engine._releaseBuffer(this._indexBuffer);
  20304. }
  20305. this._indices = indices;
  20306. if (this._meshes.length !== 0 && this._indices) {
  20307. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20308. }
  20309. var meshes = this._meshes;
  20310. var numOfMeshes = meshes.length;
  20311. for (var index = 0; index < numOfMeshes; index++) {
  20312. meshes[index]._createGlobalSubMesh();
  20313. }
  20314. };
  20315. Geometry.prototype.getTotalIndices = function () {
  20316. if (!this.isReady()) {
  20317. return 0;
  20318. }
  20319. return this._indices.length;
  20320. };
  20321. Geometry.prototype.getIndices = function () {
  20322. if (!this.isReady()) {
  20323. return null;
  20324. }
  20325. return this._indices;
  20326. };
  20327. Geometry.prototype.getIndexBuffer = function () {
  20328. if (!this.isReady()) {
  20329. return null;
  20330. }
  20331. return this._indexBuffer;
  20332. };
  20333. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  20334. var meshes = this._meshes;
  20335. var index = meshes.indexOf(mesh);
  20336. if (index === -1) {
  20337. return;
  20338. }
  20339. for (var kind in this._vertexBuffers) {
  20340. this._vertexBuffers[kind].dispose();
  20341. }
  20342. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  20343. this._indexBuffer = null;
  20344. }
  20345. meshes.splice(index, 1);
  20346. mesh._geometry = null;
  20347. if (meshes.length == 0 && shouldDispose) {
  20348. this.dispose();
  20349. }
  20350. };
  20351. Geometry.prototype.applyToMesh = function (mesh) {
  20352. if (mesh._geometry === this) {
  20353. return;
  20354. }
  20355. var previousGeometry = mesh._geometry;
  20356. if (previousGeometry) {
  20357. previousGeometry.releaseForMesh(mesh);
  20358. }
  20359. var meshes = this._meshes;
  20360. mesh._geometry = this;
  20361. this._scene.pushGeometry(this);
  20362. meshes.push(mesh);
  20363. if (this.isReady()) {
  20364. this._applyToMesh(mesh);
  20365. } else {
  20366. mesh._boundingInfo = this._boundingInfo;
  20367. }
  20368. };
  20369. Geometry.prototype._applyToMesh = function (mesh) {
  20370. var numOfMeshes = this._meshes.length;
  20371. for (var kind in this._vertexBuffers) {
  20372. if (numOfMeshes === 1) {
  20373. this._vertexBuffers[kind].create();
  20374. }
  20375. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  20376. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20377. mesh._resetPointsArrayCache();
  20378. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  20379. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20380. mesh._createGlobalSubMesh();
  20381. }
  20382. }
  20383. if (numOfMeshes === 1 && this._indices) {
  20384. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20385. }
  20386. if (this._indexBuffer) {
  20387. this._indexBuffer.references = numOfMeshes;
  20388. }
  20389. };
  20390. Geometry.prototype.load = function (scene, onLoaded) {
  20391. var _this = this;
  20392. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20393. return;
  20394. }
  20395. if (this.isReady()) {
  20396. if (onLoaded) {
  20397. onLoaded();
  20398. }
  20399. return;
  20400. }
  20401. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20402. scene._addPendingData(this);
  20403. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20404. _this._delayLoadingFunction(JSON.parse(data), _this);
  20405. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20406. _this._delayInfo = [];
  20407. scene._removePendingData(_this);
  20408. var meshes = _this._meshes;
  20409. var numOfMeshes = meshes.length;
  20410. for (var index = 0; index < numOfMeshes; index++) {
  20411. _this._applyToMesh(meshes[index]);
  20412. }
  20413. if (onLoaded) {
  20414. onLoaded();
  20415. }
  20416. }, function () {
  20417. }, scene.database);
  20418. };
  20419. Geometry.prototype.dispose = function () {
  20420. var meshes = this._meshes;
  20421. var numOfMeshes = meshes.length;
  20422. for (var index = 0; index < numOfMeshes; index++) {
  20423. this.releaseForMesh(meshes[index]);
  20424. }
  20425. this._meshes = [];
  20426. for (var kind in this._vertexBuffers) {
  20427. this._vertexBuffers[kind].dispose();
  20428. }
  20429. this._vertexBuffers = [];
  20430. this._totalVertices = 0;
  20431. if (this._indexBuffer) {
  20432. this._engine._releaseBuffer(this._indexBuffer);
  20433. }
  20434. this._indexBuffer = null;
  20435. this._indices = [];
  20436. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20437. this.delayLoadingFile = null;
  20438. this._delayLoadingFunction = null;
  20439. this._delayInfo = [];
  20440. this._boundingInfo = null;
  20441. var geometries = this._scene.getGeometries();
  20442. index = geometries.indexOf(this);
  20443. if (index > -1) {
  20444. geometries.splice(index, 1);
  20445. }
  20446. };
  20447. Geometry.prototype.copy = function (id) {
  20448. var vertexData = new BABYLON.VertexData();
  20449. vertexData.indices = [];
  20450. var indices = this.getIndices();
  20451. for (var index = 0; index < indices.length; index++) {
  20452. vertexData.indices.push(indices[index]);
  20453. }
  20454. var updatable = false;
  20455. var stopChecking = false;
  20456. for (var kind in this._vertexBuffers) {
  20457. vertexData.set(this.getVerticesData(kind), kind);
  20458. if (!stopChecking) {
  20459. updatable = this.getVertexBuffer(kind).isUpdatable();
  20460. stopChecking = !updatable;
  20461. }
  20462. }
  20463. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  20464. geometry.delayLoadState = this.delayLoadState;
  20465. geometry.delayLoadingFile = this.delayLoadingFile;
  20466. geometry._delayLoadingFunction = this._delayLoadingFunction;
  20467. for (kind in this._delayInfo) {
  20468. geometry._delayInfo = geometry._delayInfo || [];
  20469. geometry._delayInfo.push(kind);
  20470. }
  20471. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  20472. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20473. return geometry;
  20474. };
  20475. Geometry.ExtractFromMesh = function (mesh, id) {
  20476. var geometry = mesh._geometry;
  20477. if (!geometry) {
  20478. return null;
  20479. }
  20480. return geometry.copy(id);
  20481. };
  20482. Geometry.RandomId = function () {
  20483. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20484. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20485. return v.toString(16);
  20486. });
  20487. };
  20488. return Geometry;
  20489. })();
  20490. BABYLON.Geometry = Geometry;
  20491. (function (Geometry) {
  20492. (function (Primitives) {
  20493. var _Primitive = (function (_super) {
  20494. __extends(_Primitive, _super);
  20495. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20496. this._beingRegenerated = true;
  20497. this._canBeRegenerated = canBeRegenerated;
  20498. _super.call(this, id, scene, vertexData, false, mesh);
  20499. this._beingRegenerated = false;
  20500. }
  20501. _Primitive.prototype.canBeRegenerated = function () {
  20502. return this._canBeRegenerated;
  20503. };
  20504. _Primitive.prototype.regenerate = function () {
  20505. if (!this._canBeRegenerated) {
  20506. return;
  20507. }
  20508. this._beingRegenerated = true;
  20509. this.setAllVerticesData(this._regenerateVertexData(), false);
  20510. this._beingRegenerated = false;
  20511. };
  20512. _Primitive.prototype.asNewGeometry = function (id) {
  20513. return _super.prototype.copy.call(this, id);
  20514. };
  20515. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20516. if (!this._beingRegenerated) {
  20517. return;
  20518. }
  20519. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20520. };
  20521. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20522. if (!this._beingRegenerated) {
  20523. return;
  20524. }
  20525. _super.prototype.setVerticesData.call(this, kind, data, false);
  20526. };
  20527. _Primitive.prototype._regenerateVertexData = function () {
  20528. throw new Error("Abstract method");
  20529. };
  20530. _Primitive.prototype.copy = function (id) {
  20531. throw new Error("Must be overriden in sub-classes.");
  20532. };
  20533. return _Primitive;
  20534. })(Geometry);
  20535. Primitives._Primitive = _Primitive;
  20536. var Box = (function (_super) {
  20537. __extends(Box, _super);
  20538. function Box(id, scene, size, canBeRegenerated, mesh) {
  20539. this.size = size;
  20540. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20541. }
  20542. Box.prototype._regenerateVertexData = function () {
  20543. return BABYLON.VertexData.CreateBox(this.size);
  20544. };
  20545. Box.prototype.copy = function (id) {
  20546. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20547. };
  20548. return Box;
  20549. })(_Primitive);
  20550. Primitives.Box = Box;
  20551. var Sphere = (function (_super) {
  20552. __extends(Sphere, _super);
  20553. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20554. this.segments = segments;
  20555. this.diameter = diameter;
  20556. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20557. }
  20558. Sphere.prototype._regenerateVertexData = function () {
  20559. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20560. };
  20561. Sphere.prototype.copy = function (id) {
  20562. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20563. };
  20564. return Sphere;
  20565. })(_Primitive);
  20566. Primitives.Sphere = Sphere;
  20567. var Cylinder = (function (_super) {
  20568. __extends(Cylinder, _super);
  20569. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20570. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20571. this.height = height;
  20572. this.diameterTop = diameterTop;
  20573. this.diameterBottom = diameterBottom;
  20574. this.tessellation = tessellation;
  20575. this.subdivisions = subdivisions;
  20576. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20577. }
  20578. Cylinder.prototype._regenerateVertexData = function () {
  20579. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20580. };
  20581. Cylinder.prototype.copy = function (id) {
  20582. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20583. };
  20584. return Cylinder;
  20585. })(_Primitive);
  20586. Primitives.Cylinder = Cylinder;
  20587. var Torus = (function (_super) {
  20588. __extends(Torus, _super);
  20589. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20590. this.diameter = diameter;
  20591. this.thickness = thickness;
  20592. this.tessellation = tessellation;
  20593. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20594. }
  20595. Torus.prototype._regenerateVertexData = function () {
  20596. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20597. };
  20598. Torus.prototype.copy = function (id) {
  20599. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20600. };
  20601. return Torus;
  20602. })(_Primitive);
  20603. Primitives.Torus = Torus;
  20604. var Ground = (function (_super) {
  20605. __extends(Ground, _super);
  20606. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20607. this.width = width;
  20608. this.height = height;
  20609. this.subdivisions = subdivisions;
  20610. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20611. }
  20612. Ground.prototype._regenerateVertexData = function () {
  20613. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20614. };
  20615. Ground.prototype.copy = function (id) {
  20616. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20617. };
  20618. return Ground;
  20619. })(_Primitive);
  20620. Primitives.Ground = Ground;
  20621. var TiledGround = (function (_super) {
  20622. __extends(TiledGround, _super);
  20623. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20624. this.xmin = xmin;
  20625. this.zmin = zmin;
  20626. this.xmax = xmax;
  20627. this.zmax = zmax;
  20628. this.subdivisions = subdivisions;
  20629. this.precision = precision;
  20630. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20631. }
  20632. TiledGround.prototype._regenerateVertexData = function () {
  20633. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20634. };
  20635. TiledGround.prototype.copy = function (id) {
  20636. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20637. };
  20638. return TiledGround;
  20639. })(_Primitive);
  20640. Primitives.TiledGround = TiledGround;
  20641. var Plane = (function (_super) {
  20642. __extends(Plane, _super);
  20643. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20644. this.size = size;
  20645. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20646. }
  20647. Plane.prototype._regenerateVertexData = function () {
  20648. return BABYLON.VertexData.CreatePlane(this.size);
  20649. };
  20650. Plane.prototype.copy = function (id) {
  20651. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20652. };
  20653. return Plane;
  20654. })(_Primitive);
  20655. Primitives.Plane = Plane;
  20656. var TorusKnot = (function (_super) {
  20657. __extends(TorusKnot, _super);
  20658. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20659. this.radius = radius;
  20660. this.tube = tube;
  20661. this.radialSegments = radialSegments;
  20662. this.tubularSegments = tubularSegments;
  20663. this.p = p;
  20664. this.q = q;
  20665. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20666. }
  20667. TorusKnot.prototype._regenerateVertexData = function () {
  20668. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20669. };
  20670. TorusKnot.prototype.copy = function (id) {
  20671. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20672. };
  20673. return TorusKnot;
  20674. })(_Primitive);
  20675. Primitives.TorusKnot = TorusKnot;
  20676. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20677. var Primitives = Geometry.Primitives;
  20678. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20679. var Geometry = BABYLON.Geometry;
  20680. })(BABYLON || (BABYLON = {}));
  20681. var __extends = this.__extends || function (d, b) {
  20682. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20683. function __() { this.constructor = d; }
  20684. __.prototype = b.prototype;
  20685. d.prototype = new __();
  20686. };
  20687. var BABYLON;
  20688. (function (BABYLON) {
  20689. var Gamepads = (function () {
  20690. function Gamepads(ongamedpadconnected) {
  20691. var _this = this;
  20692. this.babylonGamepads = [];
  20693. this.oneGamepadConnected = false;
  20694. this.isMonitoring = false;
  20695. this.gamepadEventSupported = 'GamepadEvent' in window;
  20696. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20697. 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=";
  20698. this._callbackGamepadConnected = ongamedpadconnected;
  20699. if (this.gamepadSupportAvailable) {
  20700. if (this.gamepadEventSupported) {
  20701. window.addEventListener('gamepadconnected', function (evt) {
  20702. _this._onGamepadConnected(evt);
  20703. }, false);
  20704. window.addEventListener('gamepaddisconnected', function (evt) {
  20705. _this._onGamepadDisconnected(evt);
  20706. }, false);
  20707. } else {
  20708. this._startMonitoringGamepads();
  20709. }
  20710. if (!this.oneGamepadConnected) {
  20711. this._insertGamepadDOMInstructions();
  20712. }
  20713. } else {
  20714. this._insertGamepadDOMNotSupported();
  20715. }
  20716. }
  20717. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20718. Gamepads.gamepadDOMInfo = document.createElement("div");
  20719. var buttonAImage = document.createElement("img");
  20720. buttonAImage.src = this.buttonADataURL;
  20721. var spanMessage = document.createElement("span");
  20722. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20723. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20724. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20725. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20726. Gamepads.gamepadDOMInfo.style.width = "100%";
  20727. Gamepads.gamepadDOMInfo.style.height = "48px";
  20728. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20729. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20730. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20731. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20732. buttonAImage.style.position = "relative";
  20733. buttonAImage.style.bottom = "8px";
  20734. spanMessage.style.position = "relative";
  20735. spanMessage.style.fontSize = "32px";
  20736. spanMessage.style.bottom = "32px";
  20737. spanMessage.style.color = "green";
  20738. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20739. };
  20740. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  20741. Gamepads.gamepadDOMInfo = document.createElement("div");
  20742. var spanMessage = document.createElement("span");
  20743. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  20744. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20745. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20746. Gamepads.gamepadDOMInfo.style.width = "100%";
  20747. Gamepads.gamepadDOMInfo.style.height = "40px";
  20748. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20749. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20750. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20751. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20752. spanMessage.style.position = "relative";
  20753. spanMessage.style.fontSize = "32px";
  20754. spanMessage.style.color = "red";
  20755. document.body.appendChild(Gamepads.gamepadDOMInfo);
  20756. };
  20757. Gamepads.prototype.dispose = function () {
  20758. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20759. };
  20760. Gamepads.prototype._onGamepadConnected = function (evt) {
  20761. var newGamepad = this._addNewGamepad(evt.gamepad);
  20762. if (this._callbackGamepadConnected)
  20763. this._callbackGamepadConnected(newGamepad);
  20764. this._startMonitoringGamepads();
  20765. };
  20766. Gamepads.prototype._addNewGamepad = function (gamepad) {
  20767. if (!this.oneGamepadConnected) {
  20768. this.oneGamepadConnected = true;
  20769. if (Gamepads.gamepadDOMInfo) {
  20770. document.body.removeChild(Gamepads.gamepadDOMInfo);
  20771. Gamepads.gamepadDOMInfo = null;
  20772. }
  20773. }
  20774. var newGamepad;
  20775. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  20776. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  20777. } else {
  20778. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  20779. }
  20780. this.babylonGamepads.push(newGamepad);
  20781. return newGamepad;
  20782. };
  20783. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  20784. for (var i in this.babylonGamepads) {
  20785. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  20786. this.babylonGamepads.splice(i, 1);
  20787. break;
  20788. }
  20789. }
  20790. if (this.babylonGamepads.length == 0) {
  20791. this._stopMonitoringGamepads();
  20792. }
  20793. };
  20794. Gamepads.prototype._startMonitoringGamepads = function () {
  20795. if (!this.isMonitoring) {
  20796. this.isMonitoring = true;
  20797. this._checkGamepadsStatus();
  20798. }
  20799. };
  20800. Gamepads.prototype._stopMonitoringGamepads = function () {
  20801. this.isMonitoring = false;
  20802. };
  20803. Gamepads.prototype._checkGamepadsStatus = function () {
  20804. var _this = this;
  20805. this._updateGamepadObjects();
  20806. for (var i in this.babylonGamepads) {
  20807. this.babylonGamepads[i].update();
  20808. }
  20809. if (this.isMonitoring) {
  20810. if (window.requestAnimationFrame) {
  20811. window.requestAnimationFrame(function () {
  20812. _this._checkGamepadsStatus();
  20813. });
  20814. } else if (window.mozRequestAnimationFrame) {
  20815. window.mozRequestAnimationFrame(function () {
  20816. _this._checkGamepadsStatus();
  20817. });
  20818. } else if (window.webkitRequestAnimationFrame) {
  20819. window.webkitRequestAnimationFrame(function () {
  20820. _this._checkGamepadsStatus();
  20821. });
  20822. }
  20823. }
  20824. };
  20825. Gamepads.prototype._updateGamepadObjects = function () {
  20826. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  20827. for (var i = 0; i < gamepads.length; i++) {
  20828. if (gamepads[i]) {
  20829. if (!(gamepads[i].index in this.babylonGamepads)) {
  20830. var newGamepad = this._addNewGamepad(gamepads[i]);
  20831. if (this._callbackGamepadConnected) {
  20832. this._callbackGamepadConnected(newGamepad);
  20833. }
  20834. } else {
  20835. this.babylonGamepads[i].browserGamepad = gamepads[i];
  20836. }
  20837. }
  20838. }
  20839. };
  20840. return Gamepads;
  20841. })();
  20842. BABYLON.Gamepads = Gamepads;
  20843. var StickValues = (function () {
  20844. function StickValues(x, y) {
  20845. this.x = x;
  20846. this.y = y;
  20847. }
  20848. return StickValues;
  20849. })();
  20850. BABYLON.StickValues = StickValues;
  20851. var Gamepad = (function () {
  20852. function Gamepad(id, index, browserGamepad) {
  20853. this.id = id;
  20854. this.index = index;
  20855. this.browserGamepad = browserGamepad;
  20856. if (this.browserGamepad.axes.length >= 2) {
  20857. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20858. }
  20859. if (this.browserGamepad.axes.length >= 4) {
  20860. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20861. }
  20862. }
  20863. Gamepad.prototype.onleftstickchanged = function (callback) {
  20864. this._onleftstickchanged = callback;
  20865. };
  20866. Gamepad.prototype.onrightstickchanged = function (callback) {
  20867. this._onrightstickchanged = callback;
  20868. };
  20869. Object.defineProperty(Gamepad.prototype, "leftStick", {
  20870. get: function () {
  20871. return this._leftStick;
  20872. },
  20873. set: function (newValues) {
  20874. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  20875. this._onleftstickchanged(newValues);
  20876. }
  20877. this._leftStick = newValues;
  20878. },
  20879. enumerable: true,
  20880. configurable: true
  20881. });
  20882. Object.defineProperty(Gamepad.prototype, "rightStick", {
  20883. get: function () {
  20884. return this._rightStick;
  20885. },
  20886. set: function (newValues) {
  20887. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  20888. this._onrightstickchanged(newValues);
  20889. }
  20890. this._rightStick = newValues;
  20891. },
  20892. enumerable: true,
  20893. configurable: true
  20894. });
  20895. Gamepad.prototype.update = function () {
  20896. if (this._leftStick) {
  20897. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  20898. }
  20899. if (this._rightStick) {
  20900. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  20901. }
  20902. };
  20903. return Gamepad;
  20904. })();
  20905. BABYLON.Gamepad = Gamepad;
  20906. var GenericPad = (function (_super) {
  20907. __extends(GenericPad, _super);
  20908. function GenericPad(id, index, gamepad) {
  20909. _super.call(this, id, index, gamepad);
  20910. this.id = id;
  20911. this.index = index;
  20912. this.gamepad = gamepad;
  20913. this._buttons = new Array(gamepad.buttons.length);
  20914. }
  20915. GenericPad.prototype.onbuttondown = function (callback) {
  20916. this._onbuttondown = callback;
  20917. };
  20918. GenericPad.prototype.onbuttonup = function (callback) {
  20919. this._onbuttonup = callback;
  20920. };
  20921. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  20922. if (newValue !== currentValue) {
  20923. if (this._onbuttondown && newValue === 1) {
  20924. this._onbuttondown(buttonIndex);
  20925. }
  20926. if (this._onbuttonup && newValue === 0) {
  20927. this._onbuttonup(buttonIndex);
  20928. }
  20929. }
  20930. return newValue;
  20931. };
  20932. GenericPad.prototype.update = function () {
  20933. _super.prototype.update.call(this);
  20934. for (var index = 0; index < this._buttons.length; index++) {
  20935. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  20936. }
  20937. };
  20938. return GenericPad;
  20939. })(Gamepad);
  20940. BABYLON.GenericPad = GenericPad;
  20941. (function (Xbox360Button) {
  20942. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  20943. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  20944. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  20945. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  20946. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  20947. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  20948. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  20949. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  20950. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  20951. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  20952. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  20953. var Xbox360Button = BABYLON.Xbox360Button;
  20954. (function (Xbox360Dpad) {
  20955. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  20956. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  20957. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  20958. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  20959. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  20960. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  20961. var Xbox360Pad = (function (_super) {
  20962. __extends(Xbox360Pad, _super);
  20963. function Xbox360Pad() {
  20964. _super.apply(this, arguments);
  20965. this._leftTrigger = 0;
  20966. this._rightTrigger = 0;
  20967. this._buttonA = 0;
  20968. this._buttonB = 0;
  20969. this._buttonX = 0;
  20970. this._buttonY = 0;
  20971. this._buttonBack = 0;
  20972. this._buttonStart = 0;
  20973. this._buttonLB = 0;
  20974. this._buttonRB = 0;
  20975. this._buttonLeftStick = 0;
  20976. this._buttonRightStick = 0;
  20977. this._dPadUp = 0;
  20978. this._dPadDown = 0;
  20979. this._dPadLeft = 0;
  20980. this._dPadRight = 0;
  20981. }
  20982. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  20983. this._onlefttriggerchanged = callback;
  20984. };
  20985. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  20986. this._onrighttriggerchanged = callback;
  20987. };
  20988. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  20989. get: function () {
  20990. return this._leftTrigger;
  20991. },
  20992. set: function (newValue) {
  20993. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  20994. this._onlefttriggerchanged(newValue);
  20995. }
  20996. this._leftTrigger = newValue;
  20997. },
  20998. enumerable: true,
  20999. configurable: true
  21000. });
  21001. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  21002. get: function () {
  21003. return this._rightTrigger;
  21004. },
  21005. set: function (newValue) {
  21006. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  21007. this._onrighttriggerchanged(newValue);
  21008. }
  21009. this._rightTrigger = newValue;
  21010. },
  21011. enumerable: true,
  21012. configurable: true
  21013. });
  21014. Xbox360Pad.prototype.onbuttondown = function (callback) {
  21015. this._onbuttondown = callback;
  21016. };
  21017. Xbox360Pad.prototype.onbuttonup = function (callback) {
  21018. this._onbuttonup = callback;
  21019. };
  21020. Xbox360Pad.prototype.ondpaddown = function (callback) {
  21021. this._ondpaddown = callback;
  21022. };
  21023. Xbox360Pad.prototype.ondpadup = function (callback) {
  21024. this._ondpadup = callback;
  21025. };
  21026. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  21027. if (newValue !== currentValue) {
  21028. if (this._onbuttondown && newValue === 1) {
  21029. this._onbuttondown(buttonType);
  21030. }
  21031. if (this._onbuttonup && newValue === 0) {
  21032. this._onbuttonup(buttonType);
  21033. }
  21034. }
  21035. return newValue;
  21036. };
  21037. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  21038. if (newValue !== currentValue) {
  21039. if (this._ondpaddown && newValue === 1) {
  21040. this._ondpaddown(buttonType);
  21041. }
  21042. if (this._ondpadup && newValue === 0) {
  21043. this._ondpadup(buttonType);
  21044. }
  21045. }
  21046. return newValue;
  21047. };
  21048. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  21049. get: function () {
  21050. return this._buttonA;
  21051. },
  21052. set: function (value) {
  21053. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  21054. },
  21055. enumerable: true,
  21056. configurable: true
  21057. });
  21058. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  21059. get: function () {
  21060. return this._buttonB;
  21061. },
  21062. set: function (value) {
  21063. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  21064. },
  21065. enumerable: true,
  21066. configurable: true
  21067. });
  21068. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  21069. get: function () {
  21070. return this._buttonX;
  21071. },
  21072. set: function (value) {
  21073. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  21079. get: function () {
  21080. return this._buttonY;
  21081. },
  21082. set: function (value) {
  21083. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  21089. get: function () {
  21090. return this._buttonStart;
  21091. },
  21092. set: function (value) {
  21093. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  21099. get: function () {
  21100. return this._buttonBack;
  21101. },
  21102. set: function (value) {
  21103. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  21109. get: function () {
  21110. return this._buttonLB;
  21111. },
  21112. set: function (value) {
  21113. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  21119. get: function () {
  21120. return this._buttonRB;
  21121. },
  21122. set: function (value) {
  21123. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  21129. get: function () {
  21130. return this._buttonLeftStick;
  21131. },
  21132. set: function (value) {
  21133. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  21134. },
  21135. enumerable: true,
  21136. configurable: true
  21137. });
  21138. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  21139. get: function () {
  21140. return this._buttonRightStick;
  21141. },
  21142. set: function (value) {
  21143. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  21149. get: function () {
  21150. return this._dPadUp;
  21151. },
  21152. set: function (value) {
  21153. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  21154. },
  21155. enumerable: true,
  21156. configurable: true
  21157. });
  21158. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  21159. get: function () {
  21160. return this._dPadDown;
  21161. },
  21162. set: function (value) {
  21163. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  21169. get: function () {
  21170. return this._dPadLeft;
  21171. },
  21172. set: function (value) {
  21173. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  21174. },
  21175. enumerable: true,
  21176. configurable: true
  21177. });
  21178. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  21179. get: function () {
  21180. return this._dPadRight;
  21181. },
  21182. set: function (value) {
  21183. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  21184. },
  21185. enumerable: true,
  21186. configurable: true
  21187. });
  21188. Xbox360Pad.prototype.update = function () {
  21189. _super.prototype.update.call(this);
  21190. this.buttonA = this.browserGamepad.buttons[0].value;
  21191. this.buttonB = this.browserGamepad.buttons[1].value;
  21192. this.buttonX = this.browserGamepad.buttons[2].value;
  21193. this.buttonY = this.browserGamepad.buttons[3].value;
  21194. this.buttonLB = this.browserGamepad.buttons[4].value;
  21195. this.buttonRB = this.browserGamepad.buttons[5].value;
  21196. this.leftTrigger = this.browserGamepad.buttons[6].value;
  21197. this.rightTrigger = this.browserGamepad.buttons[7].value;
  21198. this.buttonBack = this.browserGamepad.buttons[8].value;
  21199. this.buttonStart = this.browserGamepad.buttons[9].value;
  21200. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  21201. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  21202. this.dPadUp = this.browserGamepad.buttons[12].value;
  21203. this.dPadDown = this.browserGamepad.buttons[13].value;
  21204. this.dPadLeft = this.browserGamepad.buttons[14].value;
  21205. this.dPadRight = this.browserGamepad.buttons[15].value;
  21206. };
  21207. return Xbox360Pad;
  21208. })(Gamepad);
  21209. BABYLON.Xbox360Pad = Xbox360Pad;
  21210. })(BABYLON || (BABYLON = {}));
  21211. var __extends = this.__extends || function (d, b) {
  21212. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21213. function __() { this.constructor = d; }
  21214. __.prototype = b.prototype;
  21215. d.prototype = new __();
  21216. };
  21217. var BABYLON;
  21218. (function (BABYLON) {
  21219. var GamepadCamera = (function (_super) {
  21220. __extends(GamepadCamera, _super);
  21221. function GamepadCamera(name, position, scene) {
  21222. var _this = this;
  21223. _super.call(this, name, position, scene);
  21224. this.angularSensibility = 200;
  21225. this.moveSensibility = 75;
  21226. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21227. _this._onNewGameConnected(gamepad);
  21228. });
  21229. }
  21230. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21231. if (gamepad.index === 0) {
  21232. this._gamepad = gamepad;
  21233. }
  21234. };
  21235. GamepadCamera.prototype._checkInputs = function () {
  21236. if (!this._gamepad) {
  21237. return;
  21238. }
  21239. var LSValues = this._gamepad.leftStick;
  21240. var normalizedLX = LSValues.x / this.moveSensibility;
  21241. var normalizedLY = LSValues.y / this.moveSensibility;
  21242. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21243. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21244. var RSValues = this._gamepad.rightStick;
  21245. var normalizedRX = RSValues.x / this.angularSensibility;
  21246. var normalizedRY = RSValues.y / this.angularSensibility;
  21247. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  21248. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  21249. ;
  21250. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21251. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21252. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21253. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  21254. };
  21255. GamepadCamera.prototype.dispose = function () {
  21256. this._gamepads.dispose();
  21257. _super.prototype.dispose.call(this);
  21258. };
  21259. return GamepadCamera;
  21260. })(BABYLON.FreeCamera);
  21261. BABYLON.GamepadCamera = GamepadCamera;
  21262. })(BABYLON || (BABYLON = {}));
  21263. var __extends = this.__extends || function (d, b) {
  21264. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21265. function __() { this.constructor = d; }
  21266. __.prototype = b.prototype;
  21267. d.prototype = new __();
  21268. };
  21269. var BABYLON;
  21270. (function (BABYLON) {
  21271. var LinesMesh = (function (_super) {
  21272. __extends(LinesMesh, _super);
  21273. function LinesMesh(name, scene, updatable) {
  21274. if (typeof updatable === "undefined") { updatable = false; }
  21275. _super.call(this, name, scene);
  21276. this.color = new BABYLON.Color3(1, 1, 1);
  21277. this.alpha = 1;
  21278. this._indices = new Array();
  21279. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21280. attributes: ["position"],
  21281. uniforms: ["worldViewProjection", "color"],
  21282. needAlphaBlending: true
  21283. });
  21284. }
  21285. Object.defineProperty(LinesMesh.prototype, "material", {
  21286. get: function () {
  21287. return this._colorShader;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  21293. get: function () {
  21294. return false;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  21300. get: function () {
  21301. return false;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  21307. var engine = this.getScene().getEngine();
  21308. var indexToBind = this._geometry.getIndexBuffer();
  21309. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  21310. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  21311. };
  21312. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21313. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21314. return;
  21315. }
  21316. var engine = this.getScene().getEngine();
  21317. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  21318. };
  21319. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  21320. return null;
  21321. };
  21322. LinesMesh.prototype.dispose = function (doNotRecurse) {
  21323. this._colorShader.dispose();
  21324. _super.prototype.dispose.call(this, doNotRecurse);
  21325. };
  21326. return LinesMesh;
  21327. })(BABYLON.Mesh);
  21328. BABYLON.LinesMesh = LinesMesh;
  21329. })(BABYLON || (BABYLON = {}));
  21330. var BABYLON;
  21331. (function (BABYLON) {
  21332. var OutlineRenderer = (function () {
  21333. function OutlineRenderer(scene) {
  21334. this._scene = scene;
  21335. }
  21336. OutlineRenderer.prototype.render = function (subMesh, batch) {
  21337. var scene = this._scene;
  21338. var engine = this._scene.getEngine();
  21339. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  21340. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  21341. return;
  21342. }
  21343. var mesh = subMesh.getRenderingMesh();
  21344. var material = subMesh.getMaterial();
  21345. engine.enableEffect(this._effect);
  21346. this._effect.setFloat("offset", mesh.outlineWidth);
  21347. this._effect.setColor3("color", mesh.outlineColor);
  21348. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21349. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  21350. if (useBones) {
  21351. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  21352. }
  21353. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  21354. if (material && material.needAlphaTesting()) {
  21355. var alphaTexture = material.getAlphaTestTexture();
  21356. this._effect.setTexture("diffuseSampler", alphaTexture);
  21357. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  21358. }
  21359. if (hardwareInstancedRendering) {
  21360. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  21361. } else {
  21362. if (batch.renderSelf[subMesh._id]) {
  21363. this._effect.setMatrix("world", mesh.getWorldMatrix());
  21364. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21365. }
  21366. if (batch.visibleInstances[subMesh._id]) {
  21367. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21368. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21369. this._effect.setMatrix("world", instance.getWorldMatrix());
  21370. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21371. }
  21372. }
  21373. }
  21374. };
  21375. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  21376. var defines = [];
  21377. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  21378. var mesh = subMesh.getMesh();
  21379. var material = subMesh.getMaterial();
  21380. if (material && material.needAlphaTesting()) {
  21381. defines.push("#define ALPHATEST");
  21382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21383. attribs.push(BABYLON.VertexBuffer.UVKind);
  21384. defines.push("#define UV1");
  21385. }
  21386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21388. defines.push("#define UV2");
  21389. }
  21390. }
  21391. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21394. defines.push("#define BONES");
  21395. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21396. }
  21397. if (useInstances) {
  21398. defines.push("#define INSTANCES");
  21399. attribs.push("world0");
  21400. attribs.push("world1");
  21401. attribs.push("world2");
  21402. attribs.push("world3");
  21403. }
  21404. var join = defines.join("\n");
  21405. if (this._cachedDefines != join) {
  21406. this._cachedDefines = join;
  21407. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  21408. }
  21409. return this._effect.isReady();
  21410. };
  21411. return OutlineRenderer;
  21412. })();
  21413. BABYLON.OutlineRenderer = OutlineRenderer;
  21414. })(BABYLON || (BABYLON = {}));
  21415. var BABYLON;
  21416. (function (BABYLON) {
  21417. var MeshAssetTask = (function () {
  21418. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  21419. this.name = name;
  21420. this.meshesNames = meshesNames;
  21421. this.rootUrl = rootUrl;
  21422. this.sceneFilename = sceneFilename;
  21423. this.isCompleted = false;
  21424. }
  21425. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21426. var _this = this;
  21427. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  21428. _this.loadedMeshes = meshes;
  21429. _this.loadedParticleSystems = particleSystems;
  21430. _this.loadedSkeletons = skeletons;
  21431. _this.isCompleted = true;
  21432. if (_this.onSuccess) {
  21433. _this.onSuccess(_this);
  21434. }
  21435. onSuccess();
  21436. }, null, function () {
  21437. if (_this.onError) {
  21438. _this.onError(_this);
  21439. }
  21440. onError();
  21441. });
  21442. };
  21443. return MeshAssetTask;
  21444. })();
  21445. BABYLON.MeshAssetTask = MeshAssetTask;
  21446. var TextFileAssetTask = (function () {
  21447. function TextFileAssetTask(name, url) {
  21448. this.name = name;
  21449. this.url = url;
  21450. this.isCompleted = false;
  21451. }
  21452. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21453. var _this = this;
  21454. BABYLON.Tools.LoadFile(this.url, function (data) {
  21455. _this.text = data;
  21456. _this.isCompleted = true;
  21457. if (_this.onSuccess) {
  21458. _this.onSuccess(_this);
  21459. }
  21460. onSuccess();
  21461. }, null, scene.database, false, function () {
  21462. if (_this.onError) {
  21463. _this.onError(_this);
  21464. }
  21465. onError();
  21466. });
  21467. };
  21468. return TextFileAssetTask;
  21469. })();
  21470. BABYLON.TextFileAssetTask = TextFileAssetTask;
  21471. var BinaryFileAssetTask = (function () {
  21472. function BinaryFileAssetTask(name, url) {
  21473. this.name = name;
  21474. this.url = url;
  21475. this.isCompleted = false;
  21476. }
  21477. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21478. var _this = this;
  21479. BABYLON.Tools.LoadFile(this.url, function (data) {
  21480. _this.data = data;
  21481. _this.isCompleted = true;
  21482. if (_this.onSuccess) {
  21483. _this.onSuccess(_this);
  21484. }
  21485. onSuccess();
  21486. }, null, scene.database, true, function () {
  21487. if (_this.onError) {
  21488. _this.onError(_this);
  21489. }
  21490. onError();
  21491. });
  21492. };
  21493. return BinaryFileAssetTask;
  21494. })();
  21495. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21496. var ImageAssetTask = (function () {
  21497. function ImageAssetTask(name, url) {
  21498. this.name = name;
  21499. this.url = url;
  21500. this.isCompleted = false;
  21501. }
  21502. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21503. var _this = this;
  21504. var img = new Image();
  21505. img.onload = function () {
  21506. _this.image = img;
  21507. _this.isCompleted = true;
  21508. if (_this.onSuccess) {
  21509. _this.onSuccess(_this);
  21510. }
  21511. onSuccess();
  21512. };
  21513. img.onerror = function () {
  21514. if (_this.onError) {
  21515. _this.onError(_this);
  21516. }
  21517. onError();
  21518. };
  21519. img.src = this.url;
  21520. };
  21521. return ImageAssetTask;
  21522. })();
  21523. BABYLON.ImageAssetTask = ImageAssetTask;
  21524. var TextureAssetTask = (function () {
  21525. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21526. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21527. this.name = name;
  21528. this.url = url;
  21529. this.noMipmap = noMipmap;
  21530. this.invertY = invertY;
  21531. this.samplingMode = samplingMode;
  21532. this.isCompleted = false;
  21533. }
  21534. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21535. var _this = this;
  21536. var onload = function () {
  21537. _this.isCompleted = true;
  21538. if (_this.onSuccess) {
  21539. _this.onSuccess(_this);
  21540. }
  21541. onSuccess();
  21542. };
  21543. var onerror = function () {
  21544. if (_this.onError) {
  21545. _this.onError(_this);
  21546. }
  21547. onError();
  21548. };
  21549. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21550. };
  21551. return TextureAssetTask;
  21552. })();
  21553. BABYLON.TextureAssetTask = TextureAssetTask;
  21554. var AssetsManager = (function () {
  21555. function AssetsManager(scene) {
  21556. this._tasks = new Array();
  21557. this._waitingTasksCount = 0;
  21558. this.useDefaultLoadingScreen = true;
  21559. this._scene = scene;
  21560. }
  21561. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21562. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21563. this._tasks.push(task);
  21564. return task;
  21565. };
  21566. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21567. var task = new TextFileAssetTask(taskName, url);
  21568. this._tasks.push(task);
  21569. return task;
  21570. };
  21571. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21572. var task = new BinaryFileAssetTask(taskName, url);
  21573. this._tasks.push(task);
  21574. return task;
  21575. };
  21576. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21577. var task = new ImageAssetTask(taskName, url);
  21578. this._tasks.push(task);
  21579. return task;
  21580. };
  21581. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21582. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21583. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21584. this._tasks.push(task);
  21585. return task;
  21586. };
  21587. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21588. this._waitingTasksCount--;
  21589. if (this._waitingTasksCount === 0) {
  21590. if (this.onFinish) {
  21591. this.onFinish(this._tasks);
  21592. }
  21593. this._scene.getEngine().hideLoadingUI();
  21594. }
  21595. };
  21596. AssetsManager.prototype._runTask = function (task) {
  21597. var _this = this;
  21598. task.run(this._scene, function () {
  21599. if (_this.onTaskSuccess) {
  21600. _this.onTaskSuccess(task);
  21601. }
  21602. _this._decreaseWaitingTasksCount();
  21603. }, function () {
  21604. if (_this.onTaskError) {
  21605. _this.onTaskError(task);
  21606. }
  21607. _this._decreaseWaitingTasksCount();
  21608. });
  21609. };
  21610. AssetsManager.prototype.reset = function () {
  21611. this._tasks = new Array();
  21612. return this;
  21613. };
  21614. AssetsManager.prototype.load = function () {
  21615. this._waitingTasksCount = this._tasks.length;
  21616. if (this._waitingTasksCount === 0) {
  21617. if (this.onFinish) {
  21618. this.onFinish(this._tasks);
  21619. }
  21620. return this;
  21621. }
  21622. if (this.useDefaultLoadingScreen) {
  21623. this._scene.getEngine().displayLoadingUI();
  21624. }
  21625. for (var index = 0; index < this._tasks.length; index++) {
  21626. var task = this._tasks[index];
  21627. this._runTask(task);
  21628. }
  21629. return this;
  21630. };
  21631. return AssetsManager;
  21632. })();
  21633. BABYLON.AssetsManager = AssetsManager;
  21634. })(BABYLON || (BABYLON = {}));
  21635. var __extends = this.__extends || function (d, b) {
  21636. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21637. function __() { this.constructor = d; }
  21638. __.prototype = b.prototype;
  21639. d.prototype = new __();
  21640. };
  21641. var BABYLON;
  21642. (function (BABYLON) {
  21643. var VRDeviceOrientationCamera = (function (_super) {
  21644. __extends(VRDeviceOrientationCamera, _super);
  21645. function VRDeviceOrientationCamera(name, position, scene) {
  21646. _super.call(this, name, position, scene);
  21647. this._alpha = 0;
  21648. this._beta = 0;
  21649. this._gamma = 0;
  21650. }
  21651. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21652. this._alpha = +evt.alpha | 0;
  21653. this._beta = +evt.beta | 0;
  21654. this._gamma = +evt.gamma | 0;
  21655. if (this._gamma < 0) {
  21656. this._gamma = 90 + this._gamma;
  21657. } else {
  21658. this._gamma = 270 - this._gamma;
  21659. }
  21660. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21661. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21662. this.rotation.z = this._beta / 180.0 * Math.PI;
  21663. };
  21664. return VRDeviceOrientationCamera;
  21665. })(BABYLON.OculusCamera);
  21666. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21667. })(BABYLON || (BABYLON = {}));
  21668. var __extends = this.__extends || function (d, b) {
  21669. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21670. function __() { this.constructor = d; }
  21671. __.prototype = b.prototype;
  21672. d.prototype = new __();
  21673. };
  21674. var BABYLON;
  21675. (function (BABYLON) {
  21676. var WebVRCamera = (function (_super) {
  21677. __extends(WebVRCamera, _super);
  21678. function WebVRCamera(name, position, scene) {
  21679. _super.call(this, name, position, scene);
  21680. this._hmdDevice = null;
  21681. this._sensorDevice = null;
  21682. this._cacheState = null;
  21683. this._cacheQuaternion = new BABYLON.Quaternion();
  21684. this._cacheRotation = BABYLON.Vector3.Zero();
  21685. this._vrEnabled = false;
  21686. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21687. }
  21688. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21689. var size = devices.length;
  21690. var i = 0;
  21691. this._sensorDevice = null;
  21692. this._hmdDevice = null;
  21693. while (i < size && this._hmdDevice === null) {
  21694. if (devices[i] instanceof HMDVRDevice) {
  21695. this._hmdDevice = devices[i];
  21696. }
  21697. i++;
  21698. }
  21699. i = 0;
  21700. while (i < size && this._sensorDevice === null) {
  21701. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21702. this._sensorDevice = devices[i];
  21703. }
  21704. i++;
  21705. }
  21706. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21707. };
  21708. WebVRCamera.prototype._update = function () {
  21709. if (this._vrEnabled) {
  21710. this._cacheState = this._sensorDevice.getState();
  21711. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21712. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21713. this.rotation.x = -this._cacheRotation.z;
  21714. this.rotation.y = -this._cacheRotation.y;
  21715. this.rotation.z = this._cacheRotation.x;
  21716. }
  21717. _super.prototype._update.call(this);
  21718. };
  21719. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21720. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21721. if (navigator.getVRDevices) {
  21722. navigator.getVRDevices().then(this._getWebVRDevices);
  21723. } else if (navigator.mozGetVRDevices) {
  21724. navigator.mozGetVRDevices(this._getWebVRDevices);
  21725. }
  21726. };
  21727. WebVRCamera.prototype.detachControl = function (element) {
  21728. _super.prototype.detachControl.call(this, element);
  21729. this._vrEnabled = false;
  21730. };
  21731. return WebVRCamera;
  21732. })(BABYLON.OculusCamera);
  21733. BABYLON.WebVRCamera = WebVRCamera;
  21734. })(BABYLON || (BABYLON = {}));
  21735. var __extends = this.__extends || function (d, b) {
  21736. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21737. function __() { this.constructor = d; }
  21738. __.prototype = b.prototype;
  21739. d.prototype = new __();
  21740. };
  21741. var BABYLON;
  21742. (function (BABYLON) {
  21743. var SceneOptimization = (function () {
  21744. function SceneOptimization(priority) {
  21745. if (typeof priority === "undefined") { priority = 0; }
  21746. this.priority = priority;
  21747. this.apply = function (scene) {
  21748. return true;
  21749. };
  21750. }
  21751. return SceneOptimization;
  21752. })();
  21753. BABYLON.SceneOptimization = SceneOptimization;
  21754. var TextureOptimization = (function (_super) {
  21755. __extends(TextureOptimization, _super);
  21756. function TextureOptimization(priority, maximumSize) {
  21757. if (typeof priority === "undefined") { priority = 0; }
  21758. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  21759. var _this = this;
  21760. _super.call(this, priority);
  21761. this.priority = priority;
  21762. this.maximumSize = maximumSize;
  21763. this.apply = function (scene) {
  21764. var allDone = true;
  21765. for (var index = 0; index < scene.textures.length; index++) {
  21766. var texture = scene.textures[index];
  21767. if (!texture.canRescale) {
  21768. continue;
  21769. }
  21770. var currentSize = texture.getSize();
  21771. var maxDimension = Math.max(currentSize.width, currentSize.height);
  21772. if (maxDimension > _this.maximumSize) {
  21773. texture.scale(0.5);
  21774. allDone = false;
  21775. }
  21776. }
  21777. return allDone;
  21778. };
  21779. }
  21780. return TextureOptimization;
  21781. })(SceneOptimization);
  21782. BABYLON.TextureOptimization = TextureOptimization;
  21783. var HardwareScalingOptimization = (function (_super) {
  21784. __extends(HardwareScalingOptimization, _super);
  21785. function HardwareScalingOptimization(priority, maximumScale) {
  21786. if (typeof priority === "undefined") { priority = 0; }
  21787. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  21788. var _this = this;
  21789. _super.call(this, priority);
  21790. this.priority = priority;
  21791. this.maximumScale = maximumScale;
  21792. this._currentScale = 1;
  21793. this.apply = function (scene) {
  21794. _this._currentScale++;
  21795. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  21796. return _this._currentScale >= _this.maximumScale;
  21797. };
  21798. }
  21799. return HardwareScalingOptimization;
  21800. })(SceneOptimization);
  21801. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  21802. var ShadowsOptimization = (function (_super) {
  21803. __extends(ShadowsOptimization, _super);
  21804. function ShadowsOptimization() {
  21805. _super.apply(this, arguments);
  21806. this.apply = function (scene) {
  21807. scene.shadowsEnabled = false;
  21808. return true;
  21809. };
  21810. }
  21811. return ShadowsOptimization;
  21812. })(SceneOptimization);
  21813. BABYLON.ShadowsOptimization = ShadowsOptimization;
  21814. var PostProcessesOptimization = (function (_super) {
  21815. __extends(PostProcessesOptimization, _super);
  21816. function PostProcessesOptimization() {
  21817. _super.apply(this, arguments);
  21818. this.apply = function (scene) {
  21819. scene.postProcessesEnabled = false;
  21820. return true;
  21821. };
  21822. }
  21823. return PostProcessesOptimization;
  21824. })(SceneOptimization);
  21825. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  21826. var LensFlaresOptimization = (function (_super) {
  21827. __extends(LensFlaresOptimization, _super);
  21828. function LensFlaresOptimization() {
  21829. _super.apply(this, arguments);
  21830. this.apply = function (scene) {
  21831. scene.lensFlaresEnabled = false;
  21832. return true;
  21833. };
  21834. }
  21835. return LensFlaresOptimization;
  21836. })(SceneOptimization);
  21837. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  21838. var ParticlesOptimization = (function (_super) {
  21839. __extends(ParticlesOptimization, _super);
  21840. function ParticlesOptimization() {
  21841. _super.apply(this, arguments);
  21842. this.apply = function (scene) {
  21843. scene.particlesEnabled = false;
  21844. return true;
  21845. };
  21846. }
  21847. return ParticlesOptimization;
  21848. })(SceneOptimization);
  21849. BABYLON.ParticlesOptimization = ParticlesOptimization;
  21850. var RenderTargetsOptimization = (function (_super) {
  21851. __extends(RenderTargetsOptimization, _super);
  21852. function RenderTargetsOptimization() {
  21853. _super.apply(this, arguments);
  21854. this.apply = function (scene) {
  21855. scene.renderTargetsEnabled = false;
  21856. return true;
  21857. };
  21858. }
  21859. return RenderTargetsOptimization;
  21860. })(SceneOptimization);
  21861. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  21862. var SceneOptimizerOptions = (function () {
  21863. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  21864. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  21865. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  21866. this.targetFrameRate = targetFrameRate;
  21867. this.trackerDuration = trackerDuration;
  21868. this.optimizations = new Array();
  21869. }
  21870. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  21871. var result = new SceneOptimizerOptions(targetFrameRate);
  21872. var priority = 0;
  21873. result.optimizations.push(new ShadowsOptimization(priority));
  21874. result.optimizations.push(new LensFlaresOptimization(priority));
  21875. priority++;
  21876. result.optimizations.push(new PostProcessesOptimization(priority));
  21877. result.optimizations.push(new ParticlesOptimization(priority));
  21878. priority++;
  21879. result.optimizations.push(new TextureOptimization(priority, 1024));
  21880. return result;
  21881. };
  21882. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  21883. var result = new SceneOptimizerOptions(targetFrameRate);
  21884. var priority = 0;
  21885. result.optimizations.push(new ShadowsOptimization(priority));
  21886. result.optimizations.push(new LensFlaresOptimization(priority));
  21887. priority++;
  21888. result.optimizations.push(new PostProcessesOptimization(priority));
  21889. result.optimizations.push(new ParticlesOptimization(priority));
  21890. priority++;
  21891. result.optimizations.push(new TextureOptimization(priority, 512));
  21892. priority++;
  21893. result.optimizations.push(new RenderTargetsOptimization(priority));
  21894. priority++;
  21895. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  21896. return result;
  21897. };
  21898. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  21899. var result = new SceneOptimizerOptions(targetFrameRate);
  21900. var priority = 0;
  21901. result.optimizations.push(new ShadowsOptimization(priority));
  21902. result.optimizations.push(new LensFlaresOptimization(priority));
  21903. priority++;
  21904. result.optimizations.push(new PostProcessesOptimization(priority));
  21905. result.optimizations.push(new ParticlesOptimization(priority));
  21906. priority++;
  21907. result.optimizations.push(new TextureOptimization(priority, 256));
  21908. priority++;
  21909. result.optimizations.push(new RenderTargetsOptimization(priority));
  21910. priority++;
  21911. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  21912. return result;
  21913. };
  21914. return SceneOptimizerOptions;
  21915. })();
  21916. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  21917. var SceneOptimizer = (function () {
  21918. function SceneOptimizer() {
  21919. }
  21920. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  21921. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  21922. if (onSuccess) {
  21923. onSuccess();
  21924. }
  21925. return;
  21926. }
  21927. var allDone = true;
  21928. var noOptimizationApplied = true;
  21929. for (var index = 0; index < options.optimizations.length; index++) {
  21930. var optimization = options.optimizations[index];
  21931. if (optimization.priority === currentPriorityLevel) {
  21932. noOptimizationApplied = false;
  21933. allDone = allDone && optimization.apply(scene);
  21934. }
  21935. }
  21936. if (noOptimizationApplied) {
  21937. if (onFailure) {
  21938. onFailure();
  21939. }
  21940. return;
  21941. }
  21942. if (allDone) {
  21943. currentPriorityLevel++;
  21944. }
  21945. scene.executeWhenReady(function () {
  21946. setTimeout(function () {
  21947. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  21948. }, options.trackerDuration);
  21949. });
  21950. };
  21951. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  21952. if (!options) {
  21953. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  21954. }
  21955. scene.executeWhenReady(function () {
  21956. setTimeout(function () {
  21957. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  21958. }, options.trackerDuration);
  21959. });
  21960. };
  21961. return SceneOptimizer;
  21962. })();
  21963. BABYLON.SceneOptimizer = SceneOptimizer;
  21964. })(BABYLON || (BABYLON = {}));
  21965. var BABYLON;
  21966. (function (BABYLON) {
  21967. (function (Internals) {
  21968. var MeshLODLevel = (function () {
  21969. function MeshLODLevel(distance, mesh) {
  21970. this.distance = distance;
  21971. this.mesh = mesh;
  21972. }
  21973. return MeshLODLevel;
  21974. })();
  21975. Internals.MeshLODLevel = MeshLODLevel;
  21976. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21977. var Internals = BABYLON.Internals;
  21978. })(BABYLON || (BABYLON = {}));