babylon.2.0-alpha.debug.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139
  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, length) {
  1806. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1807. this.origin = origin;
  1808. this.direction = direction;
  1809. this.length = length;
  1810. }
  1811. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1812. var d = 0.0;
  1813. var maxValue = Number.MAX_VALUE;
  1814. if (Math.abs(this.direction.x) < 0.0000001) {
  1815. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1816. return false;
  1817. }
  1818. } else {
  1819. var inv = 1.0 / this.direction.x;
  1820. var min = (minimum.x - this.origin.x) * inv;
  1821. var max = (maximum.x - this.origin.x) * inv;
  1822. if (min > max) {
  1823. var temp = min;
  1824. min = max;
  1825. max = temp;
  1826. }
  1827. d = Math.max(min, d);
  1828. maxValue = Math.min(max, maxValue);
  1829. if (d > maxValue) {
  1830. return false;
  1831. }
  1832. }
  1833. if (Math.abs(this.direction.y) < 0.0000001) {
  1834. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1835. return false;
  1836. }
  1837. } else {
  1838. inv = 1.0 / this.direction.y;
  1839. min = (minimum.y - this.origin.y) * inv;
  1840. max = (maximum.y - this.origin.y) * inv;
  1841. if (min > max) {
  1842. temp = min;
  1843. min = max;
  1844. max = temp;
  1845. }
  1846. d = Math.max(min, d);
  1847. maxValue = Math.min(max, maxValue);
  1848. if (d > maxValue) {
  1849. return false;
  1850. }
  1851. }
  1852. if (Math.abs(this.direction.z) < 0.0000001) {
  1853. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1854. return false;
  1855. }
  1856. } else {
  1857. inv = 1.0 / this.direction.z;
  1858. min = (minimum.z - this.origin.z) * inv;
  1859. max = (maximum.z - this.origin.z) * inv;
  1860. if (min > max) {
  1861. temp = min;
  1862. min = max;
  1863. max = temp;
  1864. }
  1865. d = Math.max(min, d);
  1866. maxValue = Math.min(max, maxValue);
  1867. if (d > maxValue) {
  1868. return false;
  1869. }
  1870. }
  1871. return true;
  1872. };
  1873. Ray.prototype.intersectsBox = function (box) {
  1874. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1875. };
  1876. Ray.prototype.intersectsSphere = function (sphere) {
  1877. var x = sphere.center.x - this.origin.x;
  1878. var y = sphere.center.y - this.origin.y;
  1879. var z = sphere.center.z - this.origin.z;
  1880. var pyth = (x * x) + (y * y) + (z * z);
  1881. var rr = sphere.radius * sphere.radius;
  1882. if (pyth <= rr) {
  1883. return true;
  1884. }
  1885. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1886. if (dot < 0.0) {
  1887. return false;
  1888. }
  1889. var temp = pyth - (dot * dot);
  1890. return temp <= rr;
  1891. };
  1892. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1893. if (!this._edge1) {
  1894. this._edge1 = BABYLON.Vector3.Zero();
  1895. this._edge2 = BABYLON.Vector3.Zero();
  1896. this._pvec = BABYLON.Vector3.Zero();
  1897. this._tvec = BABYLON.Vector3.Zero();
  1898. this._qvec = BABYLON.Vector3.Zero();
  1899. }
  1900. vertex1.subtractToRef(vertex0, this._edge1);
  1901. vertex2.subtractToRef(vertex0, this._edge2);
  1902. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1903. var det = Vector3.Dot(this._edge1, this._pvec);
  1904. if (det === 0) {
  1905. return null;
  1906. }
  1907. var invdet = 1 / det;
  1908. this.origin.subtractToRef(vertex0, this._tvec);
  1909. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1910. if (bu < 0 || bu > 1.0) {
  1911. return null;
  1912. }
  1913. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1914. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1915. if (bv < 0 || bu + bv > 1.0) {
  1916. return null;
  1917. }
  1918. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1919. if (distance > this.length) {
  1920. return null;
  1921. }
  1922. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1923. };
  1924. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1925. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1926. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1927. var direction = end.subtract(start);
  1928. direction.normalize();
  1929. return new Ray(start, direction);
  1930. };
  1931. /**
  1932. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  1933. * transformed to the given world matrix.
  1934. * @param origin The origin point
  1935. * @param end The end point
  1936. * @param world a matrix to transform the ray to. Default is the identity matrix.
  1937. */
  1938. Ray.CreateNewFromTo = function (origin, end, world) {
  1939. if (typeof world === "undefined") { world = BABYLON.Matrix.Identity(); }
  1940. var direction = end.subtract(origin);
  1941. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  1942. direction.normalize();
  1943. return Ray.Transform(new Ray(origin, direction, length), world);
  1944. };
  1945. Ray.Transform = function (ray, matrix) {
  1946. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1947. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1948. return new Ray(newOrigin, newDirection, ray.length);
  1949. };
  1950. return Ray;
  1951. })();
  1952. BABYLON.Ray = Ray;
  1953. (function (Space) {
  1954. Space[Space["LOCAL"] = 0] = "LOCAL";
  1955. Space[Space["WORLD"] = 1] = "WORLD";
  1956. })(BABYLON.Space || (BABYLON.Space = {}));
  1957. var Space = BABYLON.Space;
  1958. var Axis = (function () {
  1959. function Axis() {
  1960. }
  1961. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1962. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1963. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1964. return Axis;
  1965. })();
  1966. BABYLON.Axis = Axis;
  1967. ;
  1968. })(BABYLON || (BABYLON = {}));
  1969. var BABYLON;
  1970. (function (BABYLON) {
  1971. var screenshotCanvas;
  1972. var fpsRange = 60;
  1973. var previousFramesDuration = [];
  1974. var fps = 60;
  1975. var deltaTime = 0;
  1976. var cloneValue = function (source, destinationObject) {
  1977. if (!source)
  1978. return null;
  1979. if (source instanceof BABYLON.Mesh) {
  1980. return null;
  1981. }
  1982. if (source instanceof BABYLON.SubMesh) {
  1983. return source.clone(destinationObject);
  1984. } else if (source.clone) {
  1985. return source.clone();
  1986. }
  1987. return null;
  1988. };
  1989. var Tools = (function () {
  1990. function Tools() {
  1991. }
  1992. Tools.GetFilename = function (path) {
  1993. var index = path.lastIndexOf("/");
  1994. if (index < 0)
  1995. return path;
  1996. return path.substring(index + 1);
  1997. };
  1998. Tools.GetDOMTextContent = function (element) {
  1999. var result = "";
  2000. var child = element.firstChild;
  2001. while (child) {
  2002. if (child.nodeType == 3) {
  2003. result += child.textContent;
  2004. }
  2005. child = child.nextSibling;
  2006. }
  2007. return result;
  2008. };
  2009. Tools.ToDegrees = function (angle) {
  2010. return angle * 180 / Math.PI;
  2011. };
  2012. Tools.ToRadians = function (angle) {
  2013. return angle * Math.PI / 180;
  2014. };
  2015. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2016. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2017. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2018. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2019. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2020. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2021. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2022. }
  2023. return {
  2024. minimum: minimum,
  2025. maximum: maximum
  2026. };
  2027. };
  2028. Tools.ExtractMinAndMax = function (positions, start, count) {
  2029. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2030. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2031. for (var index = start; index < start + count; index++) {
  2032. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2033. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2034. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2035. }
  2036. return {
  2037. minimum: minimum,
  2038. maximum: maximum
  2039. };
  2040. };
  2041. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2042. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2043. return undefined;
  2044. return Array.isArray(obj) ? obj : [obj];
  2045. };
  2046. Tools.GetPointerPrefix = function () {
  2047. var eventPrefix = "pointer";
  2048. if (!navigator.pointerEnabled) {
  2049. eventPrefix = "mouse";
  2050. }
  2051. return eventPrefix;
  2052. };
  2053. Tools.QueueNewFrame = function (func) {
  2054. if (window.requestAnimationFrame)
  2055. window.requestAnimationFrame(func);
  2056. else if (window.msRequestAnimationFrame)
  2057. window.msRequestAnimationFrame(func);
  2058. else if (window.webkitRequestAnimationFrame)
  2059. window.webkitRequestAnimationFrame(func);
  2060. else if (window.mozRequestAnimationFrame)
  2061. window.mozRequestAnimationFrame(func);
  2062. else if (window.oRequestAnimationFrame)
  2063. window.oRequestAnimationFrame(func);
  2064. else {
  2065. window.setTimeout(func, 16);
  2066. }
  2067. };
  2068. Tools.RequestFullscreen = function (element) {
  2069. if (element.requestFullscreen)
  2070. element.requestFullscreen();
  2071. else if (element.msRequestFullscreen)
  2072. element.msRequestFullscreen();
  2073. else if (element.webkitRequestFullscreen)
  2074. element.webkitRequestFullscreen();
  2075. else if (element.mozRequestFullScreen)
  2076. element.mozRequestFullScreen();
  2077. };
  2078. Tools.ExitFullscreen = function () {
  2079. if (document.exitFullscreen) {
  2080. document.exitFullscreen();
  2081. } else if (document.mozCancelFullScreen) {
  2082. document.mozCancelFullScreen();
  2083. } else if (document.webkitCancelFullScreen) {
  2084. document.webkitCancelFullScreen();
  2085. } else if (document.msCancelFullScreen) {
  2086. document.msCancelFullScreen();
  2087. }
  2088. };
  2089. Tools.CleanUrl = function (url) {
  2090. url = url.replace(/#/mg, "%23");
  2091. return url;
  2092. };
  2093. Tools.LoadImage = function (url, onload, onerror, database) {
  2094. url = Tools.CleanUrl(url);
  2095. var img = new Image();
  2096. if (url.substr(0, 5) != "data:")
  2097. img.crossOrigin = 'anonymous';
  2098. img.onload = function () {
  2099. onload(img);
  2100. };
  2101. img.onerror = function (err) {
  2102. onerror(img, err);
  2103. };
  2104. var noIndexedDB = function () {
  2105. img.src = url;
  2106. };
  2107. var loadFromIndexedDB = function () {
  2108. database.loadImageFromDB(url, img);
  2109. };
  2110. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2111. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2112. } else {
  2113. if (url.indexOf("file:") === -1) {
  2114. noIndexedDB();
  2115. } else {
  2116. try {
  2117. var textureName = url.substring(5);
  2118. var blobURL;
  2119. try {
  2120. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2121. } catch (ex) {
  2122. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2123. }
  2124. img.src = blobURL;
  2125. } catch (e) {
  2126. Tools.Log("Error while trying to load texture: " + textureName);
  2127. img.src = null;
  2128. }
  2129. }
  2130. }
  2131. return img;
  2132. };
  2133. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2134. url = Tools.CleanUrl(url);
  2135. var noIndexedDB = function () {
  2136. var request = new XMLHttpRequest();
  2137. var loadUrl = Tools.BaseUrl + url;
  2138. request.open('GET', loadUrl, true);
  2139. if (useArrayBuffer) {
  2140. request.responseType = "arraybuffer";
  2141. }
  2142. request.onprogress = progressCallBack;
  2143. request.onreadystatechange = function () {
  2144. if (request.readyState == 4) {
  2145. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2146. callback(!useArrayBuffer ? request.responseText : request.response);
  2147. } else {
  2148. if (onError) {
  2149. onError();
  2150. } else {
  2151. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2152. }
  2153. }
  2154. }
  2155. };
  2156. request.send(null);
  2157. };
  2158. var loadFromIndexedDB = function () {
  2159. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2160. };
  2161. if (url.indexOf("file:") !== -1) {
  2162. var fileName = url.substring(5);
  2163. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2164. } else {
  2165. if (database && database.enableSceneOffline) {
  2166. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2167. } else {
  2168. noIndexedDB();
  2169. }
  2170. }
  2171. };
  2172. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2173. var reader = new FileReader();
  2174. reader.onload = function (e) {
  2175. callback(e.target.result);
  2176. };
  2177. reader.onprogress = progressCallback;
  2178. reader.readAsDataURL(fileToLoad);
  2179. };
  2180. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2181. var reader = new FileReader();
  2182. reader.onload = function (e) {
  2183. callback(e.target.result);
  2184. };
  2185. reader.onprogress = progressCallBack;
  2186. if (!useArrayBuffer) {
  2187. reader.readAsText(fileToLoad);
  2188. } else {
  2189. reader.readAsArrayBuffer(fileToLoad);
  2190. }
  2191. };
  2192. Tools.CheckExtends = function (v, min, max) {
  2193. if (v.x < min.x)
  2194. min.x = v.x;
  2195. if (v.y < min.y)
  2196. min.y = v.y;
  2197. if (v.z < min.z)
  2198. min.z = v.z;
  2199. if (v.x > max.x)
  2200. max.x = v.x;
  2201. if (v.y > max.y)
  2202. max.y = v.y;
  2203. if (v.z > max.z)
  2204. max.z = v.z;
  2205. };
  2206. Tools.WithinEpsilon = function (a, b) {
  2207. var num = a - b;
  2208. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2209. };
  2210. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2211. for (var prop in source) {
  2212. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2213. continue;
  2214. }
  2215. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2216. continue;
  2217. }
  2218. var sourceValue = source[prop];
  2219. var typeOfSourceValue = typeof sourceValue;
  2220. if (typeOfSourceValue == "function") {
  2221. continue;
  2222. }
  2223. if (typeOfSourceValue == "object") {
  2224. if (sourceValue instanceof Array) {
  2225. destination[prop] = [];
  2226. if (sourceValue.length > 0) {
  2227. if (typeof sourceValue[0] == "object") {
  2228. for (var index = 0; index < sourceValue.length; index++) {
  2229. var clonedValue = cloneValue(sourceValue[index], destination);
  2230. if (destination[prop].indexOf(clonedValue) === -1) {
  2231. destination[prop].push(clonedValue);
  2232. }
  2233. }
  2234. } else {
  2235. destination[prop] = sourceValue.slice(0);
  2236. }
  2237. }
  2238. } else {
  2239. destination[prop] = cloneValue(sourceValue, destination);
  2240. }
  2241. } else {
  2242. destination[prop] = sourceValue;
  2243. }
  2244. }
  2245. };
  2246. Tools.IsEmpty = function (obj) {
  2247. for (var i in obj) {
  2248. return false;
  2249. }
  2250. return true;
  2251. };
  2252. Tools.RegisterTopRootEvents = function (events) {
  2253. for (var index = 0; index < events.length; index++) {
  2254. var event = events[index];
  2255. window.addEventListener(event.name, event.handler, false);
  2256. try {
  2257. if (window.parent) {
  2258. window.parent.addEventListener(event.name, event.handler, false);
  2259. }
  2260. } catch (e) {
  2261. }
  2262. }
  2263. };
  2264. Tools.UnregisterTopRootEvents = function (events) {
  2265. for (var index = 0; index < events.length; index++) {
  2266. var event = events[index];
  2267. window.removeEventListener(event.name, event.handler);
  2268. try {
  2269. if (window.parent) {
  2270. window.parent.removeEventListener(event.name, event.handler);
  2271. }
  2272. } catch (e) {
  2273. }
  2274. }
  2275. };
  2276. Tools.GetFps = function () {
  2277. return fps;
  2278. };
  2279. Tools.GetDeltaTime = function () {
  2280. return deltaTime;
  2281. };
  2282. Tools._MeasureFps = function () {
  2283. previousFramesDuration.push(Tools.Now);
  2284. var length = previousFramesDuration.length;
  2285. if (length >= 2) {
  2286. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2287. }
  2288. if (length >= fpsRange) {
  2289. if (length > fpsRange) {
  2290. previousFramesDuration.splice(0, 1);
  2291. length = previousFramesDuration.length;
  2292. }
  2293. var sum = 0;
  2294. for (var id = 0; id < length - 1; id++) {
  2295. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2296. }
  2297. fps = 1000.0 / (sum / (length - 1));
  2298. }
  2299. };
  2300. Tools.CreateScreenshot = function (engine, camera, size) {
  2301. var width;
  2302. var height;
  2303. var scene = camera.getScene();
  2304. var previousCamera = null;
  2305. if (scene.activeCamera !== camera) {
  2306. previousCamera = scene.activeCamera;
  2307. scene.activeCamera = camera;
  2308. }
  2309. if (size.precision) {
  2310. width = Math.round(engine.getRenderWidth() * size.precision);
  2311. height = Math.round(width / engine.getAspectRatio(camera));
  2312. size = { width: width, height: height };
  2313. } else if (size.width && size.height) {
  2314. width = size.width;
  2315. height = size.height;
  2316. } else if (size.width && !size.height) {
  2317. width = size.width;
  2318. height = Math.round(width / engine.getAspectRatio(camera));
  2319. size = { width: width, height: height };
  2320. } else if (size.height && !size.width) {
  2321. height = size.height;
  2322. width = Math.round(height * engine.getAspectRatio(camera));
  2323. size = { width: width, height: height };
  2324. } else if (!isNaN(size)) {
  2325. height = size;
  2326. width = size;
  2327. } else {
  2328. Tools.Error("Invalid 'size' parameter !");
  2329. return;
  2330. }
  2331. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2332. texture.renderList = engine.scenes[0].meshes;
  2333. texture.onAfterRender = function () {
  2334. var numberOfChannelsByLine = width * 4;
  2335. var halfHeight = height / 2;
  2336. var data = engine.readPixels(0, 0, width, height);
  2337. for (var i = 0; i < halfHeight; i++) {
  2338. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2339. var currentCell = j + i * numberOfChannelsByLine;
  2340. var targetLine = height - i - 1;
  2341. var targetCell = j + targetLine * numberOfChannelsByLine;
  2342. var temp = data[currentCell];
  2343. data[currentCell] = data[targetCell];
  2344. data[targetCell] = temp;
  2345. }
  2346. }
  2347. if (!screenshotCanvas) {
  2348. screenshotCanvas = document.createElement('canvas');
  2349. }
  2350. screenshotCanvas.width = width;
  2351. screenshotCanvas.height = height;
  2352. var context = screenshotCanvas.getContext('2d');
  2353. var imageData = context.createImageData(width, height);
  2354. imageData.data.set(data);
  2355. context.putImageData(imageData, 0, 0);
  2356. var base64Image = screenshotCanvas.toDataURL();
  2357. if (("download" in document.createElement("a"))) {
  2358. var a = window.document.createElement("a");
  2359. a.href = base64Image;
  2360. var date = new Date();
  2361. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2362. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2363. window.document.body.appendChild(a);
  2364. a.addEventListener("click", function () {
  2365. a.parentElement.removeChild(a);
  2366. });
  2367. a.click();
  2368. } else {
  2369. var newWindow = window.open("");
  2370. var img = newWindow.document.createElement("img");
  2371. img.src = base64Image;
  2372. newWindow.document.body.appendChild(img);
  2373. }
  2374. };
  2375. texture.render(true);
  2376. texture.dispose();
  2377. if (previousCamera) {
  2378. scene.activeCamera = previousCamera;
  2379. }
  2380. };
  2381. Tools.ValidateXHRData = function (xhr, dataType) {
  2382. if (typeof dataType === "undefined") { dataType = 7; }
  2383. try {
  2384. if (dataType & 1) {
  2385. if (xhr.responseText && xhr.responseText.length > 0) {
  2386. return true;
  2387. } else if (dataType === 1) {
  2388. return false;
  2389. }
  2390. }
  2391. if (dataType & 2) {
  2392. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2393. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2394. return true;
  2395. } else if (dataType === 2) {
  2396. return false;
  2397. }
  2398. }
  2399. if (dataType & 4) {
  2400. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2401. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2402. return true;
  2403. } else {
  2404. return false;
  2405. }
  2406. }
  2407. } catch (e) {
  2408. }
  2409. return false;
  2410. };
  2411. Object.defineProperty(Tools, "NoneLogLevel", {
  2412. get: function () {
  2413. return Tools._NoneLogLevel;
  2414. },
  2415. enumerable: true,
  2416. configurable: true
  2417. });
  2418. Object.defineProperty(Tools, "MessageLogLevel", {
  2419. get: function () {
  2420. return Tools._MessageLogLevel;
  2421. },
  2422. enumerable: true,
  2423. configurable: true
  2424. });
  2425. Object.defineProperty(Tools, "WarningLogLevel", {
  2426. get: function () {
  2427. return Tools._WarningLogLevel;
  2428. },
  2429. enumerable: true,
  2430. configurable: true
  2431. });
  2432. Object.defineProperty(Tools, "ErrorLogLevel", {
  2433. get: function () {
  2434. return Tools._ErrorLogLevel;
  2435. },
  2436. enumerable: true,
  2437. configurable: true
  2438. });
  2439. Object.defineProperty(Tools, "AllLogLevel", {
  2440. get: function () {
  2441. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2442. },
  2443. enumerable: true,
  2444. configurable: true
  2445. });
  2446. Tools._FormatMessage = function (message) {
  2447. var padStr = function (i) {
  2448. return (i < 10) ? "0" + i : "" + i;
  2449. };
  2450. var date = new Date();
  2451. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2452. };
  2453. Tools._LogDisabled = function (message) {
  2454. };
  2455. Tools._LogEnabled = function (message) {
  2456. console.log(Tools._FormatMessage(message));
  2457. };
  2458. Tools._WarnDisabled = function (message) {
  2459. };
  2460. Tools._WarnEnabled = function (message) {
  2461. console.warn(Tools._FormatMessage(message));
  2462. };
  2463. Tools._ErrorDisabled = function (message) {
  2464. };
  2465. Tools._ErrorEnabled = function (message) {
  2466. console.error(Tools._FormatMessage(message));
  2467. };
  2468. Object.defineProperty(Tools, "LogLevels", {
  2469. set: function (level) {
  2470. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2471. Tools.Log = Tools._LogEnabled;
  2472. } else {
  2473. Tools.Log = Tools._LogDisabled;
  2474. }
  2475. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2476. Tools.Warn = Tools._WarnEnabled;
  2477. } else {
  2478. Tools.Warn = Tools._WarnDisabled;
  2479. }
  2480. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2481. Tools.Error = Tools._ErrorEnabled;
  2482. } else {
  2483. Tools.Error = Tools._ErrorDisabled;
  2484. }
  2485. },
  2486. enumerable: true,
  2487. configurable: true
  2488. });
  2489. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2490. get: function () {
  2491. return Tools._PerformanceNoneLogLevel;
  2492. },
  2493. enumerable: true,
  2494. configurable: true
  2495. });
  2496. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2497. get: function () {
  2498. return Tools._PerformanceUserMarkLogLevel;
  2499. },
  2500. enumerable: true,
  2501. configurable: true
  2502. });
  2503. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2504. get: function () {
  2505. return Tools._PerformanceConsoleLogLevel;
  2506. },
  2507. enumerable: true,
  2508. configurable: true
  2509. });
  2510. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2511. set: function (level) {
  2512. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2513. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2514. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2515. return;
  2516. }
  2517. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2518. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2519. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2520. return;
  2521. }
  2522. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2523. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2524. },
  2525. enumerable: true,
  2526. configurable: true
  2527. });
  2528. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2529. };
  2530. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2531. };
  2532. Tools._StartUserMark = function (counterName, condition) {
  2533. if (typeof condition === "undefined") { condition = true; }
  2534. if (!condition || !Tools._performance.mark) {
  2535. return;
  2536. }
  2537. Tools._performance.mark(counterName + "-Begin");
  2538. };
  2539. Tools._EndUserMark = function (counterName, condition) {
  2540. if (typeof condition === "undefined") { condition = true; }
  2541. if (!condition || !Tools._performance.mark) {
  2542. return;
  2543. }
  2544. Tools._performance.mark(counterName + "-End");
  2545. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2546. };
  2547. Tools._StartPerformanceConsole = function (counterName, condition) {
  2548. if (typeof condition === "undefined") { condition = true; }
  2549. if (!condition) {
  2550. return;
  2551. }
  2552. Tools._StartUserMark(counterName, condition);
  2553. if (console.time) {
  2554. console.time(counterName);
  2555. }
  2556. };
  2557. Tools._EndPerformanceConsole = function (counterName, condition) {
  2558. if (typeof condition === "undefined") { condition = true; }
  2559. if (!condition) {
  2560. return;
  2561. }
  2562. Tools._EndUserMark(counterName, condition);
  2563. if (console.time) {
  2564. console.timeEnd(counterName);
  2565. }
  2566. };
  2567. Object.defineProperty(Tools, "Now", {
  2568. get: function () {
  2569. if (window.performance && window.performance.now) {
  2570. return window.performance.now();
  2571. }
  2572. return new Date().getTime();
  2573. },
  2574. enumerable: true,
  2575. configurable: true
  2576. });
  2577. Tools.BaseUrl = "";
  2578. Tools.GetExponantOfTwo = function (value, max) {
  2579. var count = 1;
  2580. do {
  2581. count *= 2;
  2582. } while(count < value);
  2583. if (count > max)
  2584. count = max;
  2585. return count;
  2586. };
  2587. Tools._NoneLogLevel = 0;
  2588. Tools._MessageLogLevel = 1;
  2589. Tools._WarningLogLevel = 2;
  2590. Tools._ErrorLogLevel = 4;
  2591. Tools.Log = Tools._LogEnabled;
  2592. Tools.Warn = Tools._WarnEnabled;
  2593. Tools.Error = Tools._ErrorEnabled;
  2594. Tools._PerformanceNoneLogLevel = 0;
  2595. Tools._PerformanceUserMarkLogLevel = 1;
  2596. Tools._PerformanceConsoleLogLevel = 2;
  2597. Tools._performance = window.performance;
  2598. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2599. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2600. return Tools;
  2601. })();
  2602. BABYLON.Tools = Tools;
  2603. })(BABYLON || (BABYLON = {}));
  2604. var BABYLON;
  2605. (function (BABYLON) {
  2606. var _DepthCullingState = (function () {
  2607. function _DepthCullingState() {
  2608. this._isDepthTestDirty = false;
  2609. this._isDepthMaskDirty = false;
  2610. this._isDepthFuncDirty = false;
  2611. this._isCullFaceDirty = false;
  2612. this._isCullDirty = false;
  2613. }
  2614. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2615. get: function () {
  2616. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2617. },
  2618. enumerable: true,
  2619. configurable: true
  2620. });
  2621. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2622. get: function () {
  2623. return this._cullFace;
  2624. },
  2625. set: function (value) {
  2626. if (this._cullFace === value) {
  2627. return;
  2628. }
  2629. this._cullFace = value;
  2630. this._isCullFaceDirty = true;
  2631. },
  2632. enumerable: true,
  2633. configurable: true
  2634. });
  2635. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2636. get: function () {
  2637. return this._cull;
  2638. },
  2639. set: function (value) {
  2640. if (this._cull === value) {
  2641. return;
  2642. }
  2643. this._cull = value;
  2644. this._isCullDirty = true;
  2645. },
  2646. enumerable: true,
  2647. configurable: true
  2648. });
  2649. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2650. get: function () {
  2651. return this._depthFunc;
  2652. },
  2653. set: function (value) {
  2654. if (this._depthFunc === value) {
  2655. return;
  2656. }
  2657. this._depthFunc = value;
  2658. this._isDepthFuncDirty = true;
  2659. },
  2660. enumerable: true,
  2661. configurable: true
  2662. });
  2663. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2664. get: function () {
  2665. return this._depthMask;
  2666. },
  2667. set: function (value) {
  2668. if (this._depthMask === value) {
  2669. return;
  2670. }
  2671. this._depthMask = value;
  2672. this._isDepthMaskDirty = true;
  2673. },
  2674. enumerable: true,
  2675. configurable: true
  2676. });
  2677. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2678. get: function () {
  2679. return this._depthTest;
  2680. },
  2681. set: function (value) {
  2682. if (this._depthTest === value) {
  2683. return;
  2684. }
  2685. this._depthTest = value;
  2686. this._isDepthTestDirty = true;
  2687. },
  2688. enumerable: true,
  2689. configurable: true
  2690. });
  2691. _DepthCullingState.prototype.reset = function () {
  2692. this._depthMask = true;
  2693. this._depthTest = true;
  2694. this._depthFunc = null;
  2695. this._cull = null;
  2696. this._cullFace = null;
  2697. this._isDepthTestDirty = true;
  2698. this._isDepthMaskDirty = true;
  2699. this._isDepthFuncDirty = false;
  2700. this._isCullFaceDirty = false;
  2701. this._isCullDirty = false;
  2702. };
  2703. _DepthCullingState.prototype.apply = function (gl) {
  2704. if (!this.isDirty) {
  2705. return;
  2706. }
  2707. if (this._isCullDirty) {
  2708. if (this.cull === true) {
  2709. gl.enable(gl.CULL_FACE);
  2710. } else if (this.cull === false) {
  2711. gl.disable(gl.CULL_FACE);
  2712. }
  2713. this._isCullDirty = false;
  2714. }
  2715. if (this._isCullFaceDirty) {
  2716. gl.cullFace(this.cullFace);
  2717. this._isCullFaceDirty = false;
  2718. }
  2719. if (this._isDepthMaskDirty) {
  2720. gl.depthMask(this.depthMask);
  2721. this._isDepthMaskDirty = false;
  2722. }
  2723. if (this._isDepthTestDirty) {
  2724. if (this.depthTest === true) {
  2725. gl.enable(gl.DEPTH_TEST);
  2726. } else if (this.depthTest === false) {
  2727. gl.disable(gl.DEPTH_TEST);
  2728. }
  2729. this._isDepthTestDirty = false;
  2730. }
  2731. if (this._isDepthFuncDirty) {
  2732. gl.depthFunc(this.depthFunc);
  2733. this._isDepthFuncDirty = false;
  2734. }
  2735. };
  2736. return _DepthCullingState;
  2737. })();
  2738. BABYLON._DepthCullingState = _DepthCullingState;
  2739. var _AlphaState = (function () {
  2740. function _AlphaState() {
  2741. this._isAlphaBlendDirty = false;
  2742. this._isBlendFunctionParametersDirty = false;
  2743. this._alphaBlend = false;
  2744. this._blendFunctionParameters = new Array(4);
  2745. }
  2746. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2747. get: function () {
  2748. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2749. },
  2750. enumerable: true,
  2751. configurable: true
  2752. });
  2753. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2754. get: function () {
  2755. return this._alphaBlend;
  2756. },
  2757. set: function (value) {
  2758. if (this._alphaBlend === value) {
  2759. return;
  2760. }
  2761. this._alphaBlend = value;
  2762. this._isAlphaBlendDirty = true;
  2763. },
  2764. enumerable: true,
  2765. configurable: true
  2766. });
  2767. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2768. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2769. return;
  2770. }
  2771. this._blendFunctionParameters[0] = value0;
  2772. this._blendFunctionParameters[1] = value1;
  2773. this._blendFunctionParameters[2] = value2;
  2774. this._blendFunctionParameters[3] = value3;
  2775. this._isBlendFunctionParametersDirty = true;
  2776. };
  2777. _AlphaState.prototype.reset = function () {
  2778. this._alphaBlend = false;
  2779. this._blendFunctionParameters[0] = null;
  2780. this._blendFunctionParameters[1] = null;
  2781. this._blendFunctionParameters[2] = null;
  2782. this._blendFunctionParameters[3] = null;
  2783. this._isAlphaBlendDirty = true;
  2784. this._isBlendFunctionParametersDirty = false;
  2785. };
  2786. _AlphaState.prototype.apply = function (gl) {
  2787. if (!this.isDirty) {
  2788. return;
  2789. }
  2790. if (this._isAlphaBlendDirty) {
  2791. if (this._alphaBlend === true) {
  2792. gl.enable(gl.BLEND);
  2793. } else if (this._alphaBlend === false) {
  2794. gl.disable(gl.BLEND);
  2795. }
  2796. this._isAlphaBlendDirty = false;
  2797. }
  2798. if (this._isBlendFunctionParametersDirty) {
  2799. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2800. this._isBlendFunctionParametersDirty = false;
  2801. }
  2802. };
  2803. return _AlphaState;
  2804. })();
  2805. BABYLON._AlphaState = _AlphaState;
  2806. var compileShader = function (gl, source, type, defines) {
  2807. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2808. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2809. gl.compileShader(shader);
  2810. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2811. throw new Error(gl.getShaderInfoLog(shader));
  2812. }
  2813. return shader;
  2814. };
  2815. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2816. var magFilter = gl.NEAREST;
  2817. var minFilter = gl.NEAREST;
  2818. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2819. magFilter = gl.LINEAR;
  2820. if (generateMipMaps) {
  2821. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2822. } else {
  2823. minFilter = gl.LINEAR;
  2824. }
  2825. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2826. magFilter = gl.LINEAR;
  2827. if (generateMipMaps) {
  2828. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2829. } else {
  2830. minFilter = gl.LINEAR;
  2831. }
  2832. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2833. magFilter = gl.NEAREST;
  2834. if (generateMipMaps) {
  2835. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2836. } else {
  2837. minFilter = gl.NEAREST;
  2838. }
  2839. }
  2840. return {
  2841. min: minFilter,
  2842. mag: magFilter
  2843. };
  2844. };
  2845. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2846. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2847. var engine = scene.getEngine();
  2848. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2849. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2850. gl.bindTexture(gl.TEXTURE_2D, texture);
  2851. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2852. processFunction(potWidth, potHeight);
  2853. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2856. if (!noMipmap && !isCompressed) {
  2857. gl.generateMipmap(gl.TEXTURE_2D);
  2858. }
  2859. gl.bindTexture(gl.TEXTURE_2D, null);
  2860. engine._activeTexturesCache = [];
  2861. texture._baseWidth = width;
  2862. texture._baseHeight = height;
  2863. texture._width = potWidth;
  2864. texture._height = potHeight;
  2865. texture.isReady = true;
  2866. scene._removePendingData(texture);
  2867. };
  2868. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2869. var img;
  2870. var onload = function () {
  2871. loadedImages[index] = img;
  2872. loadedImages._internalCount++;
  2873. scene._removePendingData(img);
  2874. if (loadedImages._internalCount == 6) {
  2875. onfinish(loadedImages);
  2876. }
  2877. };
  2878. var onerror = function () {
  2879. scene._removePendingData(img);
  2880. };
  2881. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2882. scene._addPendingData(img);
  2883. };
  2884. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2885. var loadedImages = [];
  2886. loadedImages._internalCount = 0;
  2887. for (var index = 0; index < 6; index++) {
  2888. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2889. }
  2890. };
  2891. var EngineCapabilities = (function () {
  2892. function EngineCapabilities() {
  2893. }
  2894. return EngineCapabilities;
  2895. })();
  2896. BABYLON.EngineCapabilities = EngineCapabilities;
  2897. var Engine = (function () {
  2898. function Engine(canvas, antialias, options) {
  2899. var _this = this;
  2900. this.isFullscreen = false;
  2901. this.isPointerLock = false;
  2902. this.forceWireframe = false;
  2903. this.cullBackFaces = true;
  2904. this.renderEvenInBackground = true;
  2905. this.scenes = new Array();
  2906. this._windowIsBackground = false;
  2907. this._runningLoop = false;
  2908. this._loadingDivBackgroundColor = "black";
  2909. this._depthCullingState = new _DepthCullingState();
  2910. this._alphaState = new _AlphaState();
  2911. this._loadedTexturesCache = new Array();
  2912. this._activeTexturesCache = new Array();
  2913. this._compiledEffects = {};
  2914. this._uintIndicesCurrentlySet = false;
  2915. this._renderingCanvas = canvas;
  2916. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2917. options = options || {};
  2918. options.antialias = antialias;
  2919. try {
  2920. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2921. } catch (e) {
  2922. throw new Error("WebGL not supported");
  2923. }
  2924. if (!this._gl) {
  2925. throw new Error("WebGL not supported");
  2926. }
  2927. this._onBlur = function () {
  2928. _this._windowIsBackground = true;
  2929. };
  2930. this._onFocus = function () {
  2931. _this._windowIsBackground = false;
  2932. };
  2933. window.addEventListener("blur", this._onBlur);
  2934. window.addEventListener("focus", this._onFocus);
  2935. this._workingCanvas = document.createElement("canvas");
  2936. this._workingContext = this._workingCanvas.getContext("2d");
  2937. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  2938. this.resize();
  2939. this._caps = new EngineCapabilities();
  2940. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  2941. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  2942. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  2943. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  2944. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  2945. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  2946. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  2947. 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');
  2948. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  2949. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  2950. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  2951. this.setDepthBuffer(true);
  2952. this.setDepthFunctionToLessOrEqual();
  2953. this.setDepthWrite(true);
  2954. this._onFullscreenChange = function () {
  2955. if (document.fullscreen !== undefined) {
  2956. _this.isFullscreen = document.fullscreen;
  2957. } else if (document.mozFullScreen !== undefined) {
  2958. _this.isFullscreen = document.mozFullScreen;
  2959. } else if (document.webkitIsFullScreen !== undefined) {
  2960. _this.isFullscreen = document.webkitIsFullScreen;
  2961. } else if (document.msIsFullScreen !== undefined) {
  2962. _this.isFullscreen = document.msIsFullScreen;
  2963. }
  2964. if (_this.isFullscreen && _this._pointerLockRequested) {
  2965. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  2966. if (canvas.requestPointerLock) {
  2967. canvas.requestPointerLock();
  2968. }
  2969. }
  2970. };
  2971. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  2972. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  2973. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  2974. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  2975. this._onPointerLockChange = function () {
  2976. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  2977. };
  2978. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  2979. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  2980. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  2981. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  2982. }
  2983. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  2984. get: function () {
  2985. return Engine._ALPHA_DISABLE;
  2986. },
  2987. enumerable: true,
  2988. configurable: true
  2989. });
  2990. Object.defineProperty(Engine, "ALPHA_ADD", {
  2991. get: function () {
  2992. return Engine._ALPHA_ADD;
  2993. },
  2994. enumerable: true,
  2995. configurable: true
  2996. });
  2997. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  2998. get: function () {
  2999. return Engine._ALPHA_COMBINE;
  3000. },
  3001. enumerable: true,
  3002. configurable: true
  3003. });
  3004. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3005. get: function () {
  3006. return Engine._DELAYLOADSTATE_NONE;
  3007. },
  3008. enumerable: true,
  3009. configurable: true
  3010. });
  3011. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3012. get: function () {
  3013. return Engine._DELAYLOADSTATE_LOADED;
  3014. },
  3015. enumerable: true,
  3016. configurable: true
  3017. });
  3018. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3019. get: function () {
  3020. return Engine._DELAYLOADSTATE_LOADING;
  3021. },
  3022. enumerable: true,
  3023. configurable: true
  3024. });
  3025. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3026. get: function () {
  3027. return Engine._DELAYLOADSTATE_NOTLOADED;
  3028. },
  3029. enumerable: true,
  3030. configurable: true
  3031. });
  3032. Object.defineProperty(Engine, "Version", {
  3033. get: function () {
  3034. return "2.0.0";
  3035. },
  3036. enumerable: true,
  3037. configurable: true
  3038. });
  3039. Engine.prototype.getAspectRatio = function (camera) {
  3040. var viewport = camera.viewport;
  3041. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3042. };
  3043. Engine.prototype.getRenderWidth = function () {
  3044. if (this._currentRenderTarget) {
  3045. return this._currentRenderTarget._width;
  3046. }
  3047. return this._renderingCanvas.width;
  3048. };
  3049. Engine.prototype.getRenderHeight = function () {
  3050. if (this._currentRenderTarget) {
  3051. return this._currentRenderTarget._height;
  3052. }
  3053. return this._renderingCanvas.height;
  3054. };
  3055. Engine.prototype.getRenderingCanvas = function () {
  3056. return this._renderingCanvas;
  3057. };
  3058. Engine.prototype.getRenderingCanvasClientRect = function () {
  3059. return this._renderingCanvas.getBoundingClientRect();
  3060. };
  3061. Engine.prototype.setHardwareScalingLevel = function (level) {
  3062. this._hardwareScalingLevel = level;
  3063. this.resize();
  3064. };
  3065. Engine.prototype.getHardwareScalingLevel = function () {
  3066. return this._hardwareScalingLevel;
  3067. };
  3068. Engine.prototype.getLoadedTexturesCache = function () {
  3069. return this._loadedTexturesCache;
  3070. };
  3071. Engine.prototype.getCaps = function () {
  3072. return this._caps;
  3073. };
  3074. Engine.prototype.setDepthFunctionToGreater = function () {
  3075. this._depthCullingState.depthFunc = this._gl.GREATER;
  3076. };
  3077. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3078. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3079. };
  3080. Engine.prototype.setDepthFunctionToLess = function () {
  3081. this._depthCullingState.depthFunc = this._gl.LESS;
  3082. };
  3083. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3084. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3085. };
  3086. Engine.prototype.stopRenderLoop = function () {
  3087. this._renderFunction = null;
  3088. this._runningLoop = false;
  3089. };
  3090. Engine.prototype._renderLoop = function () {
  3091. var _this = this;
  3092. var shouldRender = true;
  3093. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3094. shouldRender = false;
  3095. }
  3096. if (shouldRender) {
  3097. this.beginFrame();
  3098. if (this._renderFunction) {
  3099. this._renderFunction();
  3100. }
  3101. this.endFrame();
  3102. }
  3103. if (this._runningLoop) {
  3104. BABYLON.Tools.QueueNewFrame(function () {
  3105. _this._renderLoop();
  3106. });
  3107. }
  3108. };
  3109. Engine.prototype.runRenderLoop = function (renderFunction) {
  3110. var _this = this;
  3111. this._runningLoop = true;
  3112. this._renderFunction = renderFunction;
  3113. BABYLON.Tools.QueueNewFrame(function () {
  3114. _this._renderLoop();
  3115. });
  3116. };
  3117. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3118. if (this.isFullscreen) {
  3119. BABYLON.Tools.ExitFullscreen();
  3120. } else {
  3121. this._pointerLockRequested = requestPointerLock;
  3122. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3123. }
  3124. };
  3125. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3126. this.applyStates();
  3127. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3128. if (this._depthCullingState.depthMask) {
  3129. this._gl.clearDepth(1.0);
  3130. }
  3131. var mode = 0;
  3132. if (backBuffer)
  3133. mode |= this._gl.COLOR_BUFFER_BIT;
  3134. if (depthStencil && this._depthCullingState.depthMask)
  3135. mode |= this._gl.DEPTH_BUFFER_BIT;
  3136. this._gl.clear(mode);
  3137. };
  3138. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3139. var width = requiredWidth || this._renderingCanvas.width;
  3140. var height = requiredHeight || this._renderingCanvas.height;
  3141. var x = viewport.x || 0;
  3142. var y = viewport.y || 0;
  3143. this._cachedViewport = viewport;
  3144. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3145. };
  3146. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3147. this._cachedViewport = null;
  3148. this._gl.viewport(x, y, width, height);
  3149. };
  3150. Engine.prototype.beginFrame = function () {
  3151. BABYLON.Tools._MeasureFps();
  3152. };
  3153. Engine.prototype.endFrame = function () {
  3154. this.flushFramebuffer();
  3155. };
  3156. Engine.prototype.resize = function () {
  3157. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3158. };
  3159. Engine.prototype.setSize = function (width, height) {
  3160. this._renderingCanvas.width = width;
  3161. this._renderingCanvas.height = height;
  3162. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3163. };
  3164. Engine.prototype.bindFramebuffer = function (texture) {
  3165. this._currentRenderTarget = texture;
  3166. var gl = this._gl;
  3167. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3168. this._gl.viewport(0, 0, texture._width, texture._height);
  3169. this.wipeCaches();
  3170. };
  3171. Engine.prototype.unBindFramebuffer = function (texture) {
  3172. this._currentRenderTarget = null;
  3173. if (texture.generateMipMaps) {
  3174. var gl = this._gl;
  3175. gl.bindTexture(gl.TEXTURE_2D, texture);
  3176. gl.generateMipmap(gl.TEXTURE_2D);
  3177. gl.bindTexture(gl.TEXTURE_2D, null);
  3178. }
  3179. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3180. };
  3181. Engine.prototype.flushFramebuffer = function () {
  3182. this._gl.flush();
  3183. };
  3184. Engine.prototype.restoreDefaultFramebuffer = function () {
  3185. this._currentRenderTarget = null;
  3186. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3187. this.setViewport(this._cachedViewport);
  3188. this.wipeCaches();
  3189. };
  3190. Engine.prototype._resetVertexBufferBinding = function () {
  3191. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3192. this._cachedVertexBuffers = null;
  3193. };
  3194. Engine.prototype.createVertexBuffer = function (vertices) {
  3195. var vbo = this._gl.createBuffer();
  3196. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3197. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3198. this._resetVertexBufferBinding();
  3199. vbo.references = 1;
  3200. return vbo;
  3201. };
  3202. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3203. var vbo = this._gl.createBuffer();
  3204. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3205. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3206. this._resetVertexBufferBinding();
  3207. vbo.references = 1;
  3208. return vbo;
  3209. };
  3210. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3212. if (vertices instanceof Float32Array) {
  3213. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3214. } else {
  3215. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3216. }
  3217. this._resetVertexBufferBinding();
  3218. };
  3219. Engine.prototype._resetIndexBufferBinding = function () {
  3220. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3221. this._cachedIndexBuffer = null;
  3222. };
  3223. Engine.prototype.createIndexBuffer = function (indices) {
  3224. var vbo = this._gl.createBuffer();
  3225. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3226. var arrayBuffer;
  3227. var need32Bits = false;
  3228. if (this._caps.uintIndices) {
  3229. for (var index = 0; index < indices.length; index++) {
  3230. if (indices[index] > 65535) {
  3231. need32Bits = true;
  3232. break;
  3233. }
  3234. }
  3235. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3236. } else {
  3237. arrayBuffer = new Uint16Array(indices);
  3238. }
  3239. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3240. this._resetIndexBufferBinding();
  3241. vbo.references = 1;
  3242. vbo.is32Bits = need32Bits;
  3243. return vbo;
  3244. };
  3245. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3246. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3247. this._cachedVertexBuffers = vertexBuffer;
  3248. this._cachedEffectForVertexBuffers = effect;
  3249. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3250. var offset = 0;
  3251. for (var index = 0; index < vertexDeclaration.length; index++) {
  3252. var order = effect.getAttributeLocation(index);
  3253. if (order >= 0) {
  3254. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3255. }
  3256. offset += vertexDeclaration[index] * 4;
  3257. }
  3258. }
  3259. if (this._cachedIndexBuffer !== indexBuffer) {
  3260. this._cachedIndexBuffer = indexBuffer;
  3261. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3262. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3263. }
  3264. };
  3265. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3266. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3267. this._cachedVertexBuffers = vertexBuffers;
  3268. this._cachedEffectForVertexBuffers = effect;
  3269. var attributes = effect.getAttributesNames();
  3270. for (var index = 0; index < attributes.length; index++) {
  3271. var order = effect.getAttributeLocation(index);
  3272. if (order >= 0) {
  3273. var vertexBuffer = vertexBuffers[attributes[index]];
  3274. if (!vertexBuffer) {
  3275. continue;
  3276. }
  3277. var stride = vertexBuffer.getStrideSize();
  3278. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3279. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3280. }
  3281. }
  3282. }
  3283. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3284. this._cachedIndexBuffer = indexBuffer;
  3285. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3286. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3287. }
  3288. };
  3289. Engine.prototype._releaseBuffer = function (buffer) {
  3290. buffer.references--;
  3291. if (buffer.references === 0) {
  3292. this._gl.deleteBuffer(buffer);
  3293. return true;
  3294. }
  3295. return false;
  3296. };
  3297. Engine.prototype.createInstancesBuffer = function (capacity) {
  3298. var buffer = this._gl.createBuffer();
  3299. buffer.capacity = capacity;
  3300. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3301. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3302. return buffer;
  3303. };
  3304. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3305. this._gl.deleteBuffer(buffer);
  3306. };
  3307. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3308. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3309. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3310. for (var index = 0; index < 4; index++) {
  3311. var offsetLocation = offsetLocations[index];
  3312. this._gl.enableVertexAttribArray(offsetLocation);
  3313. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3314. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3315. }
  3316. };
  3317. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3318. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3319. for (var index = 0; index < 4; index++) {
  3320. var offsetLocation = offsetLocations[index];
  3321. this._gl.disableVertexAttribArray(offsetLocation);
  3322. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3323. }
  3324. };
  3325. Engine.prototype.applyStates = function () {
  3326. this._depthCullingState.apply(this._gl);
  3327. this._alphaState.apply(this._gl);
  3328. };
  3329. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3330. this.applyStates();
  3331. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3332. if (instancesCount) {
  3333. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3334. return;
  3335. }
  3336. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3337. };
  3338. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3339. this.applyStates();
  3340. if (instancesCount) {
  3341. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3342. return;
  3343. }
  3344. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3345. };
  3346. Engine.prototype._releaseEffect = function (effect) {
  3347. if (this._compiledEffects[effect._key]) {
  3348. delete this._compiledEffects[effect._key];
  3349. if (effect.getProgram()) {
  3350. this._gl.deleteProgram(effect.getProgram());
  3351. }
  3352. }
  3353. };
  3354. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3355. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3356. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3357. var name = vertex + "+" + fragment + "@" + defines;
  3358. if (this._compiledEffects[name]) {
  3359. return this._compiledEffects[name];
  3360. }
  3361. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3362. effect._key = name;
  3363. this._compiledEffects[name] = effect;
  3364. return effect;
  3365. };
  3366. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3367. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3368. if (typeof samplers === "undefined") { samplers = []; }
  3369. if (typeof defines === "undefined") { defines = ""; }
  3370. return this.createEffect({
  3371. vertex: "particles",
  3372. fragmentElement: fragmentName
  3373. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3374. };
  3375. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3376. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3377. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3378. var shaderProgram = this._gl.createProgram();
  3379. this._gl.attachShader(shaderProgram, vertexShader);
  3380. this._gl.attachShader(shaderProgram, fragmentShader);
  3381. this._gl.linkProgram(shaderProgram);
  3382. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3383. if (!linked) {
  3384. var error = this._gl.getProgramInfoLog(shaderProgram);
  3385. if (error) {
  3386. throw new Error(error);
  3387. }
  3388. }
  3389. this._gl.deleteShader(vertexShader);
  3390. this._gl.deleteShader(fragmentShader);
  3391. return shaderProgram;
  3392. };
  3393. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3394. var results = [];
  3395. for (var index = 0; index < uniformsNames.length; index++) {
  3396. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3397. }
  3398. return results;
  3399. };
  3400. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3401. var results = [];
  3402. for (var index = 0; index < attributesNames.length; index++) {
  3403. try {
  3404. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3405. } catch (e) {
  3406. results.push(-1);
  3407. }
  3408. }
  3409. return results;
  3410. };
  3411. Engine.prototype.enableEffect = function (effect) {
  3412. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3413. if (effect && effect.onBind) {
  3414. effect.onBind(effect);
  3415. }
  3416. return;
  3417. }
  3418. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3419. this._gl.useProgram(effect.getProgram());
  3420. for (var i in this._vertexAttribArrays) {
  3421. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3422. continue;
  3423. }
  3424. this._vertexAttribArrays[i] = false;
  3425. this._gl.disableVertexAttribArray(i);
  3426. }
  3427. var attributesCount = effect.getAttributesCount();
  3428. for (var index = 0; index < attributesCount; index++) {
  3429. var order = effect.getAttributeLocation(index);
  3430. if (order >= 0) {
  3431. this._vertexAttribArrays[order] = true;
  3432. this._gl.enableVertexAttribArray(order);
  3433. }
  3434. }
  3435. this._currentEffect = effect;
  3436. if (effect.onBind) {
  3437. effect.onBind(effect);
  3438. }
  3439. };
  3440. Engine.prototype.setArray = function (uniform, array) {
  3441. if (!uniform)
  3442. return;
  3443. this._gl.uniform1fv(uniform, array);
  3444. };
  3445. Engine.prototype.setMatrices = function (uniform, matrices) {
  3446. if (!uniform)
  3447. return;
  3448. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3449. };
  3450. Engine.prototype.setMatrix = function (uniform, matrix) {
  3451. if (!uniform)
  3452. return;
  3453. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3454. };
  3455. Engine.prototype.setFloat = function (uniform, value) {
  3456. if (!uniform)
  3457. return;
  3458. this._gl.uniform1f(uniform, value);
  3459. };
  3460. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3461. if (!uniform)
  3462. return;
  3463. this._gl.uniform2f(uniform, x, y);
  3464. };
  3465. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3466. if (!uniform)
  3467. return;
  3468. this._gl.uniform3f(uniform, x, y, z);
  3469. };
  3470. Engine.prototype.setBool = function (uniform, bool) {
  3471. if (!uniform)
  3472. return;
  3473. this._gl.uniform1i(uniform, bool);
  3474. };
  3475. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3476. if (!uniform)
  3477. return;
  3478. this._gl.uniform4f(uniform, x, y, z, w);
  3479. };
  3480. Engine.prototype.setColor3 = function (uniform, color3) {
  3481. if (!uniform)
  3482. return;
  3483. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3484. };
  3485. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3486. if (!uniform)
  3487. return;
  3488. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3489. };
  3490. Engine.prototype.setState = function (culling, force) {
  3491. if (this._depthCullingState.cull !== culling || force) {
  3492. if (culling) {
  3493. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3494. this._depthCullingState.cull = true;
  3495. } else {
  3496. this._depthCullingState.cull = false;
  3497. }
  3498. }
  3499. };
  3500. Engine.prototype.setDepthBuffer = function (enable) {
  3501. this._depthCullingState.depthTest = enable;
  3502. };
  3503. Engine.prototype.getDepthWrite = function () {
  3504. return this._depthCullingState.depthMask;
  3505. };
  3506. Engine.prototype.setDepthWrite = function (enable) {
  3507. this._depthCullingState.depthMask = enable;
  3508. };
  3509. Engine.prototype.setColorWrite = function (enable) {
  3510. this._gl.colorMask(enable, enable, enable, enable);
  3511. };
  3512. Engine.prototype.setAlphaMode = function (mode) {
  3513. switch (mode) {
  3514. case BABYLON.Engine.ALPHA_DISABLE:
  3515. this.setDepthWrite(true);
  3516. this._alphaState.alphaBlend = false;
  3517. break;
  3518. case BABYLON.Engine.ALPHA_COMBINE:
  3519. this.setDepthWrite(false);
  3520. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3521. this._alphaState.alphaBlend = true;
  3522. break;
  3523. case BABYLON.Engine.ALPHA_ADD:
  3524. this.setDepthWrite(false);
  3525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3526. this._alphaState.alphaBlend = true;
  3527. break;
  3528. }
  3529. };
  3530. Engine.prototype.setAlphaTesting = function (enable) {
  3531. this._alphaTest = enable;
  3532. };
  3533. Engine.prototype.getAlphaTesting = function () {
  3534. return this._alphaTest;
  3535. };
  3536. Engine.prototype.wipeCaches = function () {
  3537. this._activeTexturesCache = [];
  3538. this._currentEffect = null;
  3539. this._depthCullingState.reset();
  3540. this._alphaState.reset();
  3541. this._cachedVertexBuffers = null;
  3542. this._cachedIndexBuffer = null;
  3543. this._cachedEffectForVertexBuffers = null;
  3544. };
  3545. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3546. var gl = this._gl;
  3547. gl.bindTexture(gl.TEXTURE_2D, texture);
  3548. var magFilter = gl.NEAREST;
  3549. var minFilter = gl.NEAREST;
  3550. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3551. magFilter = gl.LINEAR;
  3552. minFilter = gl.LINEAR;
  3553. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3554. magFilter = gl.LINEAR;
  3555. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3556. }
  3557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3559. gl.bindTexture(gl.TEXTURE_2D, null);
  3560. };
  3561. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3562. var _this = this;
  3563. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3564. if (typeof onLoad === "undefined") { onLoad = null; }
  3565. if (typeof onError === "undefined") { onError = null; }
  3566. if (typeof buffer === "undefined") { buffer = null; }
  3567. var texture = this._gl.createTexture();
  3568. var extension;
  3569. var fromData = false;
  3570. if (url.substr(0, 5) === "data:") {
  3571. fromData = true;
  3572. }
  3573. if (!fromData)
  3574. extension = url.substr(url.length - 4, 4).toLowerCase();
  3575. else {
  3576. var oldUrl = url;
  3577. fromData = oldUrl.split(':');
  3578. url = oldUrl;
  3579. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3580. }
  3581. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3582. var isTGA = (extension === ".tga");
  3583. scene._addPendingData(texture);
  3584. texture.url = url;
  3585. texture.noMipmap = noMipmap;
  3586. texture.references = 1;
  3587. this._loadedTexturesCache.push(texture);
  3588. var onerror = function () {
  3589. scene._removePendingData(texture);
  3590. if (onError) {
  3591. onError();
  3592. }
  3593. };
  3594. if (isTGA) {
  3595. var callback = function (arrayBuffer) {
  3596. var data = new Uint8Array(arrayBuffer);
  3597. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3598. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3599. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3600. if (onLoad) {
  3601. onLoad();
  3602. }
  3603. }, samplingMode);
  3604. };
  3605. if (!(fromData instanceof Array))
  3606. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3607. callback(arrayBuffer);
  3608. }, onerror, scene.database, true);
  3609. else
  3610. callback(buffer);
  3611. } else if (isDDS) {
  3612. callback = function (data) {
  3613. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3614. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3615. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3616. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3617. if (onLoad) {
  3618. onLoad();
  3619. }
  3620. }, samplingMode);
  3621. };
  3622. if (!(fromData instanceof Array))
  3623. BABYLON.Tools.LoadFile(url, function (data) {
  3624. callback(data);
  3625. }, onerror, scene.database, true);
  3626. else
  3627. callback(buffer);
  3628. } else {
  3629. var onload = function (img) {
  3630. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3631. var isPot = (img.width == potWidth && img.height == potHeight);
  3632. if (!isPot) {
  3633. _this._workingCanvas.width = potWidth;
  3634. _this._workingCanvas.height = potHeight;
  3635. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3636. }
  3637. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3638. if (onLoad) {
  3639. onLoad();
  3640. }
  3641. }, samplingMode);
  3642. };
  3643. if (!(fromData instanceof Array))
  3644. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3645. else
  3646. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3647. }
  3648. return texture;
  3649. };
  3650. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3651. var texture = this._gl.createTexture();
  3652. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3653. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3654. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3655. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3656. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3658. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3659. this._activeTexturesCache = [];
  3660. texture._baseWidth = width;
  3661. texture._baseHeight = height;
  3662. texture._width = width;
  3663. texture._height = height;
  3664. texture.isReady = false;
  3665. texture.generateMipMaps = generateMipMaps;
  3666. texture.references = 1;
  3667. this._loadedTexturesCache.push(texture);
  3668. return texture;
  3669. };
  3670. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3671. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3672. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3673. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3674. if (texture.generateMipMaps) {
  3675. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3676. }
  3677. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3678. this._activeTexturesCache = [];
  3679. texture.isReady = true;
  3680. };
  3681. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3682. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3683. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3684. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3685. if (!texture._workingCanvas) {
  3686. texture._workingCanvas = document.createElement("canvas");
  3687. texture._workingContext = texture._workingCanvas.getContext("2d");
  3688. texture._workingCanvas.width = texture._width;
  3689. texture._workingCanvas.height = texture._height;
  3690. }
  3691. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3692. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3693. } else {
  3694. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3695. }
  3696. if (texture.generateMipMaps) {
  3697. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3698. }
  3699. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3700. this._activeTexturesCache = [];
  3701. texture.isReady = true;
  3702. };
  3703. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3704. var generateMipMaps = false;
  3705. var generateDepthBuffer = true;
  3706. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3707. if (options !== undefined) {
  3708. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3709. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3710. if (options.samplingMode !== undefined) {
  3711. samplingMode = options.samplingMode;
  3712. }
  3713. }
  3714. var gl = this._gl;
  3715. var texture = gl.createTexture();
  3716. gl.bindTexture(gl.TEXTURE_2D, texture);
  3717. var width = size.width || size;
  3718. var height = size.height || size;
  3719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3720. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3721. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3722. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3724. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3725. var depthBuffer;
  3726. if (generateDepthBuffer) {
  3727. depthBuffer = gl.createRenderbuffer();
  3728. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3729. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3730. }
  3731. var framebuffer = gl.createFramebuffer();
  3732. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3733. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3734. if (generateDepthBuffer) {
  3735. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3736. }
  3737. gl.bindTexture(gl.TEXTURE_2D, null);
  3738. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3739. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3740. texture._framebuffer = framebuffer;
  3741. if (generateDepthBuffer) {
  3742. texture._depthBuffer = depthBuffer;
  3743. }
  3744. texture._width = width;
  3745. texture._height = height;
  3746. texture.isReady = true;
  3747. texture.generateMipMaps = generateMipMaps;
  3748. texture.references = 1;
  3749. this._activeTexturesCache = [];
  3750. this._loadedTexturesCache.push(texture);
  3751. return texture;
  3752. };
  3753. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3754. var _this = this;
  3755. var gl = this._gl;
  3756. var texture = gl.createTexture();
  3757. texture.isCube = true;
  3758. texture.url = rootUrl;
  3759. texture.references = 1;
  3760. this._loadedTexturesCache.push(texture);
  3761. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3762. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3763. if (isDDS) {
  3764. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3765. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3766. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3767. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3768. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3769. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3770. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3771. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3772. }
  3773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3777. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3778. _this._activeTexturesCache = [];
  3779. texture._width = info.width;
  3780. texture._height = info.height;
  3781. texture.isReady = true;
  3782. }, null, null, true);
  3783. } else {
  3784. cascadeLoad(rootUrl, scene, function (imgs) {
  3785. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3786. var height = width;
  3787. _this._workingCanvas.width = width;
  3788. _this._workingCanvas.height = height;
  3789. var faces = [
  3790. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3791. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3792. ];
  3793. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3794. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3795. for (var index = 0; index < faces.length; index++) {
  3796. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3797. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3798. }
  3799. if (!noMipmap) {
  3800. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3801. }
  3802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3807. _this._activeTexturesCache = [];
  3808. texture._width = width;
  3809. texture._height = height;
  3810. texture.isReady = true;
  3811. }, extensions);
  3812. }
  3813. return texture;
  3814. };
  3815. Engine.prototype._releaseTexture = function (texture) {
  3816. var gl = this._gl;
  3817. if (texture._framebuffer) {
  3818. gl.deleteFramebuffer(texture._framebuffer);
  3819. }
  3820. if (texture._depthBuffer) {
  3821. gl.deleteRenderbuffer(texture._depthBuffer);
  3822. }
  3823. gl.deleteTexture(texture);
  3824. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3825. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3826. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3827. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3828. this._activeTexturesCache[channel] = null;
  3829. }
  3830. var index = this._loadedTexturesCache.indexOf(texture);
  3831. if (index !== -1) {
  3832. this._loadedTexturesCache.splice(index, 1);
  3833. }
  3834. };
  3835. Engine.prototype.bindSamplers = function (effect) {
  3836. this._gl.useProgram(effect.getProgram());
  3837. var samplers = effect.getSamplers();
  3838. for (var index = 0; index < samplers.length; index++) {
  3839. var uniform = effect.getUniform(samplers[index]);
  3840. this._gl.uniform1i(uniform, index);
  3841. }
  3842. this._currentEffect = null;
  3843. };
  3844. Engine.prototype._bindTexture = function (channel, texture) {
  3845. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3846. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3847. this._activeTexturesCache[channel] = null;
  3848. };
  3849. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3850. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3851. };
  3852. Engine.prototype.setTexture = function (channel, texture) {
  3853. if (channel < 0) {
  3854. return;
  3855. }
  3856. if (!texture || !texture.isReady()) {
  3857. if (this._activeTexturesCache[channel] != null) {
  3858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3859. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3860. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3861. this._activeTexturesCache[channel] = null;
  3862. }
  3863. return;
  3864. }
  3865. if (texture instanceof BABYLON.VideoTexture) {
  3866. if (texture.update()) {
  3867. this._activeTexturesCache[channel] = null;
  3868. }
  3869. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3870. texture.delayLoad();
  3871. return;
  3872. }
  3873. if (this._activeTexturesCache[channel] == texture) {
  3874. return;
  3875. }
  3876. this._activeTexturesCache[channel] = texture;
  3877. var internalTexture = texture.getInternalTexture();
  3878. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3879. if (internalTexture.isCube) {
  3880. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3881. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3882. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3883. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3884. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3885. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3886. }
  3887. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3888. } else {
  3889. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3890. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3891. internalTexture._cachedWrapU = texture.wrapU;
  3892. switch (texture.wrapU) {
  3893. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3894. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3895. break;
  3896. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3898. break;
  3899. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3900. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3901. break;
  3902. }
  3903. }
  3904. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3905. internalTexture._cachedWrapV = texture.wrapV;
  3906. switch (texture.wrapV) {
  3907. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3909. break;
  3910. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3912. break;
  3913. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3915. break;
  3916. }
  3917. }
  3918. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3919. }
  3920. };
  3921. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  3922. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3923. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  3924. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  3925. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  3926. }
  3927. };
  3928. Engine.prototype.readPixels = function (x, y, width, height) {
  3929. var data = new Uint8Array(height * width * 4);
  3930. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3931. return data;
  3932. };
  3933. Engine.prototype.dispose = function () {
  3934. this.hideLoadingUI();
  3935. this.stopRenderLoop();
  3936. while (this.scenes.length) {
  3937. this.scenes[0].dispose();
  3938. }
  3939. for (var name in this._compiledEffects) {
  3940. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3941. }
  3942. for (var i in this._vertexAttribArrays) {
  3943. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3944. continue;
  3945. }
  3946. this._gl.disableVertexAttribArray(i);
  3947. }
  3948. window.removeEventListener("blur", this._onBlur);
  3949. window.removeEventListener("focus", this._onFocus);
  3950. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3951. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3952. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3953. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3954. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3955. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3956. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3957. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3958. };
  3959. Engine.prototype.displayLoadingUI = function () {
  3960. var _this = this;
  3961. this._loadingDiv = document.createElement("div");
  3962. this._loadingDiv.style.opacity = "0";
  3963. this._loadingDiv.style.transition = "opacity 1.5s ease";
  3964. this._loadingTextDiv = document.createElement("div");
  3965. this._loadingTextDiv.style.position = "absolute";
  3966. this._loadingTextDiv.style.left = "0";
  3967. this._loadingTextDiv.style.top = "50%";
  3968. this._loadingTextDiv.style.marginTop = "80px";
  3969. this._loadingTextDiv.style.width = "100%";
  3970. this._loadingTextDiv.style.height = "20px";
  3971. this._loadingTextDiv.style.fontFamily = "Arial";
  3972. this._loadingTextDiv.style.fontSize = "14px";
  3973. this._loadingTextDiv.style.color = "white";
  3974. this._loadingTextDiv.style.textAlign = "center";
  3975. this._loadingTextDiv.innerHTML = "Loading";
  3976. this._loadingDiv.appendChild(this._loadingTextDiv);
  3977. var imgBack = new Image();
  3978. 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==";
  3979. imgBack.style.position = "absolute";
  3980. imgBack.style.left = "50%";
  3981. imgBack.style.top = "50%";
  3982. imgBack.style.marginLeft = "-50px";
  3983. imgBack.style.marginTop = "-50px";
  3984. imgBack.style.transition = "transform 1.0s ease";
  3985. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  3986. var deg = 360;
  3987. var onTransitionEnd = function () {
  3988. deg += 360;
  3989. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  3990. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  3991. };
  3992. imgBack.addEventListener("transitionend", onTransitionEnd);
  3993. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  3994. this._loadingDiv.appendChild(imgBack);
  3995. var imgFront = new Image();
  3996. 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=";
  3997. imgFront.style.position = "absolute";
  3998. imgFront.style.left = "50%";
  3999. imgFront.style.top = "50%";
  4000. imgFront.style.marginLeft = "-50px";
  4001. imgFront.style.marginTop = "-50px";
  4002. this._loadingDiv.appendChild(imgFront);
  4003. this._resizeLoadingUI = function () {
  4004. var canvasRect = _this.getRenderingCanvasClientRect();
  4005. _this._loadingDiv.style.position = "absolute";
  4006. _this._loadingDiv.style.left = canvasRect.left + "px";
  4007. _this._loadingDiv.style.top = canvasRect.top + "px";
  4008. _this._loadingDiv.style.width = canvasRect.width + "px";
  4009. _this._loadingDiv.style.height = canvasRect.height + "px";
  4010. };
  4011. this._resizeLoadingUI();
  4012. window.addEventListener("resize", this._resizeLoadingUI);
  4013. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4014. document.body.appendChild(this._loadingDiv);
  4015. setTimeout(function () {
  4016. _this._loadingDiv.style.opacity = "1";
  4017. imgBack.style.transform = "rotateZ(360deg)";
  4018. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4019. }, 0);
  4020. };
  4021. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4022. set: function (text) {
  4023. if (!this._loadingDiv) {
  4024. return;
  4025. }
  4026. this._loadingTextDiv.innerHTML = text;
  4027. },
  4028. enumerable: true,
  4029. configurable: true
  4030. });
  4031. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4032. get: function () {
  4033. return this._loadingDivBackgroundColor;
  4034. },
  4035. set: function (color) {
  4036. this._loadingDivBackgroundColor = color;
  4037. if (!this._loadingDiv) {
  4038. return;
  4039. }
  4040. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4041. },
  4042. enumerable: true,
  4043. configurable: true
  4044. });
  4045. Engine.prototype.hideLoadingUI = function () {
  4046. var _this = this;
  4047. if (!this._loadingDiv) {
  4048. return;
  4049. }
  4050. var onTransitionEnd = function () {
  4051. if (!_this._loadingDiv) {
  4052. return;
  4053. }
  4054. document.body.removeChild(_this._loadingDiv);
  4055. window.removeEventListener("resize", _this._resizeLoadingUI);
  4056. _this._loadingDiv = null;
  4057. };
  4058. this._loadingDiv.style.opacity = "0";
  4059. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4060. };
  4061. Engine.isSupported = function () {
  4062. try {
  4063. if (navigator.isCocoonJS) {
  4064. return true;
  4065. }
  4066. var tempcanvas = document.createElement("canvas");
  4067. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4068. return gl != null && !!window.WebGLRenderingContext;
  4069. } catch (e) {
  4070. return false;
  4071. }
  4072. };
  4073. Engine._ALPHA_DISABLE = 0;
  4074. Engine._ALPHA_ADD = 1;
  4075. Engine._ALPHA_COMBINE = 2;
  4076. Engine._DELAYLOADSTATE_NONE = 0;
  4077. Engine._DELAYLOADSTATE_LOADED = 1;
  4078. Engine._DELAYLOADSTATE_LOADING = 2;
  4079. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4080. Engine.Epsilon = 0.001;
  4081. Engine.CollisionsEpsilon = 0.001;
  4082. Engine.ShadersRepository = "Babylon/Shaders/";
  4083. return Engine;
  4084. })();
  4085. BABYLON.Engine = Engine;
  4086. })(BABYLON || (BABYLON = {}));
  4087. var BABYLON;
  4088. (function (BABYLON) {
  4089. var Node = (function () {
  4090. function Node(name, scene) {
  4091. this.state = "";
  4092. this.animations = new Array();
  4093. this._childrenFlag = -1;
  4094. this._isEnabled = true;
  4095. this._isReady = true;
  4096. this._currentRenderId = -1;
  4097. this.name = name;
  4098. this.id = name;
  4099. this._scene = scene;
  4100. this._initCache();
  4101. }
  4102. Node.prototype.getScene = function () {
  4103. return this._scene;
  4104. };
  4105. Node.prototype.getEngine = function () {
  4106. return this._scene.getEngine();
  4107. };
  4108. Node.prototype.getWorldMatrix = function () {
  4109. return BABYLON.Matrix.Identity();
  4110. };
  4111. Node.prototype._initCache = function () {
  4112. this._cache = {};
  4113. this._cache.parent = undefined;
  4114. };
  4115. Node.prototype.updateCache = function (force) {
  4116. if (!force && this.isSynchronized())
  4117. return;
  4118. this._cache.parent = this.parent;
  4119. this._updateCache();
  4120. };
  4121. Node.prototype._updateCache = function (ignoreParentClass) {
  4122. };
  4123. Node.prototype._isSynchronized = function () {
  4124. return true;
  4125. };
  4126. Node.prototype.isSynchronizedWithParent = function () {
  4127. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4128. };
  4129. Node.prototype.isSynchronized = function (updateCache) {
  4130. var check = this.hasNewParent();
  4131. check = check || !this.isSynchronizedWithParent();
  4132. check = check || !this._isSynchronized();
  4133. if (updateCache)
  4134. this.updateCache(true);
  4135. return !check;
  4136. };
  4137. Node.prototype.hasNewParent = function (update) {
  4138. if (this._cache.parent === this.parent)
  4139. return false;
  4140. if (update)
  4141. this._cache.parent = this.parent;
  4142. return true;
  4143. };
  4144. Node.prototype.isReady = function () {
  4145. return this._isReady;
  4146. };
  4147. Node.prototype.isEnabled = function () {
  4148. if (!this._isEnabled) {
  4149. return false;
  4150. }
  4151. if (this.parent) {
  4152. return this.parent.isEnabled();
  4153. }
  4154. return true;
  4155. };
  4156. Node.prototype.setEnabled = function (value) {
  4157. this._isEnabled = value;
  4158. };
  4159. Node.prototype.isDescendantOf = function (ancestor) {
  4160. if (this.parent) {
  4161. if (this.parent === ancestor) {
  4162. return true;
  4163. }
  4164. return this.parent.isDescendantOf(ancestor);
  4165. }
  4166. return false;
  4167. };
  4168. Node.prototype._getDescendants = function (list, results) {
  4169. for (var index = 0; index < list.length; index++) {
  4170. var item = list[index];
  4171. if (item.isDescendantOf(this)) {
  4172. results.push(item);
  4173. }
  4174. }
  4175. };
  4176. Node.prototype.getDescendants = function () {
  4177. var results = [];
  4178. this._getDescendants(this._scene.meshes, results);
  4179. this._getDescendants(this._scene.lights, results);
  4180. this._getDescendants(this._scene.cameras, results);
  4181. return results;
  4182. };
  4183. Node.prototype._setReady = function (state) {
  4184. if (state == this._isReady) {
  4185. return;
  4186. }
  4187. if (!state) {
  4188. this._isReady = false;
  4189. return;
  4190. }
  4191. this._isReady = true;
  4192. if (this.onReady) {
  4193. this.onReady(this);
  4194. }
  4195. };
  4196. return Node;
  4197. })();
  4198. BABYLON.Node = Node;
  4199. })(BABYLON || (BABYLON = {}));
  4200. var BABYLON;
  4201. (function (BABYLON) {
  4202. var BoundingSphere = (function () {
  4203. function BoundingSphere(minimum, maximum) {
  4204. this.minimum = minimum;
  4205. this.maximum = maximum;
  4206. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4207. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4208. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4209. this.radius = distance * 0.5;
  4210. this.centerWorld = BABYLON.Vector3.Zero();
  4211. this._update(BABYLON.Matrix.Identity());
  4212. }
  4213. BoundingSphere.prototype._update = function (world) {
  4214. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4215. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4216. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4217. };
  4218. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4219. for (var i = 0; i < 6; i++) {
  4220. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4221. return false;
  4222. }
  4223. return true;
  4224. };
  4225. BoundingSphere.prototype.intersectsPoint = function (point) {
  4226. var x = this.centerWorld.x - point.x;
  4227. var y = this.centerWorld.y - point.y;
  4228. var z = this.centerWorld.z - point.z;
  4229. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4230. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4231. return false;
  4232. return true;
  4233. };
  4234. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4235. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4236. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4237. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4238. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4239. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4240. return false;
  4241. return true;
  4242. };
  4243. return BoundingSphere;
  4244. })();
  4245. BABYLON.BoundingSphere = BoundingSphere;
  4246. })(BABYLON || (BABYLON = {}));
  4247. var BABYLON;
  4248. (function (BABYLON) {
  4249. var BoundingBox = (function () {
  4250. function BoundingBox(minimum, maximum) {
  4251. this.minimum = minimum;
  4252. this.maximum = maximum;
  4253. this.vectors = new Array();
  4254. this.vectorsWorld = new Array();
  4255. this.vectors.push(this.minimum.clone());
  4256. this.vectors.push(this.maximum.clone());
  4257. this.vectors.push(this.minimum.clone());
  4258. this.vectors[2].x = this.maximum.x;
  4259. this.vectors.push(this.minimum.clone());
  4260. this.vectors[3].y = this.maximum.y;
  4261. this.vectors.push(this.minimum.clone());
  4262. this.vectors[4].z = this.maximum.z;
  4263. this.vectors.push(this.maximum.clone());
  4264. this.vectors[5].z = this.minimum.z;
  4265. this.vectors.push(this.maximum.clone());
  4266. this.vectors[6].x = this.minimum.x;
  4267. this.vectors.push(this.maximum.clone());
  4268. this.vectors[7].y = this.minimum.y;
  4269. this.center = this.maximum.add(this.minimum).scale(0.5);
  4270. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4271. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4272. for (var index = 0; index < this.vectors.length; index++) {
  4273. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4274. }
  4275. this.minimumWorld = BABYLON.Vector3.Zero();
  4276. this.maximumWorld = BABYLON.Vector3.Zero();
  4277. this._update(BABYLON.Matrix.Identity());
  4278. }
  4279. BoundingBox.prototype.getWorldMatrix = function () {
  4280. return this._worldMatrix;
  4281. };
  4282. BoundingBox.prototype._update = function (world) {
  4283. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4284. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4285. for (var index = 0; index < this.vectors.length; index++) {
  4286. var v = this.vectorsWorld[index];
  4287. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4288. if (v.x < this.minimumWorld.x)
  4289. this.minimumWorld.x = v.x;
  4290. if (v.y < this.minimumWorld.y)
  4291. this.minimumWorld.y = v.y;
  4292. if (v.z < this.minimumWorld.z)
  4293. this.minimumWorld.z = v.z;
  4294. if (v.x > this.maximumWorld.x)
  4295. this.maximumWorld.x = v.x;
  4296. if (v.y > this.maximumWorld.y)
  4297. this.maximumWorld.y = v.y;
  4298. if (v.z > this.maximumWorld.z)
  4299. this.maximumWorld.z = v.z;
  4300. }
  4301. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4302. this.center.scaleInPlace(0.5);
  4303. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4304. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4305. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4306. this._worldMatrix = world;
  4307. };
  4308. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4309. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4310. };
  4311. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4312. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4313. };
  4314. BoundingBox.prototype.intersectsPoint = function (point) {
  4315. var delta = BABYLON.Engine.Epsilon;
  4316. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4317. return false;
  4318. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4319. return false;
  4320. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4321. return false;
  4322. return true;
  4323. };
  4324. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4325. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4326. };
  4327. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4328. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4329. return false;
  4330. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4331. return false;
  4332. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4333. return false;
  4334. return true;
  4335. };
  4336. BoundingBox.Intersects = function (box0, box1) {
  4337. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4338. return false;
  4339. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4340. return false;
  4341. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4342. return false;
  4343. return true;
  4344. };
  4345. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4346. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4347. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4348. return (num <= (sphereRadius * sphereRadius));
  4349. };
  4350. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4351. for (var p = 0; p < 6; p++) {
  4352. for (var i = 0; i < 8; i++) {
  4353. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4354. return false;
  4355. }
  4356. }
  4357. }
  4358. return true;
  4359. };
  4360. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4361. for (var p = 0; p < 6; p++) {
  4362. var inCount = 8;
  4363. for (var i = 0; i < 8; i++) {
  4364. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4365. --inCount;
  4366. } else {
  4367. break;
  4368. }
  4369. }
  4370. if (inCount == 0)
  4371. return false;
  4372. }
  4373. return true;
  4374. };
  4375. return BoundingBox;
  4376. })();
  4377. BABYLON.BoundingBox = BoundingBox;
  4378. })(BABYLON || (BABYLON = {}));
  4379. var BABYLON;
  4380. (function (BABYLON) {
  4381. var computeBoxExtents = function (axis, box) {
  4382. var p = BABYLON.Vector3.Dot(box.center, axis);
  4383. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4384. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4385. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4386. var r = r0 + r1 + r2;
  4387. return {
  4388. min: p - r,
  4389. max: p + r
  4390. };
  4391. };
  4392. var extentsOverlap = function (min0, max0, min1, max1) {
  4393. return !(min0 > max1 || min1 > max0);
  4394. };
  4395. var axisOverlap = function (axis, box0, box1) {
  4396. var result0 = computeBoxExtents(axis, box0);
  4397. var result1 = computeBoxExtents(axis, box1);
  4398. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4399. };
  4400. var BoundingInfo = (function () {
  4401. function BoundingInfo(minimum, maximum) {
  4402. this.minimum = minimum;
  4403. this.maximum = maximum;
  4404. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4405. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4406. }
  4407. BoundingInfo.prototype._update = function (world) {
  4408. this.boundingBox._update(world);
  4409. this.boundingSphere._update(world);
  4410. };
  4411. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4412. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4413. return false;
  4414. return this.boundingBox.isInFrustum(frustumPlanes);
  4415. };
  4416. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4417. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4418. };
  4419. BoundingInfo.prototype._checkCollision = function (collider) {
  4420. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4421. };
  4422. BoundingInfo.prototype.intersectsPoint = function (point) {
  4423. if (!this.boundingSphere.centerWorld) {
  4424. return false;
  4425. }
  4426. if (!this.boundingSphere.intersectsPoint(point)) {
  4427. return false;
  4428. }
  4429. if (!this.boundingBox.intersectsPoint(point)) {
  4430. return false;
  4431. }
  4432. return true;
  4433. };
  4434. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4435. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4436. return false;
  4437. }
  4438. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4439. return false;
  4440. }
  4441. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4442. return false;
  4443. }
  4444. if (!precise) {
  4445. return true;
  4446. }
  4447. var box0 = this.boundingBox;
  4448. var box1 = boundingInfo.boundingBox;
  4449. if (!axisOverlap(box0.directions[0], box0, box1))
  4450. return false;
  4451. if (!axisOverlap(box0.directions[1], box0, box1))
  4452. return false;
  4453. if (!axisOverlap(box0.directions[2], box0, box1))
  4454. return false;
  4455. if (!axisOverlap(box1.directions[0], box0, box1))
  4456. return false;
  4457. if (!axisOverlap(box1.directions[1], box0, box1))
  4458. return false;
  4459. if (!axisOverlap(box1.directions[2], box0, box1))
  4460. return false;
  4461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4462. return false;
  4463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4464. return false;
  4465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4466. return false;
  4467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4468. return false;
  4469. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4470. return false;
  4471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4472. return false;
  4473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4474. return false;
  4475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4476. return false;
  4477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4478. return false;
  4479. return true;
  4480. };
  4481. return BoundingInfo;
  4482. })();
  4483. BABYLON.BoundingInfo = BoundingInfo;
  4484. })(BABYLON || (BABYLON = {}));
  4485. var __extends = this.__extends || function (d, b) {
  4486. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4487. function __() { this.constructor = d; }
  4488. __.prototype = b.prototype;
  4489. d.prototype = new __();
  4490. };
  4491. var BABYLON;
  4492. (function (BABYLON) {
  4493. var Light = (function (_super) {
  4494. __extends(Light, _super);
  4495. function Light(name, scene) {
  4496. _super.call(this, name, scene);
  4497. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4498. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4499. this.intensity = 1.0;
  4500. this.range = Number.MAX_VALUE;
  4501. this.includedOnlyMeshes = new Array();
  4502. this.excludedMeshes = new Array();
  4503. this._excludedMeshesIds = new Array();
  4504. this._includedOnlyMeshesIds = new Array();
  4505. scene.lights.push(this);
  4506. }
  4507. Light.prototype.getShadowGenerator = function () {
  4508. return this._shadowGenerator;
  4509. };
  4510. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4511. };
  4512. Light.prototype._getWorldMatrix = function () {
  4513. return BABYLON.Matrix.Identity();
  4514. };
  4515. Light.prototype.canAffectMesh = function (mesh) {
  4516. if (!mesh) {
  4517. return true;
  4518. }
  4519. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4520. return false;
  4521. }
  4522. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4523. return false;
  4524. }
  4525. return true;
  4526. };
  4527. Light.prototype.getWorldMatrix = function () {
  4528. this._currentRenderId = this.getScene().getRenderId();
  4529. var worldMatrix = this._getWorldMatrix();
  4530. if (this.parent && this.parent.getWorldMatrix) {
  4531. if (!this._parentedWorldMatrix) {
  4532. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4533. }
  4534. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4535. return this._parentedWorldMatrix;
  4536. }
  4537. return worldMatrix;
  4538. };
  4539. Light.prototype.dispose = function () {
  4540. if (this._shadowGenerator) {
  4541. this._shadowGenerator.dispose();
  4542. this._shadowGenerator = null;
  4543. }
  4544. var index = this.getScene().lights.indexOf(this);
  4545. this.getScene().lights.splice(index, 1);
  4546. };
  4547. return Light;
  4548. })(BABYLON.Node);
  4549. BABYLON.Light = Light;
  4550. })(BABYLON || (BABYLON = {}));
  4551. var __extends = this.__extends || function (d, b) {
  4552. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4553. function __() { this.constructor = d; }
  4554. __.prototype = b.prototype;
  4555. d.prototype = new __();
  4556. };
  4557. var BABYLON;
  4558. (function (BABYLON) {
  4559. var PointLight = (function (_super) {
  4560. __extends(PointLight, _super);
  4561. function PointLight(name, position, scene) {
  4562. _super.call(this, name, scene);
  4563. this.position = position;
  4564. }
  4565. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4566. if (this.parent && this.parent.getWorldMatrix) {
  4567. if (!this._transformedPosition) {
  4568. this._transformedPosition = BABYLON.Vector3.Zero();
  4569. }
  4570. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4571. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4572. return;
  4573. }
  4574. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4575. };
  4576. PointLight.prototype.getShadowGenerator = function () {
  4577. return null;
  4578. };
  4579. PointLight.prototype._getWorldMatrix = function () {
  4580. if (!this._worldMatrix) {
  4581. this._worldMatrix = BABYLON.Matrix.Identity();
  4582. }
  4583. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4584. return this._worldMatrix;
  4585. };
  4586. return PointLight;
  4587. })(BABYLON.Light);
  4588. BABYLON.PointLight = PointLight;
  4589. })(BABYLON || (BABYLON = {}));
  4590. var __extends = this.__extends || function (d, b) {
  4591. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4592. function __() { this.constructor = d; }
  4593. __.prototype = b.prototype;
  4594. d.prototype = new __();
  4595. };
  4596. var BABYLON;
  4597. (function (BABYLON) {
  4598. var SpotLight = (function (_super) {
  4599. __extends(SpotLight, _super);
  4600. function SpotLight(name, position, direction, angle, exponent, scene) {
  4601. _super.call(this, name, scene);
  4602. this.position = position;
  4603. this.direction = direction;
  4604. this.angle = angle;
  4605. this.exponent = exponent;
  4606. }
  4607. SpotLight.prototype.setDirectionToTarget = function (target) {
  4608. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4609. return this.direction;
  4610. };
  4611. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4612. var normalizeDirection;
  4613. if (this.parent && this.parent.getWorldMatrix) {
  4614. if (!this._transformedDirection) {
  4615. this._transformedDirection = BABYLON.Vector3.Zero();
  4616. }
  4617. if (!this._transformedPosition) {
  4618. this._transformedPosition = BABYLON.Vector3.Zero();
  4619. }
  4620. var parentWorldMatrix = this.parent.getWorldMatrix();
  4621. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4622. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4623. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4624. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4625. } else {
  4626. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4627. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4628. }
  4629. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4630. };
  4631. SpotLight.prototype._getWorldMatrix = function () {
  4632. if (!this._worldMatrix) {
  4633. this._worldMatrix = BABYLON.Matrix.Identity();
  4634. }
  4635. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4636. return this._worldMatrix;
  4637. };
  4638. return SpotLight;
  4639. })(BABYLON.Light);
  4640. BABYLON.SpotLight = SpotLight;
  4641. })(BABYLON || (BABYLON = {}));
  4642. var __extends = this.__extends || function (d, b) {
  4643. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4644. function __() { this.constructor = d; }
  4645. __.prototype = b.prototype;
  4646. d.prototype = new __();
  4647. };
  4648. var BABYLON;
  4649. (function (BABYLON) {
  4650. var DirectionalLight = (function (_super) {
  4651. __extends(DirectionalLight, _super);
  4652. function DirectionalLight(name, direction, scene) {
  4653. _super.call(this, name, scene);
  4654. this.direction = direction;
  4655. this.position = direction.scale(-1);
  4656. }
  4657. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4658. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4659. return this.direction;
  4660. };
  4661. DirectionalLight.prototype._computeTransformedPosition = function () {
  4662. if (this.parent && this.parent.getWorldMatrix) {
  4663. if (!this._transformedPosition) {
  4664. this._transformedPosition = BABYLON.Vector3.Zero();
  4665. }
  4666. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4667. return true;
  4668. }
  4669. return false;
  4670. };
  4671. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4672. if (this.parent && this.parent.getWorldMatrix) {
  4673. if (!this._transformedDirection) {
  4674. this._transformedDirection = BABYLON.Vector3.Zero();
  4675. }
  4676. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4677. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4678. return;
  4679. }
  4680. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4681. };
  4682. DirectionalLight.prototype._getWorldMatrix = function () {
  4683. if (!this._worldMatrix) {
  4684. this._worldMatrix = BABYLON.Matrix.Identity();
  4685. }
  4686. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4687. return this._worldMatrix;
  4688. };
  4689. return DirectionalLight;
  4690. })(BABYLON.Light);
  4691. BABYLON.DirectionalLight = DirectionalLight;
  4692. })(BABYLON || (BABYLON = {}));
  4693. var BABYLON;
  4694. (function (BABYLON) {
  4695. var ShadowGenerator = (function () {
  4696. function ShadowGenerator(mapSize, light) {
  4697. var _this = this;
  4698. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4699. this._darkness = 0;
  4700. this._transparencyShadow = false;
  4701. this._viewMatrix = BABYLON.Matrix.Zero();
  4702. this._projectionMatrix = BABYLON.Matrix.Zero();
  4703. this._transformMatrix = BABYLON.Matrix.Zero();
  4704. this._worldViewProjection = BABYLON.Matrix.Zero();
  4705. this._light = light;
  4706. this._scene = light.getScene();
  4707. light._shadowGenerator = this;
  4708. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4709. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4710. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4711. this._shadowMap.renderParticles = false;
  4712. var renderSubMesh = function (subMesh) {
  4713. var mesh = subMesh.getRenderingMesh();
  4714. var scene = _this._scene;
  4715. var engine = scene.getEngine();
  4716. engine.setState(subMesh.getMaterial().backFaceCulling);
  4717. var batch = mesh._getInstancesRenderList(subMesh._id);
  4718. if (batch.mustReturn) {
  4719. return;
  4720. }
  4721. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4722. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4723. engine.enableEffect(_this._effect);
  4724. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4725. var material = subMesh.getMaterial();
  4726. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4727. if (material && material.needAlphaTesting()) {
  4728. var alphaTexture = material.getAlphaTestTexture();
  4729. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4730. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4731. }
  4732. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4733. if (useBones) {
  4734. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4735. }
  4736. if (hardwareInstancedRendering) {
  4737. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4738. } else {
  4739. if (batch.renderSelf[subMesh._id]) {
  4740. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4741. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4742. }
  4743. if (batch.visibleInstances[subMesh._id]) {
  4744. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4745. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4746. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4747. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4748. }
  4749. }
  4750. }
  4751. } else {
  4752. _this._shadowMap.resetRefreshCounter();
  4753. }
  4754. };
  4755. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4756. var index;
  4757. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4758. renderSubMesh(opaqueSubMeshes.data[index]);
  4759. }
  4760. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4761. renderSubMesh(alphaTestSubMeshes.data[index]);
  4762. }
  4763. if (_this._transparencyShadow) {
  4764. for (index = 0; index < transparentSubMeshes.length; index++) {
  4765. renderSubMesh(transparentSubMeshes.data[index]);
  4766. }
  4767. }
  4768. };
  4769. }
  4770. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4771. get: function () {
  4772. return ShadowGenerator._FILTER_NONE;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4778. get: function () {
  4779. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4780. },
  4781. enumerable: true,
  4782. configurable: true
  4783. });
  4784. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4785. get: function () {
  4786. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4787. },
  4788. enumerable: true,
  4789. configurable: true
  4790. });
  4791. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4792. get: function () {
  4793. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4794. },
  4795. set: function (value) {
  4796. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4797. },
  4798. enumerable: true,
  4799. configurable: true
  4800. });
  4801. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4802. get: function () {
  4803. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4804. },
  4805. set: function (value) {
  4806. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4807. },
  4808. enumerable: true,
  4809. configurable: true
  4810. });
  4811. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4812. var defines = [];
  4813. if (this.useVarianceShadowMap) {
  4814. defines.push("#define VSM");
  4815. }
  4816. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4817. var mesh = subMesh.getMesh();
  4818. var material = subMesh.getMaterial();
  4819. if (material && material.needAlphaTesting()) {
  4820. defines.push("#define ALPHATEST");
  4821. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4822. attribs.push(BABYLON.VertexBuffer.UVKind);
  4823. defines.push("#define UV1");
  4824. }
  4825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4827. defines.push("#define UV2");
  4828. }
  4829. }
  4830. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4833. defines.push("#define BONES");
  4834. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4835. }
  4836. if (useInstances) {
  4837. defines.push("#define INSTANCES");
  4838. attribs.push("world0");
  4839. attribs.push("world1");
  4840. attribs.push("world2");
  4841. attribs.push("world3");
  4842. }
  4843. var join = defines.join("\n");
  4844. if (this._cachedDefines != join) {
  4845. this._cachedDefines = join;
  4846. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4847. }
  4848. return this._effect.isReady();
  4849. };
  4850. ShadowGenerator.prototype.getShadowMap = function () {
  4851. return this._shadowMap;
  4852. };
  4853. ShadowGenerator.prototype.getLight = function () {
  4854. return this._light;
  4855. };
  4856. ShadowGenerator.prototype.getTransformMatrix = function () {
  4857. var lightPosition = this._light.position;
  4858. var lightDirection = this._light.direction;
  4859. if (this._light._computeTransformedPosition()) {
  4860. lightPosition = this._light._transformedPosition;
  4861. }
  4862. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4863. this._cachedPosition = lightPosition.clone();
  4864. this._cachedDirection = lightDirection.clone();
  4865. var activeCamera = this._scene.activeCamera;
  4866. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4867. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4868. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4869. }
  4870. return this._transformMatrix;
  4871. };
  4872. ShadowGenerator.prototype.getDarkness = function () {
  4873. return this._darkness;
  4874. };
  4875. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4876. if (darkness >= 1.0)
  4877. this._darkness = 1.0;
  4878. else if (darkness <= 0.0)
  4879. this._darkness = 0.0;
  4880. else
  4881. this._darkness = darkness;
  4882. };
  4883. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4884. this._transparencyShadow = hasShadow;
  4885. };
  4886. ShadowGenerator.prototype.dispose = function () {
  4887. this._shadowMap.dispose();
  4888. };
  4889. ShadowGenerator._FILTER_NONE = 0;
  4890. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4891. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4892. return ShadowGenerator;
  4893. })();
  4894. BABYLON.ShadowGenerator = ShadowGenerator;
  4895. })(BABYLON || (BABYLON = {}));
  4896. var __extends = this.__extends || function (d, b) {
  4897. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4898. function __() { this.constructor = d; }
  4899. __.prototype = b.prototype;
  4900. d.prototype = new __();
  4901. };
  4902. var BABYLON;
  4903. (function (BABYLON) {
  4904. var HemisphericLight = (function (_super) {
  4905. __extends(HemisphericLight, _super);
  4906. function HemisphericLight(name, direction, scene) {
  4907. _super.call(this, name, scene);
  4908. this.direction = direction;
  4909. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4910. }
  4911. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  4912. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  4913. return this.direction;
  4914. };
  4915. HemisphericLight.prototype.getShadowGenerator = function () {
  4916. return null;
  4917. };
  4918. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  4919. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4920. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  4921. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  4922. };
  4923. HemisphericLight.prototype._getWorldMatrix = function () {
  4924. if (!this._worldMatrix) {
  4925. this._worldMatrix = BABYLON.Matrix.Identity();
  4926. }
  4927. return this._worldMatrix;
  4928. };
  4929. return HemisphericLight;
  4930. })(BABYLON.Light);
  4931. BABYLON.HemisphericLight = HemisphericLight;
  4932. })(BABYLON || (BABYLON = {}));
  4933. var BABYLON;
  4934. (function (BABYLON) {
  4935. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  4936. if (boxMin.x > sphereCenter.x + sphereRadius)
  4937. return false;
  4938. if (sphereCenter.x - sphereRadius > boxMax.x)
  4939. return false;
  4940. if (boxMin.y > sphereCenter.y + sphereRadius)
  4941. return false;
  4942. if (sphereCenter.y - sphereRadius > boxMax.y)
  4943. return false;
  4944. if (boxMin.z > sphereCenter.z + sphereRadius)
  4945. return false;
  4946. if (sphereCenter.z - sphereRadius > boxMax.z)
  4947. return false;
  4948. return true;
  4949. };
  4950. var getLowestRoot = function (a, b, c, maxR) {
  4951. var determinant = b * b - 4.0 * a * c;
  4952. var result = { root: 0, found: false };
  4953. if (determinant < 0)
  4954. return result;
  4955. var sqrtD = Math.sqrt(determinant);
  4956. var r1 = (-b - sqrtD) / (2.0 * a);
  4957. var r2 = (-b + sqrtD) / (2.0 * a);
  4958. if (r1 > r2) {
  4959. var temp = r2;
  4960. r2 = r1;
  4961. r1 = temp;
  4962. }
  4963. if (r1 > 0 && r1 < maxR) {
  4964. result.root = r1;
  4965. result.found = true;
  4966. return result;
  4967. }
  4968. if (r2 > 0 && r2 < maxR) {
  4969. result.root = r2;
  4970. result.found = true;
  4971. return result;
  4972. }
  4973. return result;
  4974. };
  4975. var Collider = (function () {
  4976. function Collider() {
  4977. this.radius = new BABYLON.Vector3(1, 1, 1);
  4978. this.retry = 0;
  4979. this.basePointWorld = BABYLON.Vector3.Zero();
  4980. this.velocityWorld = BABYLON.Vector3.Zero();
  4981. this.normalizedVelocity = BABYLON.Vector3.Zero();
  4982. this._collisionPoint = BABYLON.Vector3.Zero();
  4983. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  4984. this._tempVector = BABYLON.Vector3.Zero();
  4985. this._tempVector2 = BABYLON.Vector3.Zero();
  4986. this._tempVector3 = BABYLON.Vector3.Zero();
  4987. this._tempVector4 = BABYLON.Vector3.Zero();
  4988. this._edge = BABYLON.Vector3.Zero();
  4989. this._baseToVertex = BABYLON.Vector3.Zero();
  4990. this._destinationPoint = BABYLON.Vector3.Zero();
  4991. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  4992. this._displacementVector = BABYLON.Vector3.Zero();
  4993. }
  4994. Collider.prototype._initialize = function (source, dir, e) {
  4995. this.velocity = dir;
  4996. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  4997. this.basePoint = source;
  4998. source.multiplyToRef(this.radius, this.basePointWorld);
  4999. dir.multiplyToRef(this.radius, this.velocityWorld);
  5000. this.velocityWorldLength = this.velocityWorld.length();
  5001. this.epsilon = e;
  5002. this.collisionFound = false;
  5003. };
  5004. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5005. pa.subtractToRef(point, this._tempVector);
  5006. pb.subtractToRef(point, this._tempVector2);
  5007. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5008. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5009. if (d < 0)
  5010. return false;
  5011. pc.subtractToRef(point, this._tempVector3);
  5012. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5013. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5014. if (d < 0)
  5015. return false;
  5016. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5017. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5018. return d >= 0;
  5019. };
  5020. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5021. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5022. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5023. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5024. return false;
  5025. }
  5026. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5027. return false;
  5028. return true;
  5029. };
  5030. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5031. var t0;
  5032. var embeddedInPlane = false;
  5033. if (!subMesh._trianglePlanes) {
  5034. subMesh._trianglePlanes = [];
  5035. }
  5036. if (!subMesh._trianglePlanes[faceIndex]) {
  5037. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5038. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5039. }
  5040. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5041. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5042. return;
  5043. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5044. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5045. if (normalDotVelocity == 0) {
  5046. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5047. return;
  5048. embeddedInPlane = true;
  5049. t0 = 0;
  5050. } else {
  5051. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5052. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5053. if (t0 > t1) {
  5054. var temp = t1;
  5055. t1 = t0;
  5056. t0 = temp;
  5057. }
  5058. if (t0 > 1.0 || t1 < 0.0)
  5059. return;
  5060. if (t0 < 0)
  5061. t0 = 0;
  5062. if (t0 > 1.0)
  5063. t0 = 1.0;
  5064. }
  5065. this._collisionPoint.copyFromFloats(0, 0, 0);
  5066. var found = false;
  5067. var t = 1.0;
  5068. if (!embeddedInPlane) {
  5069. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5070. this.velocity.scaleToRef(t0, this._tempVector);
  5071. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5072. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5073. found = true;
  5074. t = t0;
  5075. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5076. }
  5077. }
  5078. if (!found) {
  5079. var velocitySquaredLength = this.velocity.lengthSquared();
  5080. var a = velocitySquaredLength;
  5081. this.basePoint.subtractToRef(p1, this._tempVector);
  5082. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5083. var c = this._tempVector.lengthSquared() - 1.0;
  5084. var lowestRoot = getLowestRoot(a, b, c, t);
  5085. if (lowestRoot.found) {
  5086. t = lowestRoot.root;
  5087. found = true;
  5088. this._collisionPoint.copyFrom(p1);
  5089. }
  5090. this.basePoint.subtractToRef(p2, this._tempVector);
  5091. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5092. c = this._tempVector.lengthSquared() - 1.0;
  5093. lowestRoot = getLowestRoot(a, b, c, t);
  5094. if (lowestRoot.found) {
  5095. t = lowestRoot.root;
  5096. found = true;
  5097. this._collisionPoint.copyFrom(p2);
  5098. }
  5099. this.basePoint.subtractToRef(p3, this._tempVector);
  5100. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5101. c = this._tempVector.lengthSquared() - 1.0;
  5102. lowestRoot = getLowestRoot(a, b, c, t);
  5103. if (lowestRoot.found) {
  5104. t = lowestRoot.root;
  5105. found = true;
  5106. this._collisionPoint.copyFrom(p3);
  5107. }
  5108. p2.subtractToRef(p1, this._edge);
  5109. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5110. var edgeSquaredLength = this._edge.lengthSquared();
  5111. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5112. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5113. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5114. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5115. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5116. lowestRoot = getLowestRoot(a, b, c, t);
  5117. if (lowestRoot.found) {
  5118. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5119. if (f >= 0.0 && f <= 1.0) {
  5120. t = lowestRoot.root;
  5121. found = true;
  5122. this._edge.scaleInPlace(f);
  5123. p1.addToRef(this._edge, this._collisionPoint);
  5124. }
  5125. }
  5126. p3.subtractToRef(p2, this._edge);
  5127. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5128. edgeSquaredLength = this._edge.lengthSquared();
  5129. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5130. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5131. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5132. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5133. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5134. lowestRoot = getLowestRoot(a, b, c, t);
  5135. if (lowestRoot.found) {
  5136. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5137. if (f >= 0.0 && f <= 1.0) {
  5138. t = lowestRoot.root;
  5139. found = true;
  5140. this._edge.scaleInPlace(f);
  5141. p2.addToRef(this._edge, this._collisionPoint);
  5142. }
  5143. }
  5144. p1.subtractToRef(p3, this._edge);
  5145. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5146. edgeSquaredLength = this._edge.lengthSquared();
  5147. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5148. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5149. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5150. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5151. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5152. lowestRoot = getLowestRoot(a, b, c, t);
  5153. if (lowestRoot.found) {
  5154. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5155. if (f >= 0.0 && f <= 1.0) {
  5156. t = lowestRoot.root;
  5157. found = true;
  5158. this._edge.scaleInPlace(f);
  5159. p3.addToRef(this._edge, this._collisionPoint);
  5160. }
  5161. }
  5162. }
  5163. if (found) {
  5164. var distToCollision = t * this.velocity.length();
  5165. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5166. if (!this.intersectionPoint) {
  5167. this.intersectionPoint = this._collisionPoint.clone();
  5168. } else {
  5169. this.intersectionPoint.copyFrom(this._collisionPoint);
  5170. }
  5171. this.nearestDistance = distToCollision;
  5172. this.collisionFound = true;
  5173. this.collidedMesh = subMesh.getMesh();
  5174. }
  5175. }
  5176. };
  5177. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5178. for (var i = indexStart; i < indexEnd; i += 3) {
  5179. var p1 = pts[indices[i] - decal];
  5180. var p2 = pts[indices[i + 1] - decal];
  5181. var p3 = pts[indices[i + 2] - decal];
  5182. this._testTriangle(i, subMesh, p3, p2, p1);
  5183. }
  5184. };
  5185. Collider.prototype._getResponse = function (pos, vel) {
  5186. pos.addToRef(vel, this._destinationPoint);
  5187. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5188. this.basePoint.addToRef(vel, pos);
  5189. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5190. this._slidePlaneNormal.normalize();
  5191. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5192. pos.addInPlace(this._displacementVector);
  5193. this.intersectionPoint.addInPlace(this._displacementVector);
  5194. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5195. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5196. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5197. };
  5198. return Collider;
  5199. })();
  5200. BABYLON.Collider = Collider;
  5201. })(BABYLON || (BABYLON = {}));
  5202. var __extends = this.__extends || function (d, b) {
  5203. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5204. function __() { this.constructor = d; }
  5205. __.prototype = b.prototype;
  5206. d.prototype = new __();
  5207. };
  5208. var BABYLON;
  5209. (function (BABYLON) {
  5210. var Camera = (function (_super) {
  5211. __extends(Camera, _super);
  5212. function Camera(name, position, scene) {
  5213. _super.call(this, name, scene);
  5214. this.position = position;
  5215. this.upVector = BABYLON.Vector3.Up();
  5216. this.orthoLeft = null;
  5217. this.orthoRight = null;
  5218. this.orthoBottom = null;
  5219. this.orthoTop = null;
  5220. this.fov = 0.8;
  5221. this.minZ = 1.0;
  5222. this.maxZ = 10000.0;
  5223. this.inertia = 0.9;
  5224. this.mode = Camera.PERSPECTIVE_CAMERA;
  5225. this.isIntermediate = false;
  5226. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5227. this.subCameras = [];
  5228. this.layerMask = 0xFFFFFFFF;
  5229. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5230. this._projectionMatrix = new BABYLON.Matrix();
  5231. this._postProcesses = new Array();
  5232. this._postProcessesTakenIndices = [];
  5233. scene.cameras.push(this);
  5234. if (!scene.activeCamera) {
  5235. scene.activeCamera = this;
  5236. }
  5237. }
  5238. Camera.prototype._initCache = function () {
  5239. _super.prototype._initCache.call(this);
  5240. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5241. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5242. this._cache.mode = undefined;
  5243. this._cache.minZ = undefined;
  5244. this._cache.maxZ = undefined;
  5245. this._cache.fov = undefined;
  5246. this._cache.aspectRatio = undefined;
  5247. this._cache.orthoLeft = undefined;
  5248. this._cache.orthoRight = undefined;
  5249. this._cache.orthoBottom = undefined;
  5250. this._cache.orthoTop = undefined;
  5251. this._cache.renderWidth = undefined;
  5252. this._cache.renderHeight = undefined;
  5253. };
  5254. Camera.prototype._updateCache = function (ignoreParentClass) {
  5255. if (!ignoreParentClass) {
  5256. _super.prototype._updateCache.call(this);
  5257. }
  5258. var engine = this.getEngine();
  5259. this._cache.position.copyFrom(this.position);
  5260. this._cache.upVector.copyFrom(this.upVector);
  5261. this._cache.mode = this.mode;
  5262. this._cache.minZ = this.minZ;
  5263. this._cache.maxZ = this.maxZ;
  5264. this._cache.fov = this.fov;
  5265. this._cache.aspectRatio = engine.getAspectRatio(this);
  5266. this._cache.orthoLeft = this.orthoLeft;
  5267. this._cache.orthoRight = this.orthoRight;
  5268. this._cache.orthoBottom = this.orthoBottom;
  5269. this._cache.orthoTop = this.orthoTop;
  5270. this._cache.renderWidth = engine.getRenderWidth();
  5271. this._cache.renderHeight = engine.getRenderHeight();
  5272. };
  5273. Camera.prototype._updateFromScene = function () {
  5274. this.updateCache();
  5275. this._update();
  5276. };
  5277. Camera.prototype._isSynchronized = function () {
  5278. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5279. };
  5280. Camera.prototype._isSynchronizedViewMatrix = function () {
  5281. if (!_super.prototype._isSynchronized.call(this))
  5282. return false;
  5283. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5284. };
  5285. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5286. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5287. if (!check) {
  5288. return false;
  5289. }
  5290. var engine = this.getEngine();
  5291. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5292. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5293. } else {
  5294. 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();
  5295. }
  5296. return check;
  5297. };
  5298. Camera.prototype.attachControl = function (element) {
  5299. };
  5300. Camera.prototype.detachControl = function (element) {
  5301. };
  5302. Camera.prototype._update = function () {
  5303. };
  5304. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5305. if (typeof insertAt === "undefined") { insertAt = null; }
  5306. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5307. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5308. return 0;
  5309. }
  5310. if (insertAt == null || insertAt < 0) {
  5311. this._postProcesses.push(postProcess);
  5312. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5313. return this._postProcesses.length - 1;
  5314. }
  5315. var add = 0;
  5316. if (this._postProcesses[insertAt]) {
  5317. var start = this._postProcesses.length - 1;
  5318. for (var i = start; i >= insertAt + 1; --i) {
  5319. this._postProcesses[i + 1] = this._postProcesses[i];
  5320. }
  5321. add = 1;
  5322. }
  5323. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5324. if (this._postProcessesTakenIndices[i] < insertAt) {
  5325. continue;
  5326. }
  5327. start = this._postProcessesTakenIndices.length - 1;
  5328. for (var j = start; j >= i; --j) {
  5329. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5330. }
  5331. this._postProcessesTakenIndices[i] = insertAt;
  5332. break;
  5333. }
  5334. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5335. this._postProcessesTakenIndices.push(insertAt);
  5336. }
  5337. var result = insertAt + add;
  5338. this._postProcesses[result] = postProcess;
  5339. return result;
  5340. };
  5341. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5342. if (typeof atIndices === "undefined") { atIndices = null; }
  5343. var result = [];
  5344. if (!atIndices) {
  5345. var length = this._postProcesses.length;
  5346. for (var i = 0; i < length; i++) {
  5347. if (this._postProcesses[i] !== postProcess) {
  5348. continue;
  5349. }
  5350. delete this._postProcesses[i];
  5351. var index = this._postProcessesTakenIndices.indexOf(i);
  5352. this._postProcessesTakenIndices.splice(index, 1);
  5353. }
  5354. } else {
  5355. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5356. for (i = 0; i < atIndices.length; i++) {
  5357. var foundPostProcess = this._postProcesses[atIndices[i]];
  5358. if (foundPostProcess !== postProcess) {
  5359. result.push(i);
  5360. continue;
  5361. }
  5362. delete this._postProcesses[atIndices[i]];
  5363. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5364. this._postProcessesTakenIndices.splice(index, 1);
  5365. }
  5366. }
  5367. return result;
  5368. };
  5369. Camera.prototype.getWorldMatrix = function () {
  5370. if (!this._worldMatrix) {
  5371. this._worldMatrix = BABYLON.Matrix.Identity();
  5372. }
  5373. var viewMatrix = this.getViewMatrix();
  5374. viewMatrix.invertToRef(this._worldMatrix);
  5375. return this._worldMatrix;
  5376. };
  5377. Camera.prototype._getViewMatrix = function () {
  5378. return BABYLON.Matrix.Identity();
  5379. };
  5380. Camera.prototype.getViewMatrix = function () {
  5381. this._computedViewMatrix = this._computeViewMatrix();
  5382. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5383. return this._computedViewMatrix;
  5384. }
  5385. if (!this._worldMatrix) {
  5386. this._worldMatrix = BABYLON.Matrix.Identity();
  5387. }
  5388. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5389. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5390. this._computedViewMatrix.invert();
  5391. this._currentRenderId = this.getScene().getRenderId();
  5392. return this._computedViewMatrix;
  5393. };
  5394. Camera.prototype._computeViewMatrix = function (force) {
  5395. if (!force && this._isSynchronizedViewMatrix()) {
  5396. return this._computedViewMatrix;
  5397. }
  5398. this._computedViewMatrix = this._getViewMatrix();
  5399. if (!this.parent || !this.parent.getWorldMatrix) {
  5400. this._currentRenderId = this.getScene().getRenderId();
  5401. }
  5402. return this._computedViewMatrix;
  5403. };
  5404. Camera.prototype.getProjectionMatrix = function (force) {
  5405. if (!force && this._isSynchronizedProjectionMatrix()) {
  5406. return this._projectionMatrix;
  5407. }
  5408. var engine = this.getEngine();
  5409. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5410. if (this.minZ <= 0) {
  5411. this.minZ = 0.1;
  5412. }
  5413. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5414. return this._projectionMatrix;
  5415. }
  5416. var halfWidth = engine.getRenderWidth() / 2.0;
  5417. var halfHeight = engine.getRenderHeight() / 2.0;
  5418. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5419. return this._projectionMatrix;
  5420. };
  5421. Camera.prototype.dispose = function () {
  5422. var index = this.getScene().cameras.indexOf(this);
  5423. this.getScene().cameras.splice(index, 1);
  5424. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5425. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5426. }
  5427. };
  5428. Camera.PERSPECTIVE_CAMERA = 0;
  5429. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5430. return Camera;
  5431. })(BABYLON.Node);
  5432. BABYLON.Camera = Camera;
  5433. })(BABYLON || (BABYLON = {}));
  5434. var __extends = this.__extends || function (d, b) {
  5435. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5436. function __() { this.constructor = d; }
  5437. __.prototype = b.prototype;
  5438. d.prototype = new __();
  5439. };
  5440. var BABYLON;
  5441. (function (BABYLON) {
  5442. var TargetCamera = (function (_super) {
  5443. __extends(TargetCamera, _super);
  5444. function TargetCamera(name, position, scene) {
  5445. _super.call(this, name, position, scene);
  5446. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5447. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5448. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5449. this.speed = 2.0;
  5450. this.noRotationConstraint = false;
  5451. this.lockedTarget = null;
  5452. this._currentTarget = BABYLON.Vector3.Zero();
  5453. this._viewMatrix = BABYLON.Matrix.Zero();
  5454. this._camMatrix = BABYLON.Matrix.Zero();
  5455. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5456. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5457. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5458. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5459. this._lookAtTemp = BABYLON.Matrix.Zero();
  5460. this._tempMatrix = BABYLON.Matrix.Zero();
  5461. }
  5462. TargetCamera.prototype._getLockedTargetPosition = function () {
  5463. if (!this.lockedTarget) {
  5464. return null;
  5465. }
  5466. return this.lockedTarget.position || this.lockedTarget;
  5467. };
  5468. TargetCamera.prototype._initCache = function () {
  5469. _super.prototype._initCache.call(this);
  5470. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5471. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5472. };
  5473. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5474. if (!ignoreParentClass) {
  5475. _super.prototype._updateCache.call(this);
  5476. }
  5477. var lockedTargetPosition = this._getLockedTargetPosition();
  5478. if (!lockedTargetPosition) {
  5479. this._cache.lockedTarget = null;
  5480. } else {
  5481. if (!this._cache.lockedTarget) {
  5482. this._cache.lockedTarget = lockedTargetPosition.clone();
  5483. } else {
  5484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5485. }
  5486. }
  5487. this._cache.rotation.copyFrom(this.rotation);
  5488. };
  5489. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5490. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5491. return false;
  5492. }
  5493. var lockedTargetPosition = this._getLockedTargetPosition();
  5494. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5495. };
  5496. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5497. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5498. };
  5499. TargetCamera.prototype.setTarget = function (target) {
  5500. this.upVector.normalize();
  5501. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5502. this._camMatrix.invert();
  5503. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5504. var vDir = target.subtract(this.position);
  5505. if (vDir.x >= 0.0) {
  5506. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5507. } else {
  5508. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5509. }
  5510. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5511. if (isNaN(this.rotation.x)) {
  5512. this.rotation.x = 0;
  5513. }
  5514. if (isNaN(this.rotation.y)) {
  5515. this.rotation.y = 0;
  5516. }
  5517. if (isNaN(this.rotation.z)) {
  5518. this.rotation.z = 0;
  5519. }
  5520. };
  5521. TargetCamera.prototype.getTarget = function () {
  5522. return this._currentTarget;
  5523. };
  5524. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5525. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5526. };
  5527. TargetCamera.prototype._updatePosition = function () {
  5528. this.position.addInPlace(this.cameraDirection);
  5529. };
  5530. TargetCamera.prototype._update = function () {
  5531. var needToMove = this._decideIfNeedsToMove();
  5532. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5533. if (needToMove) {
  5534. this._updatePosition();
  5535. }
  5536. if (needToRotate) {
  5537. this.rotation.x += this.cameraRotation.x;
  5538. this.rotation.y += this.cameraRotation.y;
  5539. if (!this.noRotationConstraint) {
  5540. var limit = (Math.PI / 2) * 0.95;
  5541. if (this.rotation.x > limit)
  5542. this.rotation.x = limit;
  5543. if (this.rotation.x < -limit)
  5544. this.rotation.x = -limit;
  5545. }
  5546. }
  5547. if (needToMove) {
  5548. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5549. this.cameraDirection.x = 0;
  5550. }
  5551. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5552. this.cameraDirection.y = 0;
  5553. }
  5554. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5555. this.cameraDirection.z = 0;
  5556. }
  5557. this.cameraDirection.scaleInPlace(this.inertia);
  5558. }
  5559. if (needToRotate) {
  5560. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5561. this.cameraRotation.x = 0;
  5562. }
  5563. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5564. this.cameraRotation.y = 0;
  5565. }
  5566. this.cameraRotation.scaleInPlace(this.inertia);
  5567. }
  5568. };
  5569. TargetCamera.prototype._getViewMatrix = function () {
  5570. if (!this.lockedTarget) {
  5571. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5572. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5573. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5574. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5575. this._lookAtTemp.invert();
  5576. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5577. } else {
  5578. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5579. }
  5580. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5581. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5582. } else {
  5583. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5584. }
  5585. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5586. return this._viewMatrix;
  5587. };
  5588. return TargetCamera;
  5589. })(BABYLON.Camera);
  5590. BABYLON.TargetCamera = TargetCamera;
  5591. })(BABYLON || (BABYLON = {}));
  5592. var __extends = this.__extends || function (d, b) {
  5593. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5594. function __() { this.constructor = d; }
  5595. __.prototype = b.prototype;
  5596. d.prototype = new __();
  5597. };
  5598. var BABYLON;
  5599. (function (BABYLON) {
  5600. var FollowCamera = (function (_super) {
  5601. __extends(FollowCamera, _super);
  5602. function FollowCamera(name, position, scene) {
  5603. _super.call(this, name, position, scene);
  5604. this.radius = 12;
  5605. this.rotationOffset = 0;
  5606. this.heightOffset = 4;
  5607. this.cameraAcceleration = 0.05;
  5608. this.maxCameraSpeed = 20;
  5609. }
  5610. FollowCamera.prototype.getRadians = function (degrees) {
  5611. return degrees * Math.PI / 180;
  5612. };
  5613. FollowCamera.prototype.follow = function (cameraTarget) {
  5614. if (!cameraTarget)
  5615. return;
  5616. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5617. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5618. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5619. var dx = targetX - this.position.x;
  5620. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5621. var dz = (targetZ) - this.position.z;
  5622. var vx = dx * this.cameraAcceleration * 2;
  5623. var vy = dy * this.cameraAcceleration;
  5624. var vz = dz * this.cameraAcceleration * 2;
  5625. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5626. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5627. }
  5628. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5629. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5630. }
  5631. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5632. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5633. }
  5634. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5635. this.setTarget(cameraTarget.position);
  5636. };
  5637. FollowCamera.prototype._update = function () {
  5638. _super.prototype._update.call(this);
  5639. this.follow(this.target);
  5640. };
  5641. return FollowCamera;
  5642. })(BABYLON.TargetCamera);
  5643. BABYLON.FollowCamera = FollowCamera;
  5644. })(BABYLON || (BABYLON = {}));
  5645. var __extends = this.__extends || function (d, b) {
  5646. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5647. function __() { this.constructor = d; }
  5648. __.prototype = b.prototype;
  5649. d.prototype = new __();
  5650. };
  5651. var BABYLON;
  5652. (function (BABYLON) {
  5653. var FreeCamera = (function (_super) {
  5654. __extends(FreeCamera, _super);
  5655. function FreeCamera(name, position, scene) {
  5656. _super.call(this, name, position, scene);
  5657. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5658. this.keysUp = [38];
  5659. this.keysDown = [40];
  5660. this.keysLeft = [37];
  5661. this.keysRight = [39];
  5662. this.checkCollisions = false;
  5663. this.applyGravity = false;
  5664. this.angularSensibility = 2000.0;
  5665. this._keys = [];
  5666. this._collider = new BABYLON.Collider();
  5667. this._needMoveForGravity = true;
  5668. this._oldPosition = BABYLON.Vector3.Zero();
  5669. this._diffPosition = BABYLON.Vector3.Zero();
  5670. this._newPosition = BABYLON.Vector3.Zero();
  5671. }
  5672. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5673. var _this = this;
  5674. var previousPosition;
  5675. var engine = this.getEngine();
  5676. if (this._attachedElement) {
  5677. return;
  5678. }
  5679. this._attachedElement = element;
  5680. if (this._onMouseDown === undefined) {
  5681. this._onMouseDown = function (evt) {
  5682. previousPosition = {
  5683. x: evt.clientX,
  5684. y: evt.clientY
  5685. };
  5686. if (!noPreventDefault) {
  5687. evt.preventDefault();
  5688. }
  5689. };
  5690. this._onMouseUp = function (evt) {
  5691. previousPosition = null;
  5692. if (!noPreventDefault) {
  5693. evt.preventDefault();
  5694. }
  5695. };
  5696. this._onMouseOut = function (evt) {
  5697. previousPosition = null;
  5698. _this._keys = [];
  5699. if (!noPreventDefault) {
  5700. evt.preventDefault();
  5701. }
  5702. };
  5703. this._onMouseMove = function (evt) {
  5704. if (!previousPosition && !engine.isPointerLock) {
  5705. return;
  5706. }
  5707. var offsetX;
  5708. var offsetY;
  5709. if (!engine.isPointerLock) {
  5710. offsetX = evt.clientX - previousPosition.x;
  5711. offsetY = evt.clientY - previousPosition.y;
  5712. } else {
  5713. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5714. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5715. }
  5716. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5717. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5718. previousPosition = {
  5719. x: evt.clientX,
  5720. y: evt.clientY
  5721. };
  5722. if (!noPreventDefault) {
  5723. evt.preventDefault();
  5724. }
  5725. };
  5726. this._onKeyDown = function (evt) {
  5727. 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) {
  5728. var index = _this._keys.indexOf(evt.keyCode);
  5729. if (index === -1) {
  5730. _this._keys.push(evt.keyCode);
  5731. }
  5732. if (!noPreventDefault) {
  5733. evt.preventDefault();
  5734. }
  5735. }
  5736. };
  5737. this._onKeyUp = function (evt) {
  5738. 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) {
  5739. var index = _this._keys.indexOf(evt.keyCode);
  5740. if (index >= 0) {
  5741. _this._keys.splice(index, 1);
  5742. }
  5743. if (!noPreventDefault) {
  5744. evt.preventDefault();
  5745. }
  5746. }
  5747. };
  5748. this._onLostFocus = function () {
  5749. _this._keys = [];
  5750. };
  5751. this._reset = function () {
  5752. _this._keys = [];
  5753. previousPosition = null;
  5754. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5755. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5756. };
  5757. }
  5758. element.addEventListener("mousedown", this._onMouseDown, false);
  5759. element.addEventListener("mouseup", this._onMouseUp, false);
  5760. element.addEventListener("mouseout", this._onMouseOut, false);
  5761. element.addEventListener("mousemove", this._onMouseMove, false);
  5762. BABYLON.Tools.RegisterTopRootEvents([
  5763. { name: "keydown", handler: this._onKeyDown },
  5764. { name: "keyup", handler: this._onKeyUp },
  5765. { name: "blur", handler: this._onLostFocus }
  5766. ]);
  5767. };
  5768. FreeCamera.prototype.detachControl = function (element) {
  5769. if (this._attachedElement != element) {
  5770. return;
  5771. }
  5772. element.removeEventListener("mousedown", this._onMouseDown);
  5773. element.removeEventListener("mouseup", this._onMouseUp);
  5774. element.removeEventListener("mouseout", this._onMouseOut);
  5775. element.removeEventListener("mousemove", this._onMouseMove);
  5776. BABYLON.Tools.UnregisterTopRootEvents([
  5777. { name: "keydown", handler: this._onKeyDown },
  5778. { name: "keyup", handler: this._onKeyUp },
  5779. { name: "blur", handler: this._onLostFocus }
  5780. ]);
  5781. this._attachedElement = null;
  5782. if (this._reset) {
  5783. this._reset();
  5784. }
  5785. };
  5786. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5787. var globalPosition;
  5788. if (this.parent) {
  5789. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5790. } else {
  5791. globalPosition = this.position;
  5792. }
  5793. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5794. this._collider.radius = this.ellipsoid;
  5795. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5796. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5797. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5798. this.position.addInPlace(this._diffPosition);
  5799. if (this.onCollide) {
  5800. this.onCollide(this._collider.collidedMesh);
  5801. }
  5802. }
  5803. };
  5804. FreeCamera.prototype._checkInputs = function () {
  5805. if (!this._localDirection) {
  5806. this._localDirection = BABYLON.Vector3.Zero();
  5807. this._transformedDirection = BABYLON.Vector3.Zero();
  5808. }
  5809. for (var index = 0; index < this._keys.length; index++) {
  5810. var keyCode = this._keys[index];
  5811. var speed = this._computeLocalCameraSpeed();
  5812. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5813. this._localDirection.copyFromFloats(-speed, 0, 0);
  5814. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5815. this._localDirection.copyFromFloats(0, 0, speed);
  5816. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5817. this._localDirection.copyFromFloats(speed, 0, 0);
  5818. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5819. this._localDirection.copyFromFloats(0, 0, -speed);
  5820. }
  5821. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5822. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5823. this.cameraDirection.addInPlace(this._transformedDirection);
  5824. }
  5825. };
  5826. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5827. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5828. };
  5829. FreeCamera.prototype._updatePosition = function () {
  5830. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5831. this._collideWithWorld(this.cameraDirection);
  5832. if (this.applyGravity) {
  5833. var oldPosition = this.position;
  5834. this._collideWithWorld(this.getScene().gravity);
  5835. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5836. }
  5837. } else {
  5838. this.position.addInPlace(this.cameraDirection);
  5839. }
  5840. };
  5841. FreeCamera.prototype._update = function () {
  5842. this._checkInputs();
  5843. _super.prototype._update.call(this);
  5844. };
  5845. return FreeCamera;
  5846. })(BABYLON.TargetCamera);
  5847. BABYLON.FreeCamera = FreeCamera;
  5848. })(BABYLON || (BABYLON = {}));
  5849. var __extends = this.__extends || function (d, b) {
  5850. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5851. function __() { this.constructor = d; }
  5852. __.prototype = b.prototype;
  5853. d.prototype = new __();
  5854. };
  5855. var BABYLON;
  5856. (function (BABYLON) {
  5857. var TouchCamera = (function (_super) {
  5858. __extends(TouchCamera, _super);
  5859. function TouchCamera(name, position, scene) {
  5860. _super.call(this, name, position, scene);
  5861. this._offsetX = null;
  5862. this._offsetY = null;
  5863. this._pointerCount = 0;
  5864. this._pointerPressed = [];
  5865. this.angularSensibility = 200000.0;
  5866. this.moveSensibility = 500.0;
  5867. }
  5868. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5869. var _this = this;
  5870. var previousPosition;
  5871. if (this._attachedCanvas) {
  5872. return;
  5873. }
  5874. this._attachedCanvas = canvas;
  5875. if (this._onPointerDown === undefined) {
  5876. this._onPointerDown = function (evt) {
  5877. if (!noPreventDefault) {
  5878. evt.preventDefault();
  5879. }
  5880. _this._pointerPressed.push(evt.pointerId);
  5881. if (_this._pointerPressed.length !== 1) {
  5882. return;
  5883. }
  5884. previousPosition = {
  5885. x: evt.clientX,
  5886. y: evt.clientY
  5887. };
  5888. };
  5889. this._onPointerUp = function (evt) {
  5890. if (!noPreventDefault) {
  5891. evt.preventDefault();
  5892. }
  5893. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5894. if (index === -1) {
  5895. return;
  5896. }
  5897. _this._pointerPressed.splice(index, 1);
  5898. if (index != 0) {
  5899. return;
  5900. }
  5901. previousPosition = null;
  5902. _this._offsetX = null;
  5903. _this._offsetY = null;
  5904. };
  5905. this._onPointerMove = function (evt) {
  5906. if (!noPreventDefault) {
  5907. evt.preventDefault();
  5908. }
  5909. if (!previousPosition) {
  5910. return;
  5911. }
  5912. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5913. if (index != 0) {
  5914. return;
  5915. }
  5916. _this._offsetX = evt.clientX - previousPosition.x;
  5917. _this._offsetY = -(evt.clientY - previousPosition.y);
  5918. };
  5919. this._onLostFocus = function () {
  5920. _this._offsetX = null;
  5921. _this._offsetY = null;
  5922. };
  5923. }
  5924. canvas.addEventListener("pointerdown", this._onPointerDown);
  5925. canvas.addEventListener("pointerup", this._onPointerUp);
  5926. canvas.addEventListener("pointerout", this._onPointerUp);
  5927. canvas.addEventListener("pointermove", this._onPointerMove);
  5928. BABYLON.Tools.RegisterTopRootEvents([
  5929. { name: "blur", handler: this._onLostFocus }
  5930. ]);
  5931. };
  5932. TouchCamera.prototype.detachControl = function (canvas) {
  5933. if (this._attachedCanvas != canvas) {
  5934. return;
  5935. }
  5936. canvas.removeEventListener("pointerdown", this._onPointerDown);
  5937. canvas.removeEventListener("pointerup", this._onPointerUp);
  5938. canvas.removeEventListener("pointerout", this._onPointerUp);
  5939. canvas.removeEventListener("pointermove", this._onPointerMove);
  5940. BABYLON.Tools.UnregisterTopRootEvents([
  5941. { name: "blur", handler: this._onLostFocus }
  5942. ]);
  5943. this._attachedCanvas = null;
  5944. };
  5945. TouchCamera.prototype._checkInputs = function () {
  5946. if (!this._offsetX) {
  5947. return;
  5948. }
  5949. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  5950. if (this._pointerPressed.length > 1) {
  5951. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  5952. } else {
  5953. var speed = this._computeLocalCameraSpeed();
  5954. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  5955. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  5956. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  5957. }
  5958. };
  5959. return TouchCamera;
  5960. })(BABYLON.FreeCamera);
  5961. BABYLON.TouchCamera = TouchCamera;
  5962. })(BABYLON || (BABYLON = {}));
  5963. var __extends = this.__extends || function (d, b) {
  5964. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5965. function __() { this.constructor = d; }
  5966. __.prototype = b.prototype;
  5967. d.prototype = new __();
  5968. };
  5969. var BABYLON;
  5970. (function (BABYLON) {
  5971. var DeviceOrientationCamera = (function (_super) {
  5972. __extends(DeviceOrientationCamera, _super);
  5973. function DeviceOrientationCamera(name, position, scene) {
  5974. var _this = this;
  5975. _super.call(this, name, position, scene);
  5976. this._offsetX = null;
  5977. this._offsetY = null;
  5978. this._orientationGamma = 0;
  5979. this._orientationBeta = 0;
  5980. this._initialOrientationGamma = 0;
  5981. this._initialOrientationBeta = 0;
  5982. this.angularSensibility = 10000.0;
  5983. this.moveSensibility = 50.0;
  5984. window.addEventListener("resize", function () {
  5985. _this._initialOrientationGamma = null;
  5986. }, false);
  5987. }
  5988. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5989. var _this = this;
  5990. if (this._attachedCanvas) {
  5991. return;
  5992. }
  5993. this._attachedCanvas = canvas;
  5994. if (!this._orientationChanged) {
  5995. this._orientationChanged = function (evt) {
  5996. if (!_this._initialOrientationGamma) {
  5997. _this._initialOrientationGamma = evt.gamma;
  5998. _this._initialOrientationBeta = evt.beta;
  5999. }
  6000. _this._orientationGamma = evt.gamma;
  6001. _this._orientationBeta = evt.beta;
  6002. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6003. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6004. };
  6005. }
  6006. window.addEventListener("deviceorientation", this._orientationChanged);
  6007. };
  6008. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6009. if (this._attachedCanvas != canvas) {
  6010. return;
  6011. }
  6012. window.removeEventListener("deviceorientation", this._orientationChanged);
  6013. this._attachedCanvas = null;
  6014. this._orientationGamma = 0;
  6015. this._orientationBeta = 0;
  6016. this._initialOrientationGamma = 0;
  6017. this._initialOrientationBeta = 0;
  6018. };
  6019. DeviceOrientationCamera.prototype._checkInputs = function () {
  6020. if (!this._offsetX) {
  6021. return;
  6022. }
  6023. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6024. var speed = this._computeLocalCameraSpeed();
  6025. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6026. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6027. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6028. };
  6029. return DeviceOrientationCamera;
  6030. })(BABYLON.FreeCamera);
  6031. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6032. })(BABYLON || (BABYLON = {}));
  6033. var __extends = this.__extends || function (d, b) {
  6034. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6035. function __() { this.constructor = d; }
  6036. __.prototype = b.prototype;
  6037. d.prototype = new __();
  6038. };
  6039. var BABYLON;
  6040. (function (BABYLON) {
  6041. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6042. var ArcRotateCamera = (function (_super) {
  6043. __extends(ArcRotateCamera, _super);
  6044. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6045. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6046. this.alpha = alpha;
  6047. this.beta = beta;
  6048. this.radius = radius;
  6049. this.target = target;
  6050. this.inertialAlphaOffset = 0;
  6051. this.inertialBetaOffset = 0;
  6052. this.inertialRadiusOffset = 0;
  6053. this.lowerAlphaLimit = null;
  6054. this.upperAlphaLimit = null;
  6055. this.lowerBetaLimit = 0.01;
  6056. this.upperBetaLimit = Math.PI;
  6057. this.lowerRadiusLimit = null;
  6058. this.upperRadiusLimit = null;
  6059. this.angularSensibility = 1000.0;
  6060. this.wheelPrecision = 3.0;
  6061. this.keysUp = [38];
  6062. this.keysDown = [40];
  6063. this.keysLeft = [37];
  6064. this.keysRight = [39];
  6065. this.zoomOnFactor = 1;
  6066. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6067. this._keys = [];
  6068. this._viewMatrix = new BABYLON.Matrix();
  6069. this.checkCollisions = false;
  6070. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6071. this._collider = new BABYLON.Collider();
  6072. this._previousPosition = BABYLON.Vector3.Zero();
  6073. this._collisionVelocity = BABYLON.Vector3.Zero();
  6074. this._newPosition = BABYLON.Vector3.Zero();
  6075. this.pinchPrecision = 20;
  6076. this.getViewMatrix();
  6077. }
  6078. ArcRotateCamera.prototype._getTargetPosition = function () {
  6079. return this.target.position || this.target;
  6080. };
  6081. ArcRotateCamera.prototype._initCache = function () {
  6082. _super.prototype._initCache.call(this);
  6083. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6084. this._cache.alpha = undefined;
  6085. this._cache.beta = undefined;
  6086. this._cache.radius = undefined;
  6087. this._cache.targetScreenOffset = undefined;
  6088. };
  6089. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6090. if (!ignoreParentClass) {
  6091. _super.prototype._updateCache.call(this);
  6092. }
  6093. this._cache.target.copyFrom(this._getTargetPosition());
  6094. this._cache.alpha = this.alpha;
  6095. this._cache.beta = this.beta;
  6096. this._cache.radius = this.radius;
  6097. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6098. };
  6099. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6100. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6101. return false;
  6102. 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);
  6103. };
  6104. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6105. var _this = this;
  6106. var previousPosition;
  6107. var pointerId;
  6108. var pinchStarted = false;
  6109. var pinchPointX1, pinchPointX2;
  6110. if (this._attachedElement) {
  6111. return;
  6112. }
  6113. this._attachedElement = element;
  6114. var engine = this.getEngine();
  6115. if (this._onPointerDown === undefined) {
  6116. this._onPointerDown = function (evt) {
  6117. if (pointerId) {
  6118. return;
  6119. }
  6120. pointerId = evt.pointerId;
  6121. previousPosition = {
  6122. x: evt.clientX,
  6123. y: evt.clientY
  6124. };
  6125. if (!noPreventDefault) {
  6126. evt.preventDefault();
  6127. }
  6128. };
  6129. this._onPointerUp = function (evt) {
  6130. previousPosition = null;
  6131. pointerId = null;
  6132. if (!noPreventDefault) {
  6133. evt.preventDefault();
  6134. }
  6135. };
  6136. this._onPointerMove = function (evt) {
  6137. if (!previousPosition) {
  6138. return;
  6139. }
  6140. if (pointerId !== evt.pointerId) {
  6141. return;
  6142. }
  6143. if (pinchStarted) {
  6144. return;
  6145. }
  6146. var offsetX = evt.clientX - previousPosition.x;
  6147. var offsetY = evt.clientY - previousPosition.y;
  6148. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6149. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6150. previousPosition = {
  6151. x: evt.clientX,
  6152. y: evt.clientY
  6153. };
  6154. if (!noPreventDefault) {
  6155. evt.preventDefault();
  6156. }
  6157. };
  6158. this._onMouseMove = function (evt) {
  6159. if (!engine.isPointerLock) {
  6160. return;
  6161. }
  6162. if (pinchStarted) {
  6163. return;
  6164. }
  6165. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6166. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6167. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6168. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6169. if (!noPreventDefault) {
  6170. evt.preventDefault();
  6171. }
  6172. };
  6173. this._wheel = function (event) {
  6174. var delta = 0;
  6175. if (event.wheelDelta) {
  6176. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6177. } else if (event.detail) {
  6178. delta = -event.detail / _this.wheelPrecision;
  6179. }
  6180. if (delta)
  6181. _this.inertialRadiusOffset += delta;
  6182. if (event.preventDefault) {
  6183. if (!noPreventDefault) {
  6184. event.preventDefault();
  6185. }
  6186. }
  6187. };
  6188. this._onKeyDown = function (evt) {
  6189. 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) {
  6190. var index = _this._keys.indexOf(evt.keyCode);
  6191. if (index === -1) {
  6192. _this._keys.push(evt.keyCode);
  6193. }
  6194. if (evt.preventDefault) {
  6195. if (!noPreventDefault) {
  6196. evt.preventDefault();
  6197. }
  6198. }
  6199. }
  6200. };
  6201. this._onKeyUp = function (evt) {
  6202. 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) {
  6203. var index = _this._keys.indexOf(evt.keyCode);
  6204. if (index >= 0) {
  6205. _this._keys.splice(index, 1);
  6206. }
  6207. if (evt.preventDefault) {
  6208. if (!noPreventDefault) {
  6209. evt.preventDefault();
  6210. }
  6211. }
  6212. }
  6213. };
  6214. this._onLostFocus = function () {
  6215. _this._keys = [];
  6216. pointerId = null;
  6217. };
  6218. this._onGestureStart = function (e) {
  6219. if (window.MSGesture === undefined) {
  6220. return;
  6221. }
  6222. if (!_this._MSGestureHandler) {
  6223. _this._MSGestureHandler = new MSGesture();
  6224. _this._MSGestureHandler.target = element;
  6225. }
  6226. _this._MSGestureHandler.addPointer(e.pointerId);
  6227. };
  6228. this._onGesture = function (e) {
  6229. _this.radius *= e.scale;
  6230. if (e.preventDefault) {
  6231. if (!noPreventDefault) {
  6232. e.stopPropagation();
  6233. e.preventDefault();
  6234. }
  6235. }
  6236. };
  6237. this._reset = function () {
  6238. _this._keys = [];
  6239. _this.inertialAlphaOffset = 0;
  6240. _this.inertialBetaOffset = 0;
  6241. _this.inertialRadiusOffset = 0;
  6242. previousPosition = null;
  6243. pointerId = null;
  6244. };
  6245. this._touchStart = function (event) {
  6246. if (event.touches.length == 2) {
  6247. pinchStarted = true;
  6248. _this._pinchStart(event);
  6249. }
  6250. };
  6251. this._touchMove = function (event) {
  6252. if (pinchStarted) {
  6253. _this._pinchMove(event);
  6254. }
  6255. };
  6256. this._touchEnd = function (event) {
  6257. if (pinchStarted) {
  6258. _this._pinchEnd(event);
  6259. }
  6260. };
  6261. this._pinchStart = function (event) {
  6262. pinchPointX1 = event.touches[0].clientX;
  6263. pinchPointX2 = event.touches[1].clientX;
  6264. pinchStarted = true;
  6265. };
  6266. this._pinchMove = function (event) {
  6267. var delta = 0;
  6268. var direction = 1;
  6269. var distanceXOrigine, distanceXNow;
  6270. if (event.touches.length != 2)
  6271. return;
  6272. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6273. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6274. if (distanceXNow < distanceXOrigine) {
  6275. direction = -1;
  6276. }
  6277. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6278. _this.inertialRadiusOffset += delta;
  6279. pinchPointX1 = event.touches[0].clientX;
  6280. pinchPointX2 = event.touches[1].clientX;
  6281. };
  6282. this._pinchEnd = function (event) {
  6283. pinchStarted = false;
  6284. };
  6285. }
  6286. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6287. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6288. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6289. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6290. element.addEventListener("mousemove", this._onMouseMove, false);
  6291. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6292. element.addEventListener("MSGestureChange", this._onGesture, false);
  6293. element.addEventListener('mousewheel', this._wheel, false);
  6294. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6295. element.addEventListener('touchstart', this._touchStart, false);
  6296. element.addEventListener('touchmove', this._touchMove, false);
  6297. element.addEventListener('touchend', this._touchEnd, false);
  6298. BABYLON.Tools.RegisterTopRootEvents([
  6299. { name: "keydown", handler: this._onKeyDown },
  6300. { name: "keyup", handler: this._onKeyUp },
  6301. { name: "blur", handler: this._onLostFocus }
  6302. ]);
  6303. };
  6304. ArcRotateCamera.prototype.detachControl = function (element) {
  6305. if (this._attachedElement != element) {
  6306. return;
  6307. }
  6308. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6309. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6310. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6311. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6312. element.removeEventListener("mousemove", this._onMouseMove);
  6313. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6314. element.removeEventListener("MSGestureChange", this._onGesture);
  6315. element.removeEventListener('mousewheel', this._wheel);
  6316. element.removeEventListener('DOMMouseScroll', this._wheel);
  6317. element.removeEventListener('touchstart', this._touchStart);
  6318. element.removeEventListener('touchmove', this._touchMove);
  6319. element.removeEventListener('touchend', this._touchEnd);
  6320. BABYLON.Tools.UnregisterTopRootEvents([
  6321. { name: "keydown", handler: this._onKeyDown },
  6322. { name: "keyup", handler: this._onKeyUp },
  6323. { name: "blur", handler: this._onLostFocus }
  6324. ]);
  6325. this._MSGestureHandler = null;
  6326. this._attachedElement = null;
  6327. if (this._reset) {
  6328. this._reset();
  6329. }
  6330. };
  6331. ArcRotateCamera.prototype._update = function () {
  6332. for (var index = 0; index < this._keys.length; index++) {
  6333. var keyCode = this._keys[index];
  6334. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6335. this.inertialAlphaOffset -= 0.01;
  6336. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6337. this.inertialBetaOffset -= 0.01;
  6338. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6339. this.inertialAlphaOffset += 0.01;
  6340. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6341. this.inertialBetaOffset += 0.01;
  6342. }
  6343. }
  6344. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6345. this.alpha += this.inertialAlphaOffset;
  6346. this.beta += this.inertialBetaOffset;
  6347. this.radius -= this.inertialRadiusOffset;
  6348. this.inertialAlphaOffset *= this.inertia;
  6349. this.inertialBetaOffset *= this.inertia;
  6350. this.inertialRadiusOffset *= this.inertia;
  6351. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6352. this.inertialAlphaOffset = 0;
  6353. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6354. this.inertialBetaOffset = 0;
  6355. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6356. this.inertialRadiusOffset = 0;
  6357. }
  6358. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6359. this.alpha = this.lowerAlphaLimit;
  6360. }
  6361. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6362. this.alpha = this.upperAlphaLimit;
  6363. }
  6364. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6365. this.beta = this.lowerBetaLimit;
  6366. }
  6367. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6368. this.beta = this.upperBetaLimit;
  6369. }
  6370. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6371. this.radius = this.lowerRadiusLimit;
  6372. }
  6373. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6374. this.radius = this.upperRadiusLimit;
  6375. }
  6376. };
  6377. ArcRotateCamera.prototype.setPosition = function (position) {
  6378. var radiusv3 = position.subtract(this._getTargetPosition());
  6379. this.radius = radiusv3.length();
  6380. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6381. if (radiusv3.z < 0) {
  6382. this.alpha = 2 * Math.PI - this.alpha;
  6383. }
  6384. this.beta = Math.acos(radiusv3.y / this.radius);
  6385. };
  6386. ArcRotateCamera.prototype._getViewMatrix = function () {
  6387. var cosa = Math.cos(this.alpha);
  6388. var sina = Math.sin(this.alpha);
  6389. var cosb = Math.cos(this.beta);
  6390. var sinb = Math.sin(this.beta);
  6391. var target = this._getTargetPosition();
  6392. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6393. if (this.checkCollisions) {
  6394. this._collider.radius = this.collisionRadius;
  6395. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6396. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6397. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6398. this.position.copyFrom(this._previousPosition);
  6399. this.alpha = this._previousAlpha;
  6400. this.beta = this._previousBeta;
  6401. this.radius = this._previousRadius;
  6402. if (this.onCollide) {
  6403. this.onCollide(this._collider.collidedMesh);
  6404. }
  6405. }
  6406. }
  6407. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6408. this._previousAlpha = this.alpha;
  6409. this._previousBeta = this.beta;
  6410. this._previousRadius = this.radius;
  6411. this._previousPosition.copyFrom(this.position);
  6412. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6413. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6414. return this._viewMatrix;
  6415. };
  6416. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6417. meshes = meshes || this.getScene().meshes;
  6418. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6419. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6420. this.radius = distance * this.zoomOnFactor;
  6421. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6422. };
  6423. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6424. var meshesOrMinMaxVector;
  6425. var distance;
  6426. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6427. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6428. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6429. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6430. } else {
  6431. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6432. distance = meshesOrMinMaxVectorAndDistance.distance;
  6433. }
  6434. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6435. this.maxZ = distance * 2;
  6436. };
  6437. return ArcRotateCamera;
  6438. })(BABYLON.Camera);
  6439. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6440. })(BABYLON || (BABYLON = {}));
  6441. var BABYLON;
  6442. (function (BABYLON) {
  6443. var Scene = (function () {
  6444. function Scene(engine) {
  6445. this.autoClear = true;
  6446. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6447. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6448. this.forceWireframe = false;
  6449. this.cameraToUseForPointers = null;
  6450. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6451. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6452. this.fogDensity = 0.1;
  6453. this.fogStart = 0;
  6454. this.fogEnd = 1000.0;
  6455. this.shadowsEnabled = true;
  6456. this.lightsEnabled = true;
  6457. this.lights = new Array();
  6458. this.cameras = new Array();
  6459. this.activeCameras = new Array();
  6460. this.meshes = new Array();
  6461. this._geometries = new Array();
  6462. this.materials = new Array();
  6463. this.multiMaterials = new Array();
  6464. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6465. this.texturesEnabled = true;
  6466. this.textures = new Array();
  6467. this.particlesEnabled = true;
  6468. this.particleSystems = new Array();
  6469. this.spriteManagers = new Array();
  6470. this.layers = new Array();
  6471. this.skeletons = new Array();
  6472. this.lensFlaresEnabled = true;
  6473. this.lensFlareSystems = new Array();
  6474. this.collisionsEnabled = true;
  6475. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6476. this.postProcessesEnabled = true;
  6477. this.renderTargetsEnabled = true;
  6478. this.customRenderTargets = new Array();
  6479. this.importedMeshesFiles = new Array();
  6480. this._actionManagers = new Array();
  6481. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6482. this.proceduralTexturesEnabled = true;
  6483. this._proceduralTextures = new Array();
  6484. this._totalVertices = 0;
  6485. this._activeVertices = 0;
  6486. this._activeParticles = 0;
  6487. this._lastFrameDuration = 0;
  6488. this._evaluateActiveMeshesDuration = 0;
  6489. this._renderTargetsDuration = 0;
  6490. this._particlesDuration = 0;
  6491. this._renderDuration = 0;
  6492. this._spritesDuration = 0;
  6493. this._animationRatio = 0;
  6494. this._renderId = 0;
  6495. this._executeWhenReadyTimeoutId = -1;
  6496. this._toBeDisposed = new BABYLON.SmartArray(256);
  6497. this._onReadyCallbacks = new Array();
  6498. this._pendingData = [];
  6499. this._onBeforeRenderCallbacks = new Array();
  6500. this._activeMeshes = new BABYLON.SmartArray(256);
  6501. this._processedMaterials = new BABYLON.SmartArray(256);
  6502. this._renderTargets = new BABYLON.SmartArray(256);
  6503. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6504. this._activeSkeletons = new BABYLON.SmartArray(32);
  6505. this._activeAnimatables = new Array();
  6506. this._transformMatrix = BABYLON.Matrix.Zero();
  6507. this._scaledPosition = BABYLON.Vector3.Zero();
  6508. this._scaledVelocity = BABYLON.Vector3.Zero();
  6509. this._engine = engine;
  6510. engine.scenes.push(this);
  6511. this._renderingManager = new BABYLON.RenderingManager(this);
  6512. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6513. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6514. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6515. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6516. this.attachControl();
  6517. }
  6518. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6519. get: function () {
  6520. return this._meshUnderPointer;
  6521. },
  6522. enumerable: true,
  6523. configurable: true
  6524. });
  6525. Object.defineProperty(Scene.prototype, "pointerX", {
  6526. get: function () {
  6527. return this._pointerX;
  6528. },
  6529. enumerable: true,
  6530. configurable: true
  6531. });
  6532. Object.defineProperty(Scene.prototype, "pointerY", {
  6533. get: function () {
  6534. return this._pointerY;
  6535. },
  6536. enumerable: true,
  6537. configurable: true
  6538. });
  6539. Scene.prototype.getBoundingBoxRenderer = function () {
  6540. return this._boundingBoxRenderer;
  6541. };
  6542. Scene.prototype.getOutlineRenderer = function () {
  6543. return this._outlineRenderer;
  6544. };
  6545. Scene.prototype.getEngine = function () {
  6546. return this._engine;
  6547. };
  6548. Scene.prototype.getTotalVertices = function () {
  6549. return this._totalVertices;
  6550. };
  6551. Scene.prototype.getActiveVertices = function () {
  6552. return this._activeVertices;
  6553. };
  6554. Scene.prototype.getActiveParticles = function () {
  6555. return this._activeParticles;
  6556. };
  6557. Scene.prototype.getLastFrameDuration = function () {
  6558. return this._lastFrameDuration;
  6559. };
  6560. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6561. return this._evaluateActiveMeshesDuration;
  6562. };
  6563. Scene.prototype.getActiveMeshes = function () {
  6564. return this._activeMeshes;
  6565. };
  6566. Scene.prototype.getRenderTargetsDuration = function () {
  6567. return this._renderTargetsDuration;
  6568. };
  6569. Scene.prototype.getRenderDuration = function () {
  6570. return this._renderDuration;
  6571. };
  6572. Scene.prototype.getParticlesDuration = function () {
  6573. return this._particlesDuration;
  6574. };
  6575. Scene.prototype.getSpritesDuration = function () {
  6576. return this._spritesDuration;
  6577. };
  6578. Scene.prototype.getAnimationRatio = function () {
  6579. return this._animationRatio;
  6580. };
  6581. Scene.prototype.getRenderId = function () {
  6582. return this._renderId;
  6583. };
  6584. Scene.prototype._updatePointerPosition = function (evt) {
  6585. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6586. this._pointerX = evt.clientX - canvasRect.left;
  6587. this._pointerY = evt.clientY - canvasRect.top;
  6588. if (this.cameraToUseForPointers) {
  6589. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6590. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6591. }
  6592. };
  6593. Scene.prototype.attachControl = function () {
  6594. var _this = this;
  6595. this._onPointerMove = function (evt) {
  6596. var canvas = _this._engine.getRenderingCanvas();
  6597. _this._updatePointerPosition(evt);
  6598. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6599. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6600. }, false, _this.cameraToUseForPointers);
  6601. if (pickResult.hit) {
  6602. _this._meshUnderPointer = pickResult.pickedMesh;
  6603. _this.setPointerOverMesh(pickResult.pickedMesh);
  6604. canvas.style.cursor = "pointer";
  6605. } else {
  6606. _this.setPointerOverMesh(null);
  6607. canvas.style.cursor = "";
  6608. _this._meshUnderPointer = null;
  6609. }
  6610. };
  6611. this._onPointerDown = function (evt) {
  6612. var predicate = null;
  6613. if (!_this.onPointerDown) {
  6614. predicate = function (mesh) {
  6615. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6616. };
  6617. }
  6618. _this._updatePointerPosition(evt);
  6619. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6620. if (pickResult.hit) {
  6621. if (pickResult.pickedMesh.actionManager) {
  6622. switch (evt.button) {
  6623. case 0:
  6624. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6625. break;
  6626. case 1:
  6627. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6628. break;
  6629. case 2:
  6630. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6631. break;
  6632. }
  6633. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6634. }
  6635. }
  6636. if (_this.onPointerDown) {
  6637. _this.onPointerDown(evt, pickResult);
  6638. }
  6639. };
  6640. this._onKeyDown = function (evt) {
  6641. if (_this.actionManager) {
  6642. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6643. }
  6644. };
  6645. this._onKeyUp = function (evt) {
  6646. if (_this.actionManager) {
  6647. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6648. }
  6649. };
  6650. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6651. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6652. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6653. window.addEventListener("keydown", this._onKeyDown, false);
  6654. window.addEventListener("keyup", this._onKeyUp, false);
  6655. };
  6656. Scene.prototype.detachControl = function () {
  6657. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6658. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6659. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6660. window.removeEventListener("keydown", this._onKeyDown);
  6661. window.removeEventListener("keyup", this._onKeyUp);
  6662. };
  6663. Scene.prototype.isReady = function () {
  6664. if (this._pendingData.length > 0) {
  6665. return false;
  6666. }
  6667. for (var index = 0; index < this._geometries.length; index++) {
  6668. var geometry = this._geometries[index];
  6669. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6670. return false;
  6671. }
  6672. }
  6673. for (index = 0; index < this.meshes.length; index++) {
  6674. var mesh = this.meshes[index];
  6675. if (!mesh.isReady()) {
  6676. return false;
  6677. }
  6678. var mat = mesh.material;
  6679. if (mat) {
  6680. if (!mat.isReady(mesh)) {
  6681. return false;
  6682. }
  6683. }
  6684. }
  6685. return true;
  6686. };
  6687. Scene.prototype.registerBeforeRender = function (func) {
  6688. this._onBeforeRenderCallbacks.push(func);
  6689. };
  6690. Scene.prototype.unregisterBeforeRender = function (func) {
  6691. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6692. if (index > -1) {
  6693. this._onBeforeRenderCallbacks.splice(index, 1);
  6694. }
  6695. };
  6696. Scene.prototype._addPendingData = function (data) {
  6697. this._pendingData.push(data);
  6698. };
  6699. Scene.prototype._removePendingData = function (data) {
  6700. var index = this._pendingData.indexOf(data);
  6701. if (index !== -1) {
  6702. this._pendingData.splice(index, 1);
  6703. }
  6704. };
  6705. Scene.prototype.getWaitingItemsCount = function () {
  6706. return this._pendingData.length;
  6707. };
  6708. Scene.prototype.executeWhenReady = function (func) {
  6709. var _this = this;
  6710. this._onReadyCallbacks.push(func);
  6711. if (this._executeWhenReadyTimeoutId !== -1) {
  6712. return;
  6713. }
  6714. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6715. _this._checkIsReady();
  6716. }, 150);
  6717. };
  6718. Scene.prototype._checkIsReady = function () {
  6719. var _this = this;
  6720. if (this.isReady()) {
  6721. this._onReadyCallbacks.forEach(function (func) {
  6722. func();
  6723. });
  6724. this._onReadyCallbacks = [];
  6725. this._executeWhenReadyTimeoutId = -1;
  6726. return;
  6727. }
  6728. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6729. _this._checkIsReady();
  6730. }, 150);
  6731. };
  6732. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6733. if (speedRatio === undefined) {
  6734. speedRatio = 1.0;
  6735. }
  6736. this.stopAnimation(target);
  6737. if (!animatable) {
  6738. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6739. }
  6740. if (target.animations) {
  6741. animatable.appendAnimations(target, target.animations);
  6742. }
  6743. if (target.getAnimatables) {
  6744. var animatables = target.getAnimatables();
  6745. for (var index = 0; index < animatables.length; index++) {
  6746. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6747. }
  6748. }
  6749. return animatable;
  6750. };
  6751. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6752. if (speedRatio === undefined) {
  6753. speedRatio = 1.0;
  6754. }
  6755. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6756. return animatable;
  6757. };
  6758. Scene.prototype.getAnimatableByTarget = function (target) {
  6759. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6760. if (this._activeAnimatables[index].target === target) {
  6761. return this._activeAnimatables[index];
  6762. }
  6763. }
  6764. return null;
  6765. };
  6766. Scene.prototype.stopAnimation = function (target) {
  6767. var animatable = this.getAnimatableByTarget(target);
  6768. if (animatable) {
  6769. animatable.stop();
  6770. }
  6771. };
  6772. Scene.prototype._animate = function () {
  6773. if (!this._animationStartDate) {
  6774. this._animationStartDate = BABYLON.Tools.Now;
  6775. }
  6776. var now = BABYLON.Tools.Now;
  6777. var delay = now - this._animationStartDate;
  6778. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6779. if (!this._activeAnimatables[index]._animate(delay)) {
  6780. this._activeAnimatables.splice(index, 1);
  6781. index--;
  6782. }
  6783. }
  6784. };
  6785. Scene.prototype.getViewMatrix = function () {
  6786. return this._viewMatrix;
  6787. };
  6788. Scene.prototype.getProjectionMatrix = function () {
  6789. return this._projectionMatrix;
  6790. };
  6791. Scene.prototype.getTransformMatrix = function () {
  6792. return this._transformMatrix;
  6793. };
  6794. Scene.prototype.setTransformMatrix = function (view, projection) {
  6795. this._viewMatrix = view;
  6796. this._projectionMatrix = projection;
  6797. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6798. };
  6799. Scene.prototype.setActiveCameraByID = function (id) {
  6800. var camera = this.getCameraByID(id);
  6801. if (camera) {
  6802. this.activeCamera = camera;
  6803. return camera;
  6804. }
  6805. return null;
  6806. };
  6807. Scene.prototype.setActiveCameraByName = function (name) {
  6808. var camera = this.getCameraByName(name);
  6809. if (camera) {
  6810. this.activeCamera = camera;
  6811. return camera;
  6812. }
  6813. return null;
  6814. };
  6815. Scene.prototype.getMaterialByID = function (id) {
  6816. for (var index = 0; index < this.materials.length; index++) {
  6817. if (this.materials[index].id === id) {
  6818. return this.materials[index];
  6819. }
  6820. }
  6821. return null;
  6822. };
  6823. Scene.prototype.getMaterialByName = function (name) {
  6824. for (var index = 0; index < this.materials.length; index++) {
  6825. if (this.materials[index].name === name) {
  6826. return this.materials[index];
  6827. }
  6828. }
  6829. return null;
  6830. };
  6831. Scene.prototype.getCameraByID = function (id) {
  6832. for (var index = 0; index < this.cameras.length; index++) {
  6833. if (this.cameras[index].id === id) {
  6834. return this.cameras[index];
  6835. }
  6836. }
  6837. return null;
  6838. };
  6839. Scene.prototype.getCameraByName = function (name) {
  6840. for (var index = 0; index < this.cameras.length; index++) {
  6841. if (this.cameras[index].name === name) {
  6842. return this.cameras[index];
  6843. }
  6844. }
  6845. return null;
  6846. };
  6847. Scene.prototype.getLightByName = function (name) {
  6848. for (var index = 0; index < this.lights.length; index++) {
  6849. if (this.lights[index].name === name) {
  6850. return this.lights[index];
  6851. }
  6852. }
  6853. return null;
  6854. };
  6855. Scene.prototype.getLightByID = function (id) {
  6856. for (var index = 0; index < this.lights.length; index++) {
  6857. if (this.lights[index].id === id) {
  6858. return this.lights[index];
  6859. }
  6860. }
  6861. return null;
  6862. };
  6863. Scene.prototype.getGeometryByID = function (id) {
  6864. for (var index = 0; index < this._geometries.length; index++) {
  6865. if (this._geometries[index].id === id) {
  6866. return this._geometries[index];
  6867. }
  6868. }
  6869. return null;
  6870. };
  6871. Scene.prototype.pushGeometry = function (geometry, force) {
  6872. if (!force && this.getGeometryByID(geometry.id)) {
  6873. return false;
  6874. }
  6875. this._geometries.push(geometry);
  6876. return true;
  6877. };
  6878. Scene.prototype.getGeometries = function () {
  6879. return this._geometries;
  6880. };
  6881. Scene.prototype.getMeshByID = function (id) {
  6882. for (var index = 0; index < this.meshes.length; index++) {
  6883. if (this.meshes[index].id === id) {
  6884. return this.meshes[index];
  6885. }
  6886. }
  6887. return null;
  6888. };
  6889. Scene.prototype.getLastMeshByID = function (id) {
  6890. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6891. if (this.meshes[index].id === id) {
  6892. return this.meshes[index];
  6893. }
  6894. }
  6895. return null;
  6896. };
  6897. Scene.prototype.getLastEntryByID = function (id) {
  6898. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6899. if (this.meshes[index].id === id) {
  6900. return this.meshes[index];
  6901. }
  6902. }
  6903. for (index = this.cameras.length - 1; index >= 0; index--) {
  6904. if (this.cameras[index].id === id) {
  6905. return this.cameras[index];
  6906. }
  6907. }
  6908. for (index = this.lights.length - 1; index >= 0; index--) {
  6909. if (this.lights[index].id === id) {
  6910. return this.lights[index];
  6911. }
  6912. }
  6913. return null;
  6914. };
  6915. Scene.prototype.getMeshByName = function (name) {
  6916. for (var index = 0; index < this.meshes.length; index++) {
  6917. if (this.meshes[index].name === name) {
  6918. return this.meshes[index];
  6919. }
  6920. }
  6921. return null;
  6922. };
  6923. Scene.prototype.getLastSkeletonByID = function (id) {
  6924. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  6925. if (this.skeletons[index].id === id) {
  6926. return this.skeletons[index];
  6927. }
  6928. }
  6929. return null;
  6930. };
  6931. Scene.prototype.getSkeletonById = function (id) {
  6932. for (var index = 0; index < this.skeletons.length; index++) {
  6933. if (this.skeletons[index].id === id) {
  6934. return this.skeletons[index];
  6935. }
  6936. }
  6937. return null;
  6938. };
  6939. Scene.prototype.getSkeletonByName = function (name) {
  6940. for (var index = 0; index < this.skeletons.length; index++) {
  6941. if (this.skeletons[index].name === name) {
  6942. return this.skeletons[index];
  6943. }
  6944. }
  6945. return null;
  6946. };
  6947. Scene.prototype.isActiveMesh = function (mesh) {
  6948. return (this._activeMeshes.indexOf(mesh) !== -1);
  6949. };
  6950. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  6951. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  6952. var material = subMesh.getMaterial();
  6953. if (mesh.showSubMeshesBoundingBox) {
  6954. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  6955. }
  6956. if (material) {
  6957. if (material.getRenderTargetTextures) {
  6958. if (this._processedMaterials.indexOf(material) === -1) {
  6959. this._processedMaterials.push(material);
  6960. this._renderTargets.concat(material.getRenderTargetTextures());
  6961. }
  6962. }
  6963. this._activeVertices += subMesh.verticesCount;
  6964. this._renderingManager.dispatch(subMesh);
  6965. }
  6966. }
  6967. };
  6968. Scene.prototype._evaluateActiveMeshes = function () {
  6969. this._activeMeshes.reset();
  6970. this._renderingManager.reset();
  6971. this._processedMaterials.reset();
  6972. this._activeParticleSystems.reset();
  6973. this._activeSkeletons.reset();
  6974. this._boundingBoxRenderer.reset();
  6975. if (!this._frustumPlanes) {
  6976. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  6977. } else {
  6978. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  6979. }
  6980. var meshes;
  6981. var len;
  6982. if (this._selectionOctree) {
  6983. var selection = this._selectionOctree.select(this._frustumPlanes);
  6984. meshes = selection.data;
  6985. len = selection.length;
  6986. } else {
  6987. len = this.meshes.length;
  6988. meshes = this.meshes;
  6989. }
  6990. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  6991. var mesh = meshes[meshIndex];
  6992. if (mesh.isBlocked) {
  6993. continue;
  6994. }
  6995. this._totalVertices += mesh.getTotalVertices();
  6996. if (!mesh.isReady()) {
  6997. continue;
  6998. }
  6999. mesh.computeWorldMatrix();
  7000. mesh._preActivate();
  7001. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7002. this._meshesForIntersections.pushNoDuplicate(mesh);
  7003. }
  7004. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7005. this._activeMeshes.push(mesh);
  7006. mesh._activate(this._renderId);
  7007. this._activeMesh(mesh);
  7008. }
  7009. }
  7010. var beforeParticlesDate = BABYLON.Tools.Now;
  7011. if (this.particlesEnabled) {
  7012. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7013. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7014. var particleSystem = this.particleSystems[particleIndex];
  7015. if (!particleSystem.isStarted()) {
  7016. continue;
  7017. }
  7018. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7019. this._activeParticleSystems.push(particleSystem);
  7020. particleSystem.animate();
  7021. }
  7022. }
  7023. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7024. }
  7025. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7026. };
  7027. Scene.prototype._activeMesh = function (mesh) {
  7028. if (mesh.skeleton) {
  7029. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7030. }
  7031. if (mesh.showBoundingBox) {
  7032. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7033. }
  7034. var activeMesh = mesh.getLOD(this.activeCamera);
  7035. if (activeMesh && activeMesh.subMeshes) {
  7036. var len;
  7037. var subMeshes;
  7038. if (activeMesh._submeshesOctree && activeMesh.useOctreeForRenderingSelection) {
  7039. var intersections = activeMesh._submeshesOctree.select(this._frustumPlanes);
  7040. len = intersections.length;
  7041. subMeshes = intersections.data;
  7042. } else {
  7043. subMeshes = activeMesh.subMeshes;
  7044. len = subMeshes.length;
  7045. }
  7046. for (var subIndex = 0; subIndex < len; subIndex++) {
  7047. var subMesh = subMeshes[subIndex];
  7048. this._evaluateSubMesh(subMesh, activeMesh);
  7049. }
  7050. }
  7051. };
  7052. Scene.prototype.updateTransformMatrix = function (force) {
  7053. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7054. };
  7055. Scene.prototype._renderForCamera = function (camera) {
  7056. var engine = this._engine;
  7057. this.activeCamera = camera;
  7058. if (!this.activeCamera)
  7059. throw new Error("Active camera not set");
  7060. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7061. engine.setViewport(this.activeCamera.viewport);
  7062. this._renderId++;
  7063. this.updateTransformMatrix();
  7064. if (this.beforeCameraRender) {
  7065. this.beforeCameraRender(this.activeCamera);
  7066. }
  7067. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7068. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7069. this._evaluateActiveMeshes();
  7070. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7071. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7072. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7073. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7074. skeleton.prepare();
  7075. }
  7076. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7077. if (this.renderTargetsEnabled) {
  7078. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7079. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7080. var renderTarget = this._renderTargets.data[renderIndex];
  7081. if (renderTarget._shouldRender()) {
  7082. this._renderId++;
  7083. renderTarget.render();
  7084. }
  7085. }
  7086. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7087. this._renderId++;
  7088. }
  7089. if (this._renderTargets.length > 0) {
  7090. engine.restoreDefaultFramebuffer();
  7091. }
  7092. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7093. this.postProcessManager._prepareFrame();
  7094. var beforeRenderDate = BABYLON.Tools.Now;
  7095. if (this.layers.length) {
  7096. engine.setDepthBuffer(false);
  7097. var layerIndex;
  7098. var layer;
  7099. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7100. layer = this.layers[layerIndex];
  7101. if (layer.isBackground) {
  7102. layer.render();
  7103. }
  7104. }
  7105. engine.setDepthBuffer(true);
  7106. }
  7107. BABYLON.Tools.StartPerformanceCounter("Main render");
  7108. this._renderingManager.render(null, null, true, true);
  7109. BABYLON.Tools.EndPerformanceCounter("Main render");
  7110. this._boundingBoxRenderer.render();
  7111. if (this.lensFlaresEnabled) {
  7112. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7113. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7114. this.lensFlareSystems[lensFlareSystemIndex].render();
  7115. }
  7116. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7117. }
  7118. if (this.layers.length) {
  7119. engine.setDepthBuffer(false);
  7120. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7121. layer = this.layers[layerIndex];
  7122. if (!layer.isBackground) {
  7123. layer.render();
  7124. }
  7125. }
  7126. engine.setDepthBuffer(true);
  7127. }
  7128. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7129. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7130. this.activeCamera._updateFromScene();
  7131. this._renderTargets.reset();
  7132. if (this.afterCameraRender) {
  7133. this.afterCameraRender(this.activeCamera);
  7134. }
  7135. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7136. };
  7137. Scene.prototype._processSubCameras = function (camera) {
  7138. if (camera.subCameras.length == 0) {
  7139. this._renderForCamera(camera);
  7140. return;
  7141. }
  7142. for (var index = 0; index < camera.subCameras.length; index++) {
  7143. this._renderForCamera(camera.subCameras[index]);
  7144. }
  7145. this.activeCamera = camera;
  7146. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7147. this.activeCamera._updateFromScene();
  7148. };
  7149. Scene.prototype._checkIntersections = function () {
  7150. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7151. var sourceMesh = this._meshesForIntersections.data[index];
  7152. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7153. var action = sourceMesh.actionManager.actions[actionIndex];
  7154. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7155. var otherMesh = action.getTriggerParameter();
  7156. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7157. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7158. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7159. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7160. sourceMesh._intersectionsInProgress.push(otherMesh);
  7161. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7162. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7163. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7164. if (indexOfOther > -1) {
  7165. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7166. }
  7167. }
  7168. }
  7169. }
  7170. }
  7171. };
  7172. Scene.prototype.render = function () {
  7173. var startDate = BABYLON.Tools.Now;
  7174. this._particlesDuration = 0;
  7175. this._spritesDuration = 0;
  7176. this._activeParticles = 0;
  7177. this._renderDuration = 0;
  7178. this._evaluateActiveMeshesDuration = 0;
  7179. this._totalVertices = 0;
  7180. this._activeVertices = 0;
  7181. this._meshesForIntersections.reset();
  7182. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7183. if (this.actionManager) {
  7184. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7185. }
  7186. if (this.beforeRender) {
  7187. this.beforeRender();
  7188. }
  7189. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7190. this._onBeforeRenderCallbacks[callbackIndex]();
  7191. }
  7192. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7193. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7194. this._animate();
  7195. if (this._physicsEngine) {
  7196. BABYLON.Tools.StartPerformanceCounter("Physics");
  7197. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7198. BABYLON.Tools.EndPerformanceCounter("Physics");
  7199. }
  7200. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7201. var engine = this.getEngine();
  7202. if (this.renderTargetsEnabled) {
  7203. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7204. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7205. var renderTarget = this.customRenderTargets[customIndex];
  7206. if (renderTarget._shouldRender()) {
  7207. this._renderId++;
  7208. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7209. if (!this.activeCamera)
  7210. throw new Error("Active camera not set");
  7211. engine.setViewport(this.activeCamera.viewport);
  7212. this.updateTransformMatrix();
  7213. renderTarget.render();
  7214. }
  7215. }
  7216. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7217. this._renderId++;
  7218. }
  7219. if (this.customRenderTargets.length > 0) {
  7220. engine.restoreDefaultFramebuffer();
  7221. }
  7222. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7223. if (this.proceduralTexturesEnabled) {
  7224. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7225. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7226. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7227. if (proceduralTexture._shouldRender()) {
  7228. proceduralTexture.render();
  7229. }
  7230. }
  7231. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7232. }
  7233. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7234. if (this.shadowsEnabled) {
  7235. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7236. var light = this.lights[lightIndex];
  7237. var shadowGenerator = light.getShadowGenerator();
  7238. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7239. this._renderTargets.push(shadowGenerator.getShadowMap());
  7240. }
  7241. }
  7242. }
  7243. this.postProcessRenderPipelineManager.update();
  7244. if (this.activeCameras.length > 0) {
  7245. var currentRenderId = this._renderId;
  7246. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7247. this._renderId = currentRenderId;
  7248. this._processSubCameras(this.activeCameras[cameraIndex]);
  7249. }
  7250. } else {
  7251. if (!this.activeCamera) {
  7252. throw new Error("No camera defined");
  7253. }
  7254. this._processSubCameras(this.activeCamera);
  7255. }
  7256. this._checkIntersections();
  7257. if (this.afterRender) {
  7258. this.afterRender();
  7259. }
  7260. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7261. this._toBeDisposed.data[index].dispose();
  7262. this._toBeDisposed[index] = null;
  7263. }
  7264. this._toBeDisposed.reset();
  7265. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7266. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7267. };
  7268. Scene.prototype.dispose = function () {
  7269. this.beforeRender = null;
  7270. this.afterRender = null;
  7271. this.skeletons = [];
  7272. this._boundingBoxRenderer.dispose();
  7273. if (this.onDispose) {
  7274. this.onDispose();
  7275. }
  7276. this.detachControl();
  7277. var canvas = this._engine.getRenderingCanvas();
  7278. var index;
  7279. for (index = 0; index < this.cameras.length; index++) {
  7280. this.cameras[index].detachControl(canvas);
  7281. }
  7282. while (this.lights.length) {
  7283. this.lights[0].dispose();
  7284. }
  7285. while (this.meshes.length) {
  7286. this.meshes[0].dispose(true);
  7287. }
  7288. while (this.cameras.length) {
  7289. this.cameras[0].dispose();
  7290. }
  7291. while (this.materials.length) {
  7292. this.materials[0].dispose();
  7293. }
  7294. while (this.particleSystems.length) {
  7295. this.particleSystems[0].dispose();
  7296. }
  7297. while (this.spriteManagers.length) {
  7298. this.spriteManagers[0].dispose();
  7299. }
  7300. while (this.layers.length) {
  7301. this.layers[0].dispose();
  7302. }
  7303. while (this.textures.length) {
  7304. this.textures[0].dispose();
  7305. }
  7306. this.postProcessManager.dispose();
  7307. if (this._physicsEngine) {
  7308. this.disablePhysicsEngine();
  7309. }
  7310. index = this._engine.scenes.indexOf(this);
  7311. if (index > -1) {
  7312. this._engine.scenes.splice(index, 1);
  7313. }
  7314. this._engine.wipeCaches();
  7315. };
  7316. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7317. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7318. position.divideToRef(collider.radius, this._scaledPosition);
  7319. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7320. collider.retry = 0;
  7321. collider.initialVelocity = this._scaledVelocity;
  7322. collider.initialPosition = this._scaledPosition;
  7323. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7324. finalPosition.multiplyInPlace(collider.radius);
  7325. };
  7326. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7327. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7328. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7329. if (collider.retry >= maximumRetry) {
  7330. finalPosition.copyFrom(position);
  7331. return;
  7332. }
  7333. collider._initialize(position, velocity, closeDistance);
  7334. for (var index = 0; index < this.meshes.length; index++) {
  7335. var mesh = this.meshes[index];
  7336. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7337. mesh._checkCollision(collider);
  7338. }
  7339. }
  7340. if (!collider.collisionFound) {
  7341. position.addToRef(velocity, finalPosition);
  7342. return;
  7343. }
  7344. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7345. collider._getResponse(position, velocity);
  7346. }
  7347. if (velocity.length() <= closeDistance) {
  7348. finalPosition.copyFrom(position);
  7349. return;
  7350. }
  7351. collider.retry++;
  7352. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7353. };
  7354. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7355. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7356. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7357. if (!this._selectionOctree) {
  7358. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7359. }
  7360. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7361. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7362. for (var index = 0; index < this.meshes.length; index++) {
  7363. var mesh = this.meshes[index];
  7364. mesh.computeWorldMatrix(true);
  7365. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7366. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7367. BABYLON.Tools.CheckExtends(minBox, min, max);
  7368. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7369. }
  7370. this._selectionOctree.update(min, max, this.meshes);
  7371. return this._selectionOctree;
  7372. };
  7373. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7374. var engine = this._engine;
  7375. if (!camera) {
  7376. if (!this.activeCamera)
  7377. throw new Error("Active camera not set");
  7378. camera = this.activeCamera;
  7379. }
  7380. var cameraViewport = camera.viewport;
  7381. var viewport = cameraViewport.toGlobal(engine);
  7382. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7383. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7384. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7385. };
  7386. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7387. var pickingInfo = null;
  7388. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7389. var mesh = this.meshes[meshIndex];
  7390. if (predicate) {
  7391. if (!predicate(mesh)) {
  7392. continue;
  7393. }
  7394. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7395. continue;
  7396. }
  7397. var world = mesh.getWorldMatrix();
  7398. var ray = rayFunction(world);
  7399. var result = mesh.intersects(ray, fastCheck);
  7400. if (!result || !result.hit)
  7401. continue;
  7402. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7403. continue;
  7404. pickingInfo = result;
  7405. if (fastCheck) {
  7406. break;
  7407. }
  7408. }
  7409. return pickingInfo || new BABYLON.PickingInfo();
  7410. };
  7411. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7412. var _this = this;
  7413. return this._internalPick(function (world) {
  7414. return _this.createPickingRay(x, y, world, camera);
  7415. }, predicate, fastCheck);
  7416. };
  7417. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7418. var _this = this;
  7419. return this._internalPick(function (world) {
  7420. if (!_this._pickWithRayInverseMatrix) {
  7421. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7422. }
  7423. world.invertToRef(_this._pickWithRayInverseMatrix);
  7424. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7425. }, predicate, fastCheck);
  7426. };
  7427. Scene.prototype.setPointerOverMesh = function (mesh) {
  7428. if (this._pointerOverMesh === mesh) {
  7429. return;
  7430. }
  7431. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7432. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7433. }
  7434. this._pointerOverMesh = mesh;
  7435. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7436. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7437. }
  7438. };
  7439. Scene.prototype.getPointerOverMesh = function () {
  7440. return this._pointerOverMesh;
  7441. };
  7442. Scene.prototype.getPhysicsEngine = function () {
  7443. return this._physicsEngine;
  7444. };
  7445. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7446. if (this._physicsEngine) {
  7447. return true;
  7448. }
  7449. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7450. if (!this._physicsEngine.isSupported()) {
  7451. this._physicsEngine = null;
  7452. return false;
  7453. }
  7454. this._physicsEngine._initialize(gravity);
  7455. return true;
  7456. };
  7457. Scene.prototype.disablePhysicsEngine = function () {
  7458. if (!this._physicsEngine) {
  7459. return;
  7460. }
  7461. this._physicsEngine.dispose();
  7462. this._physicsEngine = undefined;
  7463. };
  7464. Scene.prototype.isPhysicsEnabled = function () {
  7465. return this._physicsEngine !== undefined;
  7466. };
  7467. Scene.prototype.setGravity = function (gravity) {
  7468. if (!this._physicsEngine) {
  7469. return;
  7470. }
  7471. this._physicsEngine._setGravity(gravity);
  7472. };
  7473. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7474. if (parts.parts) {
  7475. options = parts;
  7476. parts = parts.parts;
  7477. }
  7478. if (!this._physicsEngine) {
  7479. return null;
  7480. }
  7481. for (var index = 0; index < parts.length; index++) {
  7482. var mesh = parts[index].mesh;
  7483. mesh._physicImpostor = parts[index].impostor;
  7484. mesh._physicsMass = options.mass / parts.length;
  7485. mesh._physicsFriction = options.friction;
  7486. mesh._physicRestitution = options.restitution;
  7487. }
  7488. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7489. };
  7490. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7491. for (var index = 0; index < compound.parts.length; index++) {
  7492. var mesh = compound.parts[index].mesh;
  7493. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7494. this._physicsEngine._unregisterMesh(mesh);
  7495. }
  7496. };
  7497. Scene.prototype._getByTags = function (list, tagsQuery) {
  7498. if (tagsQuery === undefined) {
  7499. return list;
  7500. }
  7501. var listByTags = [];
  7502. for (var i in list) {
  7503. var item = list[i];
  7504. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7505. listByTags.push(item);
  7506. }
  7507. }
  7508. return listByTags;
  7509. };
  7510. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7511. return this._getByTags(this.meshes, tagsQuery);
  7512. };
  7513. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7514. return this._getByTags(this.cameras, tagsQuery);
  7515. };
  7516. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7517. return this._getByTags(this.lights, tagsQuery);
  7518. };
  7519. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7520. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7521. };
  7522. Scene.FOGMODE_NONE = 0;
  7523. Scene.FOGMODE_EXP = 1;
  7524. Scene.FOGMODE_EXP2 = 2;
  7525. Scene.FOGMODE_LINEAR = 3;
  7526. Scene.MinDeltaTime = 1.0;
  7527. Scene.MaxDeltaTime = 1000.0;
  7528. return Scene;
  7529. })();
  7530. BABYLON.Scene = Scene;
  7531. })(BABYLON || (BABYLON = {}));
  7532. var BABYLON;
  7533. (function (BABYLON) {
  7534. var VertexBuffer = (function () {
  7535. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  7536. if (engine instanceof BABYLON.Mesh) {
  7537. this._engine = engine.getScene().getEngine();
  7538. } else {
  7539. this._engine = engine;
  7540. }
  7541. this._updatable = updatable;
  7542. this._data = data;
  7543. if (!postponeInternalCreation) {
  7544. this.create();
  7545. }
  7546. this._kind = kind;
  7547. if (stride) {
  7548. this._strideSize = stride;
  7549. return;
  7550. }
  7551. switch (kind) {
  7552. case VertexBuffer.PositionKind:
  7553. this._strideSize = 3;
  7554. break;
  7555. case VertexBuffer.NormalKind:
  7556. this._strideSize = 3;
  7557. break;
  7558. case VertexBuffer.UVKind:
  7559. this._strideSize = 2;
  7560. break;
  7561. case VertexBuffer.UV2Kind:
  7562. this._strideSize = 2;
  7563. break;
  7564. case VertexBuffer.ColorKind:
  7565. this._strideSize = 3;
  7566. break;
  7567. case VertexBuffer.MatricesIndicesKind:
  7568. this._strideSize = 4;
  7569. break;
  7570. case VertexBuffer.MatricesWeightsKind:
  7571. this._strideSize = 4;
  7572. break;
  7573. }
  7574. }
  7575. VertexBuffer.prototype.isUpdatable = function () {
  7576. return this._updatable;
  7577. };
  7578. VertexBuffer.prototype.getData = function () {
  7579. return this._data;
  7580. };
  7581. VertexBuffer.prototype.getBuffer = function () {
  7582. return this._buffer;
  7583. };
  7584. VertexBuffer.prototype.getStrideSize = function () {
  7585. return this._strideSize;
  7586. };
  7587. VertexBuffer.prototype.create = function (data) {
  7588. if (!data && this._buffer) {
  7589. return;
  7590. }
  7591. data = data || this._data;
  7592. if (!this._buffer) {
  7593. if (this._updatable) {
  7594. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7595. } else {
  7596. this._buffer = this._engine.createVertexBuffer(data);
  7597. }
  7598. }
  7599. if (this._updatable) {
  7600. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7601. this._data = data;
  7602. }
  7603. };
  7604. VertexBuffer.prototype.update = function (data) {
  7605. this.create(data);
  7606. };
  7607. VertexBuffer.prototype.updateDirectly = function (data) {
  7608. if (!this._buffer) {
  7609. return;
  7610. }
  7611. if (this._updatable) {
  7612. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7613. this._data = null;
  7614. }
  7615. };
  7616. VertexBuffer.prototype.dispose = function () {
  7617. if (!this._buffer) {
  7618. return;
  7619. }
  7620. if (this._engine._releaseBuffer(this._buffer)) {
  7621. this._buffer = null;
  7622. }
  7623. };
  7624. Object.defineProperty(VertexBuffer, "PositionKind", {
  7625. get: function () {
  7626. return VertexBuffer._PositionKind;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(VertexBuffer, "NormalKind", {
  7632. get: function () {
  7633. return VertexBuffer._NormalKind;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(VertexBuffer, "UVKind", {
  7639. get: function () {
  7640. return VertexBuffer._UVKind;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7646. get: function () {
  7647. return VertexBuffer._UV2Kind;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(VertexBuffer, "ColorKind", {
  7653. get: function () {
  7654. return VertexBuffer._ColorKind;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7660. get: function () {
  7661. return VertexBuffer._MatricesIndicesKind;
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7667. get: function () {
  7668. return VertexBuffer._MatricesWeightsKind;
  7669. },
  7670. enumerable: true,
  7671. configurable: true
  7672. });
  7673. VertexBuffer._PositionKind = "position";
  7674. VertexBuffer._NormalKind = "normal";
  7675. VertexBuffer._UVKind = "uv";
  7676. VertexBuffer._UV2Kind = "uv2";
  7677. VertexBuffer._ColorKind = "color";
  7678. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7679. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7680. return VertexBuffer;
  7681. })();
  7682. BABYLON.VertexBuffer = VertexBuffer;
  7683. })(BABYLON || (BABYLON = {}));
  7684. var __extends = this.__extends || function (d, b) {
  7685. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7686. function __() { this.constructor = d; }
  7687. __.prototype = b.prototype;
  7688. d.prototype = new __();
  7689. };
  7690. var BABYLON;
  7691. (function (BABYLON) {
  7692. var AbstractMesh = (function (_super) {
  7693. __extends(AbstractMesh, _super);
  7694. function AbstractMesh(name, scene) {
  7695. _super.call(this, name, scene);
  7696. this.position = new BABYLON.Vector3(0, 0, 0);
  7697. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7698. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7699. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7700. this.visibility = 1.0;
  7701. this.infiniteDistance = false;
  7702. this.isVisible = true;
  7703. this.isPickable = true;
  7704. this.showBoundingBox = false;
  7705. this.showSubMeshesBoundingBox = false;
  7706. this.onDispose = null;
  7707. this.checkCollisions = false;
  7708. this.isBlocker = false;
  7709. this.renderingGroupId = 0;
  7710. this.receiveShadows = false;
  7711. this.renderOutline = false;
  7712. this.outlineColor = BABYLON.Color3.Red();
  7713. this.outlineWidth = 0.02;
  7714. this.useOctreeForRenderingSelection = true;
  7715. this.useOctreeForPicking = true;
  7716. this.useOctreeForCollisions = true;
  7717. this.layerMask = 0xFFFFFFFF;
  7718. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7719. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7720. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7721. this._collider = new BABYLON.Collider();
  7722. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7723. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7724. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7725. this._localScaling = BABYLON.Matrix.Zero();
  7726. this._localRotation = BABYLON.Matrix.Zero();
  7727. this._localTranslation = BABYLON.Matrix.Zero();
  7728. this._localBillboard = BABYLON.Matrix.Zero();
  7729. this._localPivotScaling = BABYLON.Matrix.Zero();
  7730. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7731. this._localWorld = BABYLON.Matrix.Zero();
  7732. this._worldMatrix = BABYLON.Matrix.Zero();
  7733. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7734. this._absolutePosition = BABYLON.Vector3.Zero();
  7735. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7736. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7737. this._isDirty = false;
  7738. this._pivotMatrix = BABYLON.Matrix.Identity();
  7739. this._isDisposed = false;
  7740. this._renderId = 0;
  7741. this._intersectionsInProgress = new Array();
  7742. scene.meshes.push(this);
  7743. }
  7744. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7745. get: function () {
  7746. return AbstractMesh._BILLBOARDMODE_NONE;
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7752. get: function () {
  7753. return AbstractMesh._BILLBOARDMODE_X;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7759. get: function () {
  7760. return AbstractMesh._BILLBOARDMODE_Y;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7766. get: function () {
  7767. return AbstractMesh._BILLBOARDMODE_Z;
  7768. },
  7769. enumerable: true,
  7770. configurable: true
  7771. });
  7772. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7773. get: function () {
  7774. return AbstractMesh._BILLBOARDMODE_ALL;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7780. get: function () {
  7781. return false;
  7782. },
  7783. enumerable: true,
  7784. configurable: true
  7785. });
  7786. AbstractMesh.prototype.getLOD = function (camera) {
  7787. return this;
  7788. };
  7789. AbstractMesh.prototype.getTotalVertices = function () {
  7790. return 0;
  7791. };
  7792. AbstractMesh.prototype.getIndices = function () {
  7793. return null;
  7794. };
  7795. AbstractMesh.prototype.getVerticesData = function (kind) {
  7796. return null;
  7797. };
  7798. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7799. return false;
  7800. };
  7801. AbstractMesh.prototype.getBoundingInfo = function () {
  7802. if (!this._boundingInfo) {
  7803. this._updateBoundingInfo();
  7804. }
  7805. return this._boundingInfo;
  7806. };
  7807. AbstractMesh.prototype._preActivate = function () {
  7808. };
  7809. AbstractMesh.prototype._activate = function (renderId) {
  7810. this._renderId = renderId;
  7811. };
  7812. AbstractMesh.prototype.getWorldMatrix = function () {
  7813. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7814. this.computeWorldMatrix();
  7815. }
  7816. return this._worldMatrix;
  7817. };
  7818. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7819. get: function () {
  7820. return this._worldMatrix;
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7826. get: function () {
  7827. return this._absolutePosition;
  7828. },
  7829. enumerable: true,
  7830. configurable: true
  7831. });
  7832. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7833. if (!this.rotationQuaternion) {
  7834. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7835. this.rotation = BABYLON.Vector3.Zero();
  7836. }
  7837. if (!space || space == 0 /* LOCAL */) {
  7838. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7839. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7840. } else {
  7841. if (this.parent) {
  7842. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7843. invertParentWorldMatrix.invert();
  7844. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7845. }
  7846. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7847. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7848. }
  7849. };
  7850. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7851. var displacementVector = axis.scale(distance);
  7852. if (!space || space == 0 /* LOCAL */) {
  7853. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7854. this.setPositionWithLocalVector(tempV3);
  7855. } else {
  7856. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7857. }
  7858. };
  7859. AbstractMesh.prototype.getAbsolutePosition = function () {
  7860. this.computeWorldMatrix();
  7861. return this._absolutePosition;
  7862. };
  7863. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7864. if (!absolutePosition) {
  7865. return;
  7866. }
  7867. var absolutePositionX;
  7868. var absolutePositionY;
  7869. var absolutePositionZ;
  7870. if (absolutePosition.x === undefined) {
  7871. if (arguments.length < 3) {
  7872. return;
  7873. }
  7874. absolutePositionX = arguments[0];
  7875. absolutePositionY = arguments[1];
  7876. absolutePositionZ = arguments[2];
  7877. } else {
  7878. absolutePositionX = absolutePosition.x;
  7879. absolutePositionY = absolutePosition.y;
  7880. absolutePositionZ = absolutePosition.z;
  7881. }
  7882. if (this.parent) {
  7883. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7884. invertParentWorldMatrix.invert();
  7885. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7886. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7887. } else {
  7888. this.position.x = absolutePositionX;
  7889. this.position.y = absolutePositionY;
  7890. this.position.z = absolutePositionZ;
  7891. }
  7892. };
  7893. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7894. this._pivotMatrix = matrix;
  7895. this._cache.pivotMatrixUpdated = true;
  7896. };
  7897. AbstractMesh.prototype.getPivotMatrix = function () {
  7898. return this._pivotMatrix;
  7899. };
  7900. AbstractMesh.prototype._isSynchronized = function () {
  7901. if (this._isDirty) {
  7902. return false;
  7903. }
  7904. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7905. return false;
  7906. if (this._cache.pivotMatrixUpdated) {
  7907. return false;
  7908. }
  7909. if (this.infiniteDistance) {
  7910. return false;
  7911. }
  7912. if (!this._cache.position.equals(this.position))
  7913. return false;
  7914. if (this.rotationQuaternion) {
  7915. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7916. return false;
  7917. } else {
  7918. if (!this._cache.rotation.equals(this.rotation))
  7919. return false;
  7920. }
  7921. if (!this._cache.scaling.equals(this.scaling))
  7922. return false;
  7923. return true;
  7924. };
  7925. AbstractMesh.prototype._initCache = function () {
  7926. _super.prototype._initCache.call(this);
  7927. this._cache.localMatrixUpdated = false;
  7928. this._cache.position = BABYLON.Vector3.Zero();
  7929. this._cache.scaling = BABYLON.Vector3.Zero();
  7930. this._cache.rotation = BABYLON.Vector3.Zero();
  7931. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7932. };
  7933. AbstractMesh.prototype.markAsDirty = function (property) {
  7934. if (property === "rotation") {
  7935. this.rotationQuaternion = null;
  7936. }
  7937. this._currentRenderId = Number.MAX_VALUE;
  7938. this._isDirty = true;
  7939. };
  7940. AbstractMesh.prototype._updateBoundingInfo = function () {
  7941. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7942. this._boundingInfo._update(this.worldMatrixFromCache);
  7943. if (!this.subMeshes) {
  7944. return;
  7945. }
  7946. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7947. var subMesh = this.subMeshes[subIndex];
  7948. subMesh.updateBoundingInfo(this.worldMatrixFromCache);
  7949. }
  7950. };
  7951. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7952. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  7953. return this._worldMatrix;
  7954. }
  7955. this._cache.position.copyFrom(this.position);
  7956. this._cache.scaling.copyFrom(this.scaling);
  7957. this._cache.pivotMatrixUpdated = false;
  7958. this._currentRenderId = this.getScene().getRenderId();
  7959. this._isDirty = false;
  7960. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7961. if (this.rotationQuaternion) {
  7962. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7963. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7964. } else {
  7965. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7966. this._cache.rotation.copyFrom(this.rotation);
  7967. }
  7968. if (this.infiniteDistance && !this.parent) {
  7969. var camera = this.getScene().activeCamera;
  7970. var cameraWorldMatrix = camera.getWorldMatrix();
  7971. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7972. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7973. } else {
  7974. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7975. }
  7976. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7977. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7978. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7979. var localPosition = this.position.clone();
  7980. var zero = this.getScene().activeCamera.position.clone();
  7981. if (this.parent && this.parent.position) {
  7982. localPosition.addInPlace(this.parent.position);
  7983. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7984. }
  7985. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  7986. zero = this.getScene().activeCamera.position;
  7987. } else {
  7988. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  7989. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7990. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  7991. zero.y = localPosition.y + 0.001;
  7992. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  7993. zero.z = localPosition.z + 0.001;
  7994. }
  7995. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7996. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7997. this._localBillboard.invert();
  7998. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7999. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8000. }
  8001. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8002. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8003. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8004. } else {
  8005. this._worldMatrix.copyFrom(this._localWorld);
  8006. }
  8007. this._updateBoundingInfo();
  8008. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8009. return this._worldMatrix;
  8010. };
  8011. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8012. this.computeWorldMatrix();
  8013. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8014. };
  8015. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8016. this.computeWorldMatrix();
  8017. var invLocalWorldMatrix = this._localWorld.clone();
  8018. invLocalWorldMatrix.invert();
  8019. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8020. };
  8021. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8022. this.computeWorldMatrix();
  8023. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8024. };
  8025. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8026. yawCor = yawCor || 0;
  8027. pitchCor = pitchCor || 0;
  8028. rollCor = rollCor || 0;
  8029. var dv = targetPoint.subtract(this.position);
  8030. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8031. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8032. var pitch = Math.atan2(dv.y, len);
  8033. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8034. };
  8035. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8036. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8037. return false;
  8038. }
  8039. return true;
  8040. };
  8041. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8042. if (!camera) {
  8043. camera = this.getScene().activeCamera;
  8044. }
  8045. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8046. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8047. return false;
  8048. }
  8049. return true;
  8050. };
  8051. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8052. if (!this._boundingInfo || !mesh._boundingInfo) {
  8053. return false;
  8054. }
  8055. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8056. };
  8057. AbstractMesh.prototype.intersectsPoint = function (point) {
  8058. if (!this._boundingInfo) {
  8059. return false;
  8060. }
  8061. return this._boundingInfo.intersectsPoint(point);
  8062. };
  8063. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8064. var physicsEngine = this.getScene().getPhysicsEngine();
  8065. if (!physicsEngine) {
  8066. return;
  8067. }
  8068. if (impostor.impostor) {
  8069. options = impostor;
  8070. impostor = impostor.impostor;
  8071. }
  8072. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8073. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8074. physicsEngine._unregisterMesh(this);
  8075. return;
  8076. }
  8077. options.mass = options.mass || 0;
  8078. options.friction = options.friction || 0.2;
  8079. options.restitution = options.restitution || 0.2;
  8080. this._physicImpostor = impostor;
  8081. this._physicsMass = options.mass;
  8082. this._physicsFriction = options.friction;
  8083. this._physicRestitution = options.restitution;
  8084. physicsEngine._registerMesh(this, impostor, options);
  8085. };
  8086. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8087. if (!this._physicImpostor) {
  8088. return BABYLON.PhysicsEngine.NoImpostor;
  8089. }
  8090. return this._physicImpostor;
  8091. };
  8092. AbstractMesh.prototype.getPhysicsMass = function () {
  8093. if (!this._physicsMass) {
  8094. return 0;
  8095. }
  8096. return this._physicsMass;
  8097. };
  8098. AbstractMesh.prototype.getPhysicsFriction = function () {
  8099. if (!this._physicsFriction) {
  8100. return 0;
  8101. }
  8102. return this._physicsFriction;
  8103. };
  8104. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8105. if (!this._physicRestitution) {
  8106. return 0;
  8107. }
  8108. return this._physicRestitution;
  8109. };
  8110. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8111. if (!camera) {
  8112. camera = this.getScene().activeCamera;
  8113. }
  8114. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8115. };
  8116. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8117. if (!camera) {
  8118. camera = this.getScene().activeCamera;
  8119. }
  8120. return this.absolutePosition.subtract(camera.position);
  8121. };
  8122. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8123. if (!this._physicImpostor) {
  8124. return;
  8125. }
  8126. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8127. };
  8128. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8129. if (!this._physicImpostor) {
  8130. return;
  8131. }
  8132. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8133. };
  8134. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8135. if (!this._physicImpostor) {
  8136. return;
  8137. }
  8138. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8139. };
  8140. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8141. var globalPosition = this.getAbsolutePosition();
  8142. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8143. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8144. this._collider.radius = this.ellipsoid;
  8145. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8146. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8147. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8148. this.position.addInPlace(this._diffPositionForCollisions);
  8149. }
  8150. };
  8151. /**
  8152. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8153. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8154. */
  8155. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8156. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8157. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8158. if (!this._submeshesOctree) {
  8159. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8160. }
  8161. this.computeWorldMatrix(true);
  8162. var bbox = this.getBoundingInfo().boundingBox;
  8163. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8164. return this._submeshesOctree;
  8165. };
  8166. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8167. this._generatePointsArray();
  8168. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8169. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8170. subMesh._lastColliderWorldVertices = [];
  8171. subMesh._trianglePlanes = [];
  8172. var start = subMesh.verticesStart;
  8173. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8174. for (var i = start; i < end; i++) {
  8175. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8176. }
  8177. }
  8178. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8179. };
  8180. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8181. var subMeshes;
  8182. var len;
  8183. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8184. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8185. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8186. len = intersections.length;
  8187. subMeshes = intersections.data;
  8188. } else {
  8189. subMeshes = this.subMeshes;
  8190. len = subMeshes.length;
  8191. }
  8192. for (var index = 0; index < len; index++) {
  8193. var subMesh = subMeshes[index];
  8194. if (len > 1 && !subMesh._checkCollision(collider))
  8195. continue;
  8196. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8197. }
  8198. };
  8199. AbstractMesh.prototype._checkCollision = function (collider) {
  8200. if (!this._boundingInfo._checkCollision(collider))
  8201. return;
  8202. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8203. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8204. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8205. };
  8206. AbstractMesh.prototype._generatePointsArray = function () {
  8207. return false;
  8208. };
  8209. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8210. var pickingInfo = new BABYLON.PickingInfo();
  8211. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8212. return pickingInfo;
  8213. }
  8214. if (!this._generatePointsArray()) {
  8215. return pickingInfo;
  8216. }
  8217. var intersectInfo = null;
  8218. var subMeshes;
  8219. var len;
  8220. if (this._submeshesOctree && this.useOctreeForPicking) {
  8221. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8222. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8223. len = intersections.length;
  8224. subMeshes = intersections.data;
  8225. } else {
  8226. subMeshes = this.subMeshes;
  8227. len = subMeshes.length;
  8228. }
  8229. for (var index = 0; index < len; index++) {
  8230. var subMesh = subMeshes[index];
  8231. if (len > 1 && !subMesh.canIntersects(ray))
  8232. continue;
  8233. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8234. if (currentIntersectInfo) {
  8235. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8236. intersectInfo = currentIntersectInfo;
  8237. if (fastCheck) {
  8238. break;
  8239. }
  8240. }
  8241. }
  8242. }
  8243. if (intersectInfo) {
  8244. var world = this.getWorldMatrix();
  8245. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8246. var direction = ray.direction.clone();
  8247. direction.normalize();
  8248. direction = direction.scale(intersectInfo.distance);
  8249. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8250. var pickedPoint = worldOrigin.add(worldDirection);
  8251. pickingInfo.hit = true;
  8252. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8253. pickingInfo.pickedPoint = pickedPoint;
  8254. pickingInfo.pickedMesh = this;
  8255. pickingInfo.bu = intersectInfo.bu;
  8256. pickingInfo.bv = intersectInfo.bv;
  8257. pickingInfo.faceId = intersectInfo.faceId;
  8258. return pickingInfo;
  8259. }
  8260. return pickingInfo;
  8261. };
  8262. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8263. return null;
  8264. };
  8265. AbstractMesh.prototype.releaseSubMeshes = function () {
  8266. if (this.subMeshes) {
  8267. while (this.subMeshes.length) {
  8268. this.subMeshes[0].dispose();
  8269. }
  8270. } else {
  8271. this.subMeshes = new Array();
  8272. }
  8273. };
  8274. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8275. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8276. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8277. }
  8278. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8279. var other = this._intersectionsInProgress[index];
  8280. var pos = other._intersectionsInProgress.indexOf(this);
  8281. other._intersectionsInProgress.splice(pos, 1);
  8282. }
  8283. this._intersectionsInProgress = [];
  8284. this.releaseSubMeshes();
  8285. var index = this.getScene().meshes.indexOf(this);
  8286. if (index != -1) {
  8287. this.getScene().meshes.splice(index, 1);
  8288. }
  8289. if (!doNotRecurse) {
  8290. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8291. if (this.getScene().particleSystems[index].emitter == this) {
  8292. this.getScene().particleSystems[index].dispose();
  8293. index--;
  8294. }
  8295. }
  8296. var objects = this.getScene().meshes.slice(0);
  8297. for (index = 0; index < objects.length; index++) {
  8298. if (objects[index].parent == this) {
  8299. objects[index].dispose();
  8300. }
  8301. }
  8302. } else {
  8303. for (index = 0; index < this.getScene().meshes.length; index++) {
  8304. var obj = this.getScene().meshes[index];
  8305. if (obj.parent === this) {
  8306. obj.parent = null;
  8307. obj.computeWorldMatrix(true);
  8308. }
  8309. }
  8310. }
  8311. this._isDisposed = true;
  8312. if (this.onDispose) {
  8313. this.onDispose();
  8314. }
  8315. };
  8316. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8317. AbstractMesh._BILLBOARDMODE_X = 1;
  8318. AbstractMesh._BILLBOARDMODE_Y = 2;
  8319. AbstractMesh._BILLBOARDMODE_Z = 4;
  8320. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8321. return AbstractMesh;
  8322. })(BABYLON.Node);
  8323. BABYLON.AbstractMesh = AbstractMesh;
  8324. })(BABYLON || (BABYLON = {}));
  8325. var __extends = this.__extends || function (d, b) {
  8326. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8327. function __() { this.constructor = d; }
  8328. __.prototype = b.prototype;
  8329. d.prototype = new __();
  8330. };
  8331. var BABYLON;
  8332. (function (BABYLON) {
  8333. var _InstancesBatch = (function () {
  8334. function _InstancesBatch() {
  8335. this.mustReturn = false;
  8336. this.visibleInstances = new Array();
  8337. this.renderSelf = new Array();
  8338. }
  8339. return _InstancesBatch;
  8340. })();
  8341. BABYLON._InstancesBatch = _InstancesBatch;
  8342. var Mesh = (function (_super) {
  8343. __extends(Mesh, _super);
  8344. function Mesh(name, scene) {
  8345. _super.call(this, name, scene);
  8346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8347. this.instances = new Array();
  8348. this._LODLevels = new Array();
  8349. this._onBeforeRenderCallbacks = new Array();
  8350. this._onAfterRenderCallbacks = new Array();
  8351. this._visibleInstances = {};
  8352. this._renderIdForInstances = new Array();
  8353. this._batchCache = new _InstancesBatch();
  8354. this._instancesBufferSize = 32 * 16 * 4;
  8355. }
  8356. Mesh.prototype._sortLODLevels = function () {
  8357. this._LODLevels.sort(function (a, b) {
  8358. if (a.distance < b.distance) {
  8359. return 1;
  8360. }
  8361. if (a.distance > b.distance) {
  8362. return -1;
  8363. }
  8364. return 0;
  8365. });
  8366. };
  8367. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8368. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8369. this._LODLevels.push(level);
  8370. if (mesh) {
  8371. mesh._attachedLODLevel = level;
  8372. }
  8373. this._sortLODLevels();
  8374. return this;
  8375. };
  8376. Mesh.prototype.removeLODLevel = function (mesh) {
  8377. if (mesh && !mesh._attachedLODLevel) {
  8378. return this;
  8379. }
  8380. var index;
  8381. if (mesh) {
  8382. index = this._LODLevels.indexOf(mesh._attachedLODLevel);
  8383. mesh._attachedLODLevel = null;
  8384. this._LODLevels.splice(index, 1);
  8385. this._sortLODLevels();
  8386. } else {
  8387. for (index = 0; index < this._LODLevels.length; index++) {
  8388. if (this._LODLevels[index].mesh === null) {
  8389. this._LODLevels.splice(index, 1);
  8390. break;
  8391. }
  8392. }
  8393. }
  8394. return this;
  8395. };
  8396. Mesh.prototype.getLOD = function (camera) {
  8397. if (!this._LODLevels || this._LODLevels.length === 0) {
  8398. return this;
  8399. }
  8400. var distanceToCamera = this.getBoundingInfo().boundingSphere.centerWorld.subtract(camera.position).length();
  8401. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8402. return this;
  8403. }
  8404. for (var index = 0; index < this._LODLevels.length; index++) {
  8405. var level = this._LODLevels[index];
  8406. if (level.distance < distanceToCamera) {
  8407. if (level.mesh) {
  8408. level.mesh._worldMatrix = this._worldMatrix;
  8409. }
  8410. return level.mesh;
  8411. }
  8412. }
  8413. return this;
  8414. };
  8415. Object.defineProperty(Mesh.prototype, "geometry", {
  8416. get: function () {
  8417. return this._geometry;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Mesh.prototype.getTotalVertices = function () {
  8423. if (!this._geometry) {
  8424. return 0;
  8425. }
  8426. return this._geometry.getTotalVertices();
  8427. };
  8428. Mesh.prototype.getVerticesData = function (kind) {
  8429. if (!this._geometry) {
  8430. return null;
  8431. }
  8432. return this._geometry.getVerticesData(kind);
  8433. };
  8434. Mesh.prototype.getVertexBuffer = function (kind) {
  8435. if (!this._geometry) {
  8436. return undefined;
  8437. }
  8438. return this._geometry.getVertexBuffer(kind);
  8439. };
  8440. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8441. if (!this._geometry) {
  8442. if (this._delayInfo) {
  8443. return this._delayInfo.indexOf(kind) !== -1;
  8444. }
  8445. return false;
  8446. }
  8447. return this._geometry.isVerticesDataPresent(kind);
  8448. };
  8449. Mesh.prototype.getVerticesDataKinds = function () {
  8450. if (!this._geometry) {
  8451. var result = [];
  8452. if (this._delayInfo) {
  8453. for (var kind in this._delayInfo) {
  8454. result.push(kind);
  8455. }
  8456. }
  8457. return result;
  8458. }
  8459. return this._geometry.getVerticesDataKinds();
  8460. };
  8461. Mesh.prototype.getTotalIndices = function () {
  8462. if (!this._geometry) {
  8463. return 0;
  8464. }
  8465. return this._geometry.getTotalIndices();
  8466. };
  8467. Mesh.prototype.getIndices = function () {
  8468. if (!this._geometry) {
  8469. return [];
  8470. }
  8471. return this._geometry.getIndices();
  8472. };
  8473. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8474. get: function () {
  8475. return this._attachedLODLevel !== null && this._attachedLODLevel !== undefined;
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. Mesh.prototype.isReady = function () {
  8481. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8482. return false;
  8483. }
  8484. return _super.prototype.isReady.call(this);
  8485. };
  8486. Mesh.prototype.isDisposed = function () {
  8487. return this._isDisposed;
  8488. };
  8489. Mesh.prototype._preActivate = function () {
  8490. var sceneRenderId = this.getScene().getRenderId();
  8491. if (this._preActivateId == sceneRenderId) {
  8492. return;
  8493. }
  8494. this._preActivateId = sceneRenderId;
  8495. this._visibleInstances = null;
  8496. };
  8497. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8498. if (!this._visibleInstances) {
  8499. this._visibleInstances = {};
  8500. this._visibleInstances.defaultRenderId = renderId;
  8501. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8502. }
  8503. if (!this._visibleInstances[renderId]) {
  8504. this._visibleInstances[renderId] = new Array();
  8505. }
  8506. this._visibleInstances[renderId].push(instance);
  8507. };
  8508. Mesh.prototype.refreshBoundingInfo = function () {
  8509. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8510. if (data) {
  8511. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8512. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8513. }
  8514. if (this.subMeshes) {
  8515. for (var index = 0; index < this.subMeshes.length; index++) {
  8516. this.subMeshes[index].refreshBoundingInfo();
  8517. }
  8518. }
  8519. this._updateBoundingInfo();
  8520. };
  8521. Mesh.prototype._createGlobalSubMesh = function () {
  8522. var totalVertices = this.getTotalVertices();
  8523. if (!totalVertices || !this.getIndices()) {
  8524. return null;
  8525. }
  8526. this.releaseSubMeshes();
  8527. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8528. };
  8529. Mesh.prototype.subdivide = function (count) {
  8530. if (count < 1) {
  8531. return;
  8532. }
  8533. var totalIndices = this.getTotalIndices();
  8534. var subdivisionSize = (totalIndices / count) | 0;
  8535. var offset = 0;
  8536. while (subdivisionSize % 3 != 0) {
  8537. subdivisionSize++;
  8538. }
  8539. this.releaseSubMeshes();
  8540. for (var index = 0; index < count; index++) {
  8541. if (offset >= totalIndices) {
  8542. break;
  8543. }
  8544. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8545. offset += subdivisionSize;
  8546. }
  8547. this.synchronizeInstances();
  8548. };
  8549. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  8550. if (kind instanceof Array) {
  8551. var temp = data;
  8552. data = kind;
  8553. kind = temp;
  8554. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8555. }
  8556. if (!this._geometry) {
  8557. var vertexData = new BABYLON.VertexData();
  8558. vertexData.set(data, kind);
  8559. var scene = this.getScene();
  8560. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8561. } else {
  8562. this._geometry.setVerticesData(kind, data, updatable, stride);
  8563. }
  8564. };
  8565. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8566. if (!this._geometry) {
  8567. return;
  8568. }
  8569. if (!makeItUnique) {
  8570. this._geometry.updateVerticesData(kind, data, updateExtends);
  8571. } else {
  8572. this.makeGeometryUnique();
  8573. this.updateVerticesData(kind, data, updateExtends, false);
  8574. }
  8575. };
  8576. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8577. if (!this._geometry) {
  8578. return;
  8579. }
  8580. if (!makeItUnique) {
  8581. this._geometry.updateVerticesDataDirectly(kind, data);
  8582. } else {
  8583. this.makeGeometryUnique();
  8584. this.updateVerticesDataDirectly(kind, data, false);
  8585. }
  8586. };
  8587. Mesh.prototype.makeGeometryUnique = function () {
  8588. if (!this._geometry) {
  8589. return;
  8590. }
  8591. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8592. geometry.applyToMesh(this);
  8593. };
  8594. Mesh.prototype.setIndices = function (indices) {
  8595. if (!this._geometry) {
  8596. var vertexData = new BABYLON.VertexData();
  8597. vertexData.indices = indices;
  8598. var scene = this.getScene();
  8599. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8600. } else {
  8601. this._geometry.setIndices(indices);
  8602. }
  8603. };
  8604. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8605. var engine = this.getScene().getEngine();
  8606. var indexToBind;
  8607. switch (fillMode) {
  8608. case BABYLON.Material.PointFillMode:
  8609. indexToBind = null;
  8610. break;
  8611. case BABYLON.Material.WireFrameFillMode:
  8612. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8613. break;
  8614. default:
  8615. case BABYLON.Material.TriangleFillMode:
  8616. indexToBind = this._geometry.getIndexBuffer();
  8617. break;
  8618. }
  8619. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8620. };
  8621. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8622. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8623. return;
  8624. }
  8625. var engine = this.getScene().getEngine();
  8626. switch (fillMode) {
  8627. case BABYLON.Material.PointFillMode:
  8628. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8629. break;
  8630. case BABYLON.Material.WireFrameFillMode:
  8631. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8632. break;
  8633. default:
  8634. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8635. }
  8636. };
  8637. Mesh.prototype.registerBeforeRender = function (func) {
  8638. this._onBeforeRenderCallbacks.push(func);
  8639. };
  8640. Mesh.prototype.unregisterBeforeRender = function (func) {
  8641. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8642. if (index > -1) {
  8643. this._onBeforeRenderCallbacks.splice(index, 1);
  8644. }
  8645. };
  8646. Mesh.prototype.registerAfterRender = function (func) {
  8647. this._onAfterRenderCallbacks.push(func);
  8648. };
  8649. Mesh.prototype.unregisterAfterRender = function (func) {
  8650. var index = this._onAfterRenderCallbacks.indexOf(func);
  8651. if (index > -1) {
  8652. this._onAfterRenderCallbacks.splice(index, 1);
  8653. }
  8654. };
  8655. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8656. var scene = this.getScene();
  8657. this._batchCache.mustReturn = false;
  8658. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8659. this._batchCache.visibleInstances[subMeshId] = null;
  8660. if (this._visibleInstances) {
  8661. var currentRenderId = scene.getRenderId();
  8662. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8663. var selfRenderId = this._renderId;
  8664. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8665. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8666. currentRenderId = this._visibleInstances.defaultRenderId;
  8667. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8668. }
  8669. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8670. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8671. this._batchCache.mustReturn = true;
  8672. return this._batchCache;
  8673. }
  8674. if (currentRenderId !== selfRenderId) {
  8675. this._batchCache.renderSelf[subMeshId] = false;
  8676. }
  8677. }
  8678. this._renderIdForInstances[subMeshId] = currentRenderId;
  8679. }
  8680. return this._batchCache;
  8681. };
  8682. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8683. var matricesCount = this.instances.length + 1;
  8684. var bufferSize = matricesCount * 16 * 4;
  8685. while (this._instancesBufferSize < bufferSize) {
  8686. this._instancesBufferSize *= 2;
  8687. }
  8688. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8689. if (this._worldMatricesInstancesBuffer) {
  8690. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8691. }
  8692. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8693. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8694. }
  8695. var offset = 0;
  8696. var instancesCount = 0;
  8697. var world = this.getWorldMatrix();
  8698. if (batch.renderSelf[subMesh._id]) {
  8699. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8700. offset += 16;
  8701. instancesCount++;
  8702. }
  8703. var visibleInstances = batch.visibleInstances[subMesh._id];
  8704. if (visibleInstances) {
  8705. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8706. var instance = visibleInstances[instanceIndex];
  8707. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8708. offset += 16;
  8709. instancesCount++;
  8710. }
  8711. }
  8712. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8713. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8714. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8715. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8716. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8717. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8718. this._draw(subMesh, fillMode, instancesCount);
  8719. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8720. };
  8721. Mesh.prototype.render = function (subMesh) {
  8722. var scene = this.getScene();
  8723. var batch = this._getInstancesRenderList(subMesh._id);
  8724. if (batch.mustReturn) {
  8725. return;
  8726. }
  8727. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8728. return;
  8729. }
  8730. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8731. this._onBeforeRenderCallbacks[callbackIndex]();
  8732. }
  8733. var engine = scene.getEngine();
  8734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8735. var effectiveMaterial = subMesh.getMaterial();
  8736. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8737. return;
  8738. }
  8739. var savedDepthWrite = engine.getDepthWrite();
  8740. if (this.renderOutline) {
  8741. engine.setDepthWrite(false);
  8742. scene.getOutlineRenderer().render(subMesh, batch);
  8743. }
  8744. effectiveMaterial._preBind();
  8745. var effect = effectiveMaterial.getEffect();
  8746. var fillMode = engine.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8747. this._bind(subMesh, effect, fillMode);
  8748. var world = this.getWorldMatrix();
  8749. effectiveMaterial.bind(world, this);
  8750. if (hardwareInstancedRendering) {
  8751. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8752. } else {
  8753. if (batch.renderSelf[subMesh._id]) {
  8754. this._draw(subMesh, fillMode);
  8755. }
  8756. if (batch.visibleInstances[subMesh._id]) {
  8757. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8758. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8759. world = instance.getWorldMatrix();
  8760. effectiveMaterial.bindOnlyWorldMatrix(world);
  8761. this._draw(subMesh, fillMode);
  8762. }
  8763. }
  8764. }
  8765. effectiveMaterial.unbind();
  8766. if (this.renderOutline && savedDepthWrite) {
  8767. engine.setDepthWrite(true);
  8768. engine.setColorWrite(false);
  8769. scene.getOutlineRenderer().render(subMesh, batch);
  8770. engine.setColorWrite(true);
  8771. }
  8772. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8773. this._onAfterRenderCallbacks[callbackIndex]();
  8774. }
  8775. };
  8776. Mesh.prototype.getEmittedParticleSystems = function () {
  8777. var results = new Array();
  8778. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8779. var particleSystem = this.getScene().particleSystems[index];
  8780. if (particleSystem.emitter === this) {
  8781. results.push(particleSystem);
  8782. }
  8783. }
  8784. return results;
  8785. };
  8786. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8787. var results = new Array();
  8788. var descendants = this.getDescendants();
  8789. descendants.push(this);
  8790. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8791. var particleSystem = this.getScene().particleSystems[index];
  8792. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8793. results.push(particleSystem);
  8794. }
  8795. }
  8796. return results;
  8797. };
  8798. Mesh.prototype.getChildren = function () {
  8799. var results = [];
  8800. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8801. var mesh = this.getScene().meshes[index];
  8802. if (mesh.parent == this) {
  8803. results.push(mesh);
  8804. }
  8805. }
  8806. return results;
  8807. };
  8808. Mesh.prototype._checkDelayState = function () {
  8809. var _this = this;
  8810. var that = this;
  8811. var scene = this.getScene();
  8812. if (this._geometry) {
  8813. this._geometry.load(scene);
  8814. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8815. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8816. scene._addPendingData(that);
  8817. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8818. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8819. if (data instanceof ArrayBuffer) {
  8820. _this._delayLoadingFunction(data, _this);
  8821. } else {
  8822. _this._delayLoadingFunction(JSON.parse(data), _this);
  8823. }
  8824. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  8825. scene._removePendingData(_this);
  8826. }, function () {
  8827. }, scene.database, getBinaryData);
  8828. }
  8829. };
  8830. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  8831. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8832. return false;
  8833. }
  8834. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  8835. return false;
  8836. }
  8837. this._checkDelayState();
  8838. return true;
  8839. };
  8840. Mesh.prototype.setMaterialByID = function (id) {
  8841. var materials = this.getScene().materials;
  8842. for (var index = 0; index < materials.length; index++) {
  8843. if (materials[index].id == id) {
  8844. this.material = materials[index];
  8845. return;
  8846. }
  8847. }
  8848. var multiMaterials = this.getScene().multiMaterials;
  8849. for (index = 0; index < multiMaterials.length; index++) {
  8850. if (multiMaterials[index].id == id) {
  8851. this.material = multiMaterials[index];
  8852. return;
  8853. }
  8854. }
  8855. };
  8856. Mesh.prototype.getAnimatables = function () {
  8857. var results = [];
  8858. if (this.material) {
  8859. results.push(this.material);
  8860. }
  8861. if (this.skeleton) {
  8862. results.push(this.skeleton);
  8863. }
  8864. return results;
  8865. };
  8866. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  8867. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  8868. return;
  8869. }
  8870. this._resetPointsArrayCache();
  8871. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8872. var temp = [];
  8873. for (var index = 0; index < data.length; index += 3) {
  8874. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8875. }
  8876. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  8877. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8878. return;
  8879. }
  8880. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8881. for (index = 0; index < data.length; index += 3) {
  8882. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  8883. }
  8884. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  8885. };
  8886. Mesh.prototype._resetPointsArrayCache = function () {
  8887. this._positions = null;
  8888. };
  8889. Mesh.prototype._generatePointsArray = function () {
  8890. if (this._positions)
  8891. return true;
  8892. this._positions = [];
  8893. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8894. if (!data) {
  8895. return false;
  8896. }
  8897. for (var index = 0; index < data.length; index += 3) {
  8898. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  8899. }
  8900. return true;
  8901. };
  8902. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8903. var result = new BABYLON.Mesh(name, this.getScene());
  8904. this._geometry.applyToMesh(result);
  8905. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  8906. result.material = this.material;
  8907. if (newParent) {
  8908. result.parent = newParent;
  8909. }
  8910. if (!doNotCloneChildren) {
  8911. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8912. var mesh = this.getScene().meshes[index];
  8913. if (mesh.parent == this) {
  8914. mesh.clone(mesh.name, result);
  8915. }
  8916. }
  8917. }
  8918. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8919. var system = this.getScene().particleSystems[index];
  8920. if (system.emitter == this) {
  8921. system.clone(system.name, result);
  8922. }
  8923. }
  8924. result.computeWorldMatrix(true);
  8925. return result;
  8926. };
  8927. Mesh.prototype.dispose = function (doNotRecurse) {
  8928. if (this._geometry) {
  8929. this._geometry.releaseForMesh(this, true);
  8930. }
  8931. if (this._worldMatricesInstancesBuffer) {
  8932. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8933. this._worldMatricesInstancesBuffer = null;
  8934. }
  8935. while (this.instances.length) {
  8936. this.instances[0].dispose();
  8937. }
  8938. _super.prototype.dispose.call(this, doNotRecurse);
  8939. };
  8940. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  8941. var _this = this;
  8942. var scene = this.getScene();
  8943. var onload = function (img) {
  8944. var canvas = document.createElement("canvas");
  8945. var context = canvas.getContext("2d");
  8946. var heightMapWidth = img.width;
  8947. var heightMapHeight = img.height;
  8948. canvas.width = heightMapWidth;
  8949. canvas.height = heightMapHeight;
  8950. context.drawImage(img, 0, 0);
  8951. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  8952. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  8953. };
  8954. BABYLON.Tools.LoadImage(url, onload, function () {
  8955. }, scene.database);
  8956. };
  8957. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  8958. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8959. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  8960. return;
  8961. }
  8962. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8963. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8964. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8965. var position = BABYLON.Vector3.Zero();
  8966. var normal = BABYLON.Vector3.Zero();
  8967. var uv = BABYLON.Vector2.Zero();
  8968. for (var index = 0; index < positions.length; index += 3) {
  8969. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  8970. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  8971. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  8972. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  8973. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  8974. var pos = (u + v * heightMapWidth) * 4;
  8975. var r = buffer[pos] / 255.0;
  8976. var g = buffer[pos + 1] / 255.0;
  8977. var b = buffer[pos + 2] / 255.0;
  8978. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  8979. normal.normalize();
  8980. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  8981. position = position.add(normal);
  8982. position.toArray(positions, index);
  8983. }
  8984. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  8985. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  8986. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  8987. };
  8988. Mesh.prototype.convertToFlatShadedMesh = function () {
  8989. var kinds = this.getVerticesDataKinds();
  8990. var vbs = [];
  8991. var data = [];
  8992. var newdata = [];
  8993. var updatableNormals = false;
  8994. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  8995. var kind = kinds[kindIndex];
  8996. var vertexBuffer = this.getVertexBuffer(kind);
  8997. if (kind === BABYLON.VertexBuffer.NormalKind) {
  8998. updatableNormals = vertexBuffer.isUpdatable();
  8999. kinds.splice(kindIndex, 1);
  9000. kindIndex--;
  9001. continue;
  9002. }
  9003. vbs[kind] = vertexBuffer;
  9004. data[kind] = vbs[kind].getData();
  9005. newdata[kind] = [];
  9006. }
  9007. var previousSubmeshes = this.subMeshes.slice(0);
  9008. var indices = this.getIndices();
  9009. var totalIndices = this.getTotalIndices();
  9010. for (index = 0; index < totalIndices; index++) {
  9011. var vertexIndex = indices[index];
  9012. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9013. kind = kinds[kindIndex];
  9014. var stride = vbs[kind].getStrideSize();
  9015. for (var offset = 0; offset < stride; offset++) {
  9016. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9017. }
  9018. }
  9019. }
  9020. var normals = [];
  9021. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9022. for (var index = 0; index < totalIndices; index += 3) {
  9023. indices[index] = index;
  9024. indices[index + 1] = index + 1;
  9025. indices[index + 2] = index + 2;
  9026. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9027. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9028. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9029. var p1p2 = p1.subtract(p2);
  9030. var p3p2 = p3.subtract(p2);
  9031. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9032. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9033. normals.push(normal.x);
  9034. normals.push(normal.y);
  9035. normals.push(normal.z);
  9036. }
  9037. }
  9038. this.setIndices(indices);
  9039. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9040. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9041. kind = kinds[kindIndex];
  9042. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9043. }
  9044. this.releaseSubMeshes();
  9045. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9046. var previousOne = previousSubmeshes[submeshIndex];
  9047. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9048. }
  9049. this.synchronizeInstances();
  9050. };
  9051. Mesh.prototype.createInstance = function (name) {
  9052. return new BABYLON.InstancedMesh(name, this);
  9053. };
  9054. Mesh.prototype.synchronizeInstances = function () {
  9055. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9056. var instance = this.instances[instanceIndex];
  9057. instance._syncSubMeshes();
  9058. }
  9059. };
  9060. Mesh.CreateBox = function (name, size, scene, updatable) {
  9061. var box = new BABYLON.Mesh(name, scene);
  9062. var vertexData = BABYLON.VertexData.CreateBox(size);
  9063. vertexData.applyToMesh(box, updatable);
  9064. return box;
  9065. };
  9066. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9067. var sphere = new BABYLON.Mesh(name, scene);
  9068. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9069. vertexData.applyToMesh(sphere, updatable);
  9070. return sphere;
  9071. };
  9072. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9073. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9074. if (scene !== undefined) {
  9075. updatable = scene;
  9076. }
  9077. scene = subdivisions;
  9078. subdivisions = 1;
  9079. }
  9080. var cylinder = new BABYLON.Mesh(name, scene);
  9081. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9082. vertexData.applyToMesh(cylinder, updatable);
  9083. return cylinder;
  9084. };
  9085. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9086. var torus = new BABYLON.Mesh(name, scene);
  9087. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9088. vertexData.applyToMesh(torus, updatable);
  9089. return torus;
  9090. };
  9091. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9092. var torusKnot = new BABYLON.Mesh(name, scene);
  9093. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9094. vertexData.applyToMesh(torusKnot, updatable);
  9095. return torusKnot;
  9096. };
  9097. Mesh.CreateLines = function (name, points, scene, updatable) {
  9098. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9099. var vertexData = BABYLON.VertexData.CreateLines(points);
  9100. vertexData.applyToMesh(lines, updatable);
  9101. return lines;
  9102. };
  9103. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9104. var plane = new BABYLON.Mesh(name, scene);
  9105. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9106. vertexData.applyToMesh(plane, updatable);
  9107. return plane;
  9108. };
  9109. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9110. var ground = new BABYLON.GroundMesh(name, scene);
  9111. ground._setReady(false);
  9112. ground._subdivisions = subdivisions;
  9113. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9114. vertexData.applyToMesh(ground, updatable);
  9115. ground._setReady(true);
  9116. return ground;
  9117. };
  9118. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9119. var tiledGround = new BABYLON.Mesh(name, scene);
  9120. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9121. vertexData.applyToMesh(tiledGround, updatable);
  9122. return tiledGround;
  9123. };
  9124. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9125. var ground = new BABYLON.GroundMesh(name, scene);
  9126. ground._subdivisions = subdivisions;
  9127. ground._setReady(false);
  9128. var onload = function (img) {
  9129. var canvas = document.createElement("canvas");
  9130. var context = canvas.getContext("2d");
  9131. var heightMapWidth = img.width;
  9132. var heightMapHeight = img.height;
  9133. canvas.width = heightMapWidth;
  9134. canvas.height = heightMapHeight;
  9135. context.drawImage(img, 0, 0);
  9136. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9137. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9138. vertexData.applyToMesh(ground, updatable);
  9139. ground._setReady(true);
  9140. };
  9141. BABYLON.Tools.LoadImage(url, onload, function () {
  9142. }, scene.database);
  9143. return ground;
  9144. };
  9145. Mesh.MinMax = function (meshes) {
  9146. var minVector = null;
  9147. var maxVector = null;
  9148. for (var i in meshes) {
  9149. var mesh = meshes[i];
  9150. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9151. if (!minVector) {
  9152. minVector = boundingBox.minimumWorld;
  9153. maxVector = boundingBox.maximumWorld;
  9154. continue;
  9155. }
  9156. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9157. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9158. }
  9159. return {
  9160. min: minVector,
  9161. max: maxVector
  9162. };
  9163. };
  9164. Mesh.Center = function (meshesOrMinMaxVector) {
  9165. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9166. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9167. };
  9168. return Mesh;
  9169. })(BABYLON.AbstractMesh);
  9170. BABYLON.Mesh = Mesh;
  9171. })(BABYLON || (BABYLON = {}));
  9172. var __extends = this.__extends || function (d, b) {
  9173. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9174. function __() { this.constructor = d; }
  9175. __.prototype = b.prototype;
  9176. d.prototype = new __();
  9177. };
  9178. var BABYLON;
  9179. (function (BABYLON) {
  9180. var GroundMesh = (function (_super) {
  9181. __extends(GroundMesh, _super);
  9182. function GroundMesh(name, scene) {
  9183. _super.call(this, name, scene);
  9184. this.generateOctree = false;
  9185. this._worldInverse = new BABYLON.Matrix();
  9186. }
  9187. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9188. get: function () {
  9189. return this._subdivisions;
  9190. },
  9191. enumerable: true,
  9192. configurable: true
  9193. });
  9194. GroundMesh.prototype.optimize = function (chunksCount) {
  9195. this.subdivide(this._subdivisions);
  9196. this.createOrUpdateSubmeshesOctree(32);
  9197. };
  9198. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9199. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9200. this.getWorldMatrix().invertToRef(this._worldInverse);
  9201. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9202. var pickInfo = this.intersects(ray);
  9203. if (pickInfo.hit) {
  9204. return pickInfo.pickedPoint.y;
  9205. }
  9206. return 0;
  9207. };
  9208. return GroundMesh;
  9209. })(BABYLON.Mesh);
  9210. BABYLON.GroundMesh = GroundMesh;
  9211. })(BABYLON || (BABYLON = {}));
  9212. var __extends = this.__extends || function (d, b) {
  9213. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9214. function __() { this.constructor = d; }
  9215. __.prototype = b.prototype;
  9216. d.prototype = new __();
  9217. };
  9218. var BABYLON;
  9219. (function (BABYLON) {
  9220. var InstancedMesh = (function (_super) {
  9221. __extends(InstancedMesh, _super);
  9222. function InstancedMesh(name, source) {
  9223. _super.call(this, name, source.getScene());
  9224. source.instances.push(this);
  9225. this._sourceMesh = source;
  9226. this.position.copyFrom(source.position);
  9227. this.rotation.copyFrom(source.rotation);
  9228. this.scaling.copyFrom(source.scaling);
  9229. if (source.rotationQuaternion) {
  9230. this.rotationQuaternion = source.rotationQuaternion.clone();
  9231. }
  9232. this.infiniteDistance = source.infiniteDistance;
  9233. this.setPivotMatrix(source.getPivotMatrix());
  9234. this.refreshBoundingInfo();
  9235. this._syncSubMeshes();
  9236. }
  9237. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9238. get: function () {
  9239. return this._sourceMesh.receiveShadows;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(InstancedMesh.prototype, "material", {
  9245. get: function () {
  9246. return this._sourceMesh.material;
  9247. },
  9248. enumerable: true,
  9249. configurable: true
  9250. });
  9251. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9252. get: function () {
  9253. return this._sourceMesh.visibility;
  9254. },
  9255. enumerable: true,
  9256. configurable: true
  9257. });
  9258. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9259. get: function () {
  9260. return this._sourceMesh.skeleton;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. InstancedMesh.prototype.getTotalVertices = function () {
  9266. return this._sourceMesh.getTotalVertices();
  9267. };
  9268. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9269. get: function () {
  9270. return this._sourceMesh;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. InstancedMesh.prototype.getVerticesData = function (kind) {
  9276. return this._sourceMesh.getVerticesData(kind);
  9277. };
  9278. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9279. return this._sourceMesh.isVerticesDataPresent(kind);
  9280. };
  9281. InstancedMesh.prototype.getIndices = function () {
  9282. return this._sourceMesh.getIndices();
  9283. };
  9284. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9285. get: function () {
  9286. return this._sourceMesh._positions;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9292. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9293. if (data) {
  9294. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9295. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9296. }
  9297. this._updateBoundingInfo();
  9298. };
  9299. InstancedMesh.prototype._preActivate = function () {
  9300. this.sourceMesh._preActivate();
  9301. };
  9302. InstancedMesh.prototype._activate = function (renderId) {
  9303. this.sourceMesh._registerInstanceForRenderId(this, renderId);
  9304. };
  9305. InstancedMesh.prototype._syncSubMeshes = function () {
  9306. this.releaseSubMeshes();
  9307. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9308. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9309. }
  9310. };
  9311. InstancedMesh.prototype._generatePointsArray = function () {
  9312. return this._sourceMesh._generatePointsArray();
  9313. };
  9314. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9315. var result = this._sourceMesh.createInstance(name);
  9316. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9317. this.refreshBoundingInfo();
  9318. if (newParent) {
  9319. result.parent = newParent;
  9320. }
  9321. if (!doNotCloneChildren) {
  9322. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9323. var mesh = this.getScene().meshes[index];
  9324. if (mesh.parent == this) {
  9325. mesh.clone(mesh.name, result);
  9326. }
  9327. }
  9328. }
  9329. result.computeWorldMatrix(true);
  9330. return result;
  9331. };
  9332. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9333. var index = this._sourceMesh.instances.indexOf(this);
  9334. this._sourceMesh.instances.splice(index, 1);
  9335. _super.prototype.dispose.call(this, doNotRecurse);
  9336. };
  9337. return InstancedMesh;
  9338. })(BABYLON.AbstractMesh);
  9339. BABYLON.InstancedMesh = InstancedMesh;
  9340. })(BABYLON || (BABYLON = {}));
  9341. var BABYLON;
  9342. (function (BABYLON) {
  9343. var SubMesh = (function () {
  9344. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9345. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9346. this.materialIndex = materialIndex;
  9347. this.verticesStart = verticesStart;
  9348. this.verticesCount = verticesCount;
  9349. this.indexStart = indexStart;
  9350. this.indexCount = indexCount;
  9351. this._renderId = 0;
  9352. this._mesh = mesh;
  9353. this._renderingMesh = renderingMesh || mesh;
  9354. mesh.subMeshes.push(this);
  9355. this._id = mesh.subMeshes.length - 1;
  9356. if (createBoundingBox) {
  9357. this.refreshBoundingInfo();
  9358. }
  9359. }
  9360. SubMesh.prototype.getBoundingInfo = function () {
  9361. return this._boundingInfo;
  9362. };
  9363. SubMesh.prototype.getMesh = function () {
  9364. return this._mesh;
  9365. };
  9366. SubMesh.prototype.getRenderingMesh = function () {
  9367. return this._renderingMesh;
  9368. };
  9369. SubMesh.prototype.getMaterial = function () {
  9370. var rootMaterial = this._renderingMesh.material;
  9371. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9372. var multiMaterial = rootMaterial;
  9373. return multiMaterial.getSubMaterial(this.materialIndex);
  9374. }
  9375. if (!rootMaterial) {
  9376. return this._mesh.getScene().defaultMaterial;
  9377. }
  9378. return rootMaterial;
  9379. };
  9380. SubMesh.prototype.refreshBoundingInfo = function () {
  9381. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9382. if (!data) {
  9383. this._boundingInfo = this._mesh._boundingInfo;
  9384. return;
  9385. }
  9386. var indices = this._renderingMesh.getIndices();
  9387. var extend;
  9388. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9389. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9390. } else {
  9391. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9392. }
  9393. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9394. };
  9395. SubMesh.prototype._checkCollision = function (collider) {
  9396. return this._boundingInfo._checkCollision(collider);
  9397. };
  9398. SubMesh.prototype.updateBoundingInfo = function (world) {
  9399. if (!this._boundingInfo) {
  9400. this.refreshBoundingInfo();
  9401. }
  9402. this._boundingInfo._update(world);
  9403. };
  9404. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9405. return this._boundingInfo.isInFrustum(frustumPlanes);
  9406. };
  9407. SubMesh.prototype.render = function () {
  9408. this._renderingMesh.render(this);
  9409. };
  9410. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9411. if (!this._linesIndexBuffer) {
  9412. var linesIndices = [];
  9413. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9414. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9415. }
  9416. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9417. this.linesIndexCount = linesIndices.length;
  9418. }
  9419. return this._linesIndexBuffer;
  9420. };
  9421. SubMesh.prototype.canIntersects = function (ray) {
  9422. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9423. };
  9424. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9425. var intersectInfo = null;
  9426. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9427. var p0 = positions[indices[index]];
  9428. var p1 = positions[indices[index + 1]];
  9429. var p2 = positions[indices[index + 2]];
  9430. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9431. if (currentIntersectInfo) {
  9432. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9433. intersectInfo = currentIntersectInfo;
  9434. intersectInfo.faceId = index / 3;
  9435. if (fastCheck) {
  9436. break;
  9437. }
  9438. }
  9439. }
  9440. }
  9441. return intersectInfo;
  9442. };
  9443. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9444. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9445. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9446. return result;
  9447. };
  9448. SubMesh.prototype.dispose = function () {
  9449. if (this._linesIndexBuffer) {
  9450. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9451. this._linesIndexBuffer = null;
  9452. }
  9453. var index = this._mesh.subMeshes.indexOf(this);
  9454. this._mesh.subMeshes.splice(index, 1);
  9455. };
  9456. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9457. var minVertexIndex = Number.MAX_VALUE;
  9458. var maxVertexIndex = -Number.MAX_VALUE;
  9459. renderingMesh = renderingMesh || mesh;
  9460. var indices = renderingMesh.getIndices();
  9461. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9462. var vertexIndex = indices[index];
  9463. if (vertexIndex < minVertexIndex)
  9464. minVertexIndex = vertexIndex;
  9465. if (vertexIndex > maxVertexIndex)
  9466. maxVertexIndex = vertexIndex;
  9467. }
  9468. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9469. };
  9470. return SubMesh;
  9471. })();
  9472. BABYLON.SubMesh = SubMesh;
  9473. })(BABYLON || (BABYLON = {}));
  9474. var BABYLON;
  9475. (function (BABYLON) {
  9476. var BaseTexture = (function () {
  9477. function BaseTexture(scene) {
  9478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9479. this.hasAlpha = false;
  9480. this.getAlphaFromRGB = false;
  9481. this.level = 1;
  9482. this.isCube = false;
  9483. this.isRenderTarget = false;
  9484. this.animations = new Array();
  9485. this.coordinatesIndex = 0;
  9486. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9487. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9488. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9489. this.anisotropicFilteringLevel = 4;
  9490. this._scene = scene;
  9491. this._scene.textures.push(this);
  9492. }
  9493. BaseTexture.prototype.getScene = function () {
  9494. return this._scene;
  9495. };
  9496. BaseTexture.prototype.getTextureMatrix = function () {
  9497. return null;
  9498. };
  9499. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9500. return null;
  9501. };
  9502. BaseTexture.prototype.getInternalTexture = function () {
  9503. return this._texture;
  9504. };
  9505. BaseTexture.prototype.isReady = function () {
  9506. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9507. return true;
  9508. }
  9509. if (this._texture) {
  9510. return this._texture.isReady;
  9511. }
  9512. return false;
  9513. };
  9514. BaseTexture.prototype.getSize = function () {
  9515. if (this._texture._width) {
  9516. return { width: this._texture._width, height: this._texture._height };
  9517. }
  9518. if (this._texture._size) {
  9519. return { width: this._texture._size, height: this._texture._size };
  9520. }
  9521. return { width: 0, height: 0 };
  9522. };
  9523. BaseTexture.prototype.getBaseSize = function () {
  9524. if (!this.isReady())
  9525. return { width: 0, height: 0 };
  9526. if (this._texture._size) {
  9527. return { width: this._texture._size, height: this._texture._size };
  9528. }
  9529. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9530. };
  9531. BaseTexture.prototype.scale = function (ratio) {
  9532. };
  9533. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9534. get: function () {
  9535. return false;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9541. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9542. for (var index = 0; index < texturesCache.length; index++) {
  9543. var texturesCacheEntry = texturesCache[index];
  9544. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9545. texturesCache.splice(index, 1);
  9546. return;
  9547. }
  9548. }
  9549. };
  9550. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9551. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9552. for (var index = 0; index < texturesCache.length; index++) {
  9553. var texturesCacheEntry = texturesCache[index];
  9554. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9555. texturesCacheEntry.references++;
  9556. return texturesCacheEntry;
  9557. }
  9558. }
  9559. return null;
  9560. };
  9561. BaseTexture.prototype.delayLoad = function () {
  9562. };
  9563. BaseTexture.prototype.releaseInternalTexture = function () {
  9564. if (!this._texture) {
  9565. return;
  9566. }
  9567. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9568. this._texture.references--;
  9569. if (this._texture.references == 0) {
  9570. var index = texturesCache.indexOf(this._texture);
  9571. texturesCache.splice(index, 1);
  9572. this._scene.getEngine()._releaseTexture(this._texture);
  9573. delete this._texture;
  9574. }
  9575. };
  9576. BaseTexture.prototype.clone = function () {
  9577. return null;
  9578. };
  9579. BaseTexture.prototype.dispose = function () {
  9580. var index = this._scene.textures.indexOf(this);
  9581. if (index >= 0) {
  9582. this._scene.textures.splice(index, 1);
  9583. }
  9584. if (this._texture === undefined) {
  9585. return;
  9586. }
  9587. this.releaseInternalTexture();
  9588. if (this.onDispose) {
  9589. this.onDispose();
  9590. }
  9591. };
  9592. return BaseTexture;
  9593. })();
  9594. BABYLON.BaseTexture = BaseTexture;
  9595. })(BABYLON || (BABYLON = {}));
  9596. var BABYLON;
  9597. (function (BABYLON) {
  9598. var RenderingGroup = (function () {
  9599. function RenderingGroup(index, scene) {
  9600. this.index = index;
  9601. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9602. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9603. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9604. this._scene = scene;
  9605. }
  9606. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9607. if (customRenderFunction) {
  9608. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9609. return true;
  9610. }
  9611. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9612. return false;
  9613. }
  9614. var engine = this._scene.getEngine();
  9615. var subIndex;
  9616. var submesh;
  9617. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9618. submesh = this._opaqueSubMeshes.data[subIndex];
  9619. this._activeVertices += submesh.verticesCount;
  9620. submesh.render();
  9621. }
  9622. engine.setAlphaTesting(true);
  9623. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9624. submesh = this._alphaTestSubMeshes.data[subIndex];
  9625. this._activeVertices += submesh.verticesCount;
  9626. submesh.render();
  9627. }
  9628. engine.setAlphaTesting(false);
  9629. if (beforeTransparents) {
  9630. beforeTransparents();
  9631. }
  9632. if (this._transparentSubMeshes.length) {
  9633. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9634. submesh = this._transparentSubMeshes.data[subIndex];
  9635. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9636. }
  9637. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9638. sortedArray.sort(function (a, b) {
  9639. if (a._distanceToCamera < b._distanceToCamera) {
  9640. return 1;
  9641. }
  9642. if (a._distanceToCamera > b._distanceToCamera) {
  9643. return -1;
  9644. }
  9645. return 0;
  9646. });
  9647. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9648. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9649. submesh = sortedArray[subIndex];
  9650. this._activeVertices += submesh.verticesCount;
  9651. submesh.render();
  9652. }
  9653. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9654. }
  9655. return true;
  9656. };
  9657. RenderingGroup.prototype.prepare = function () {
  9658. this._opaqueSubMeshes.reset();
  9659. this._transparentSubMeshes.reset();
  9660. this._alphaTestSubMeshes.reset();
  9661. };
  9662. RenderingGroup.prototype.dispatch = function (subMesh) {
  9663. var material = subMesh.getMaterial();
  9664. var mesh = subMesh.getMesh();
  9665. if (material.needAlphaBlending() || mesh.visibility < 1.0) {
  9666. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9667. this._transparentSubMeshes.push(subMesh);
  9668. }
  9669. } else if (material.needAlphaTesting()) {
  9670. this._alphaTestSubMeshes.push(subMesh);
  9671. } else {
  9672. this._opaqueSubMeshes.push(subMesh);
  9673. }
  9674. };
  9675. return RenderingGroup;
  9676. })();
  9677. BABYLON.RenderingGroup = RenderingGroup;
  9678. })(BABYLON || (BABYLON = {}));
  9679. var BABYLON;
  9680. (function (BABYLON) {
  9681. var RenderingManager = (function () {
  9682. function RenderingManager(scene) {
  9683. this._renderingGroups = new Array();
  9684. this._scene = scene;
  9685. }
  9686. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9687. if (this._scene._activeParticleSystems.length === 0) {
  9688. return;
  9689. }
  9690. var beforeParticlesDate = BABYLON.Tools.Now;
  9691. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9692. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9693. if (particleSystem.renderingGroupId !== index) {
  9694. continue;
  9695. }
  9696. this._clearDepthBuffer();
  9697. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9698. this._scene._activeParticles += particleSystem.render();
  9699. }
  9700. }
  9701. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9702. };
  9703. RenderingManager.prototype._renderSprites = function (index) {
  9704. if (this._scene.spriteManagers.length === 0) {
  9705. return;
  9706. }
  9707. var beforeSpritessDate = BABYLON.Tools.Now;
  9708. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9709. var spriteManager = this._scene.spriteManagers[id];
  9710. if (spriteManager.renderingGroupId === index) {
  9711. this._clearDepthBuffer();
  9712. spriteManager.render();
  9713. }
  9714. }
  9715. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9716. };
  9717. RenderingManager.prototype._clearDepthBuffer = function () {
  9718. if (this._depthBufferAlreadyCleaned) {
  9719. return;
  9720. }
  9721. this._scene.getEngine().clear(0, false, true);
  9722. this._depthBufferAlreadyCleaned = true;
  9723. };
  9724. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9725. var _this = this;
  9726. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9727. this._depthBufferAlreadyCleaned = false;
  9728. var renderingGroup = this._renderingGroups[index];
  9729. if (renderingGroup) {
  9730. this._clearDepthBuffer();
  9731. if (!renderingGroup.render(customRenderFunction, function () {
  9732. if (renderSprites) {
  9733. _this._renderSprites(index);
  9734. }
  9735. })) {
  9736. this._renderingGroups.splice(index, 1);
  9737. }
  9738. } else if (renderSprites) {
  9739. this._renderSprites(index);
  9740. }
  9741. if (renderParticles) {
  9742. this._renderParticles(index, activeMeshes);
  9743. }
  9744. }
  9745. };
  9746. RenderingManager.prototype.reset = function () {
  9747. for (var index in this._renderingGroups) {
  9748. var renderingGroup = this._renderingGroups[index];
  9749. renderingGroup.prepare();
  9750. }
  9751. };
  9752. RenderingManager.prototype.dispatch = function (subMesh) {
  9753. var mesh = subMesh.getMesh();
  9754. var renderingGroupId = mesh.renderingGroupId || 0;
  9755. if (!this._renderingGroups[renderingGroupId]) {
  9756. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9757. }
  9758. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9759. };
  9760. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9761. return RenderingManager;
  9762. })();
  9763. BABYLON.RenderingManager = RenderingManager;
  9764. })(BABYLON || (BABYLON = {}));
  9765. var __extends = this.__extends || function (d, b) {
  9766. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9767. function __() { this.constructor = d; }
  9768. __.prototype = b.prototype;
  9769. d.prototype = new __();
  9770. };
  9771. var BABYLON;
  9772. (function (BABYLON) {
  9773. var Texture = (function (_super) {
  9774. __extends(Texture, _super);
  9775. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9776. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9777. if (typeof onLoad === "undefined") { onLoad = null; }
  9778. if (typeof onError === "undefined") { onError = null; }
  9779. if (typeof buffer === "undefined") { buffer = null; }
  9780. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9781. _super.call(this, scene);
  9782. this.uOffset = 0;
  9783. this.vOffset = 0;
  9784. this.uScale = 1.0;
  9785. this.vScale = 1.0;
  9786. this.uAng = 0;
  9787. this.vAng = 0;
  9788. this.wAng = 0;
  9789. this.name = url;
  9790. this.url = url;
  9791. this._noMipmap = noMipmap;
  9792. this._invertY = invertY;
  9793. this._samplingMode = samplingMode;
  9794. this._buffer = buffer;
  9795. this._deleteBuffer = deleteBuffer;
  9796. if (!url) {
  9797. return;
  9798. }
  9799. this._texture = this._getFromCache(url, noMipmap);
  9800. if (!this._texture) {
  9801. if (!scene.useDelayedTextureLoading) {
  9802. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9803. if (deleteBuffer) {
  9804. delete this._buffer;
  9805. }
  9806. } else {
  9807. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9808. }
  9809. }
  9810. }
  9811. Texture.prototype.delayLoad = function () {
  9812. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9813. return;
  9814. }
  9815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9816. this._texture = this._getFromCache(this.url, this._noMipmap);
  9817. if (!this._texture) {
  9818. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  9819. if (this._deleteBuffer) {
  9820. delete this._buffer;
  9821. }
  9822. }
  9823. };
  9824. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  9825. x -= this.uOffset + 0.5;
  9826. y -= this.vOffset + 0.5;
  9827. z -= 0.5;
  9828. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  9829. t.x *= this.uScale;
  9830. t.y *= this.vScale;
  9831. t.x += 0.5;
  9832. t.y += 0.5;
  9833. t.z += 0.5;
  9834. };
  9835. Texture.prototype.getTextureMatrix = function () {
  9836. 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) {
  9837. return this._cachedTextureMatrix;
  9838. }
  9839. this._cachedUOffset = this.uOffset;
  9840. this._cachedVOffset = this.vOffset;
  9841. this._cachedUScale = this.uScale;
  9842. this._cachedVScale = this.vScale;
  9843. this._cachedUAng = this.uAng;
  9844. this._cachedVAng = this.vAng;
  9845. this._cachedWAng = this.wAng;
  9846. if (!this._cachedTextureMatrix) {
  9847. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9848. this._rowGenerationMatrix = new BABYLON.Matrix();
  9849. this._t0 = BABYLON.Vector3.Zero();
  9850. this._t1 = BABYLON.Vector3.Zero();
  9851. this._t2 = BABYLON.Vector3.Zero();
  9852. }
  9853. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  9854. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  9855. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  9856. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  9857. this._t1.subtractInPlace(this._t0);
  9858. this._t2.subtractInPlace(this._t0);
  9859. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9860. this._cachedTextureMatrix.m[0] = this._t1.x;
  9861. this._cachedTextureMatrix.m[1] = this._t1.y;
  9862. this._cachedTextureMatrix.m[2] = this._t1.z;
  9863. this._cachedTextureMatrix.m[4] = this._t2.x;
  9864. this._cachedTextureMatrix.m[5] = this._t2.y;
  9865. this._cachedTextureMatrix.m[6] = this._t2.z;
  9866. this._cachedTextureMatrix.m[8] = this._t0.x;
  9867. this._cachedTextureMatrix.m[9] = this._t0.y;
  9868. this._cachedTextureMatrix.m[10] = this._t0.z;
  9869. return this._cachedTextureMatrix;
  9870. };
  9871. Texture.prototype.getReflectionTextureMatrix = function () {
  9872. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  9873. return this._cachedTextureMatrix;
  9874. }
  9875. if (!this._cachedTextureMatrix) {
  9876. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  9877. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  9878. }
  9879. switch (this.coordinatesMode) {
  9880. case BABYLON.Texture.SPHERICAL_MODE:
  9881. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9882. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  9883. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  9884. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  9885. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  9886. break;
  9887. case BABYLON.Texture.PLANAR_MODE:
  9888. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9889. this._cachedTextureMatrix[0] = this.uScale;
  9890. this._cachedTextureMatrix[5] = this.vScale;
  9891. this._cachedTextureMatrix[12] = this.uOffset;
  9892. this._cachedTextureMatrix[13] = this.vOffset;
  9893. break;
  9894. case BABYLON.Texture.PROJECTION_MODE:
  9895. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  9896. this._projectionModeMatrix.m[0] = 0.5;
  9897. this._projectionModeMatrix.m[5] = -0.5;
  9898. this._projectionModeMatrix.m[10] = 0.0;
  9899. this._projectionModeMatrix.m[12] = 0.5;
  9900. this._projectionModeMatrix.m[13] = 0.5;
  9901. this._projectionModeMatrix.m[14] = 1.0;
  9902. this._projectionModeMatrix.m[15] = 1.0;
  9903. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  9904. break;
  9905. default:
  9906. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  9907. break;
  9908. }
  9909. return this._cachedTextureMatrix;
  9910. };
  9911. Texture.prototype.clone = function () {
  9912. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  9913. newTexture.hasAlpha = this.hasAlpha;
  9914. newTexture.level = this.level;
  9915. newTexture.wrapU = this.wrapU;
  9916. newTexture.wrapV = this.wrapV;
  9917. newTexture.coordinatesIndex = this.coordinatesIndex;
  9918. newTexture.coordinatesMode = this.coordinatesMode;
  9919. newTexture.uOffset = this.uOffset;
  9920. newTexture.vOffset = this.vOffset;
  9921. newTexture.uScale = this.uScale;
  9922. newTexture.vScale = this.vScale;
  9923. newTexture.uAng = this.uAng;
  9924. newTexture.vAng = this.vAng;
  9925. newTexture.wAng = this.wAng;
  9926. return newTexture;
  9927. };
  9928. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  9929. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9930. if (typeof onLoad === "undefined") { onLoad = null; }
  9931. if (typeof onError === "undefined") { onError = null; }
  9932. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  9933. };
  9934. Texture.NEAREST_SAMPLINGMODE = 1;
  9935. Texture.BILINEAR_SAMPLINGMODE = 2;
  9936. Texture.TRILINEAR_SAMPLINGMODE = 3;
  9937. Texture.EXPLICIT_MODE = 0;
  9938. Texture.SPHERICAL_MODE = 1;
  9939. Texture.PLANAR_MODE = 2;
  9940. Texture.CUBIC_MODE = 3;
  9941. Texture.PROJECTION_MODE = 4;
  9942. Texture.SKYBOX_MODE = 5;
  9943. Texture.CLAMP_ADDRESSMODE = 0;
  9944. Texture.WRAP_ADDRESSMODE = 1;
  9945. Texture.MIRROR_ADDRESSMODE = 2;
  9946. return Texture;
  9947. })(BABYLON.BaseTexture);
  9948. BABYLON.Texture = Texture;
  9949. })(BABYLON || (BABYLON = {}));
  9950. var __extends = this.__extends || function (d, b) {
  9951. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9952. function __() { this.constructor = d; }
  9953. __.prototype = b.prototype;
  9954. d.prototype = new __();
  9955. };
  9956. var BABYLON;
  9957. (function (BABYLON) {
  9958. var CubeTexture = (function (_super) {
  9959. __extends(CubeTexture, _super);
  9960. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  9961. _super.call(this, scene);
  9962. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  9963. this.name = rootUrl;
  9964. this.url = rootUrl;
  9965. this._noMipmap = noMipmap;
  9966. this.hasAlpha = false;
  9967. this._texture = this._getFromCache(rootUrl, noMipmap);
  9968. if (!extensions) {
  9969. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  9970. }
  9971. this._extensions = extensions;
  9972. if (!this._texture) {
  9973. if (!scene.useDelayedTextureLoading) {
  9974. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  9975. } else {
  9976. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9977. }
  9978. }
  9979. this.isCube = true;
  9980. this._textureMatrix = BABYLON.Matrix.Identity();
  9981. }
  9982. CubeTexture.prototype.clone = function () {
  9983. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  9984. newTexture.level = this.level;
  9985. newTexture.wrapU = this.wrapU;
  9986. newTexture.wrapV = this.wrapV;
  9987. newTexture.coordinatesIndex = this.coordinatesIndex;
  9988. newTexture.coordinatesMode = this.coordinatesMode;
  9989. return newTexture;
  9990. };
  9991. CubeTexture.prototype.delayLoad = function () {
  9992. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9993. return;
  9994. }
  9995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9996. this._texture = this._getFromCache(this.url, this._noMipmap);
  9997. if (!this._texture) {
  9998. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  9999. }
  10000. };
  10001. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10002. return this._textureMatrix;
  10003. };
  10004. return CubeTexture;
  10005. })(BABYLON.BaseTexture);
  10006. BABYLON.CubeTexture = CubeTexture;
  10007. })(BABYLON || (BABYLON = {}));
  10008. var __extends = this.__extends || function (d, b) {
  10009. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10010. function __() { this.constructor = d; }
  10011. __.prototype = b.prototype;
  10012. d.prototype = new __();
  10013. };
  10014. var BABYLON;
  10015. (function (BABYLON) {
  10016. var RenderTargetTexture = (function (_super) {
  10017. __extends(RenderTargetTexture, _super);
  10018. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10019. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10020. _super.call(this, null, scene, !generateMipMaps);
  10021. this.renderList = new Array();
  10022. this.renderParticles = true;
  10023. this.renderSprites = false;
  10024. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10025. this._currentRefreshId = -1;
  10026. this._refreshRate = 1;
  10027. this.name = name;
  10028. this.isRenderTarget = true;
  10029. this._size = size;
  10030. this._generateMipMaps = generateMipMaps;
  10031. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10032. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10033. this._renderingManager = new BABYLON.RenderingManager(scene);
  10034. }
  10035. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10036. this._currentRefreshId = -1;
  10037. };
  10038. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10039. get: function () {
  10040. return this._refreshRate;
  10041. },
  10042. set: function (value) {
  10043. this._refreshRate = value;
  10044. this.resetRefreshCounter();
  10045. },
  10046. enumerable: true,
  10047. configurable: true
  10048. });
  10049. RenderTargetTexture.prototype._shouldRender = function () {
  10050. if (this._currentRefreshId === -1) {
  10051. this._currentRefreshId = 1;
  10052. return true;
  10053. }
  10054. if (this.refreshRate == this._currentRefreshId) {
  10055. this._currentRefreshId = 1;
  10056. return true;
  10057. }
  10058. this._currentRefreshId++;
  10059. return false;
  10060. };
  10061. RenderTargetTexture.prototype.isReady = function () {
  10062. if (!this.getScene().renderTargetsEnabled) {
  10063. return false;
  10064. }
  10065. return _super.prototype.isReady.call(this);
  10066. };
  10067. RenderTargetTexture.prototype.getRenderSize = function () {
  10068. return this._size;
  10069. };
  10070. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10071. get: function () {
  10072. return true;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. RenderTargetTexture.prototype.scale = function (ratio) {
  10078. var newSize = this._size * ratio;
  10079. this.resize(newSize, this._generateMipMaps);
  10080. };
  10081. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10082. this.releaseInternalTexture();
  10083. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10084. };
  10085. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10086. var scene = this.getScene();
  10087. var engine = scene.getEngine();
  10088. if (this._waitingRenderList) {
  10089. this.renderList = [];
  10090. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10091. var id = this._waitingRenderList[index];
  10092. this.renderList.push(scene.getMeshByID(id));
  10093. }
  10094. delete this._waitingRenderList;
  10095. }
  10096. if (!this.renderList) {
  10097. return;
  10098. }
  10099. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10100. engine.bindFramebuffer(this._texture);
  10101. }
  10102. engine.clear(scene.clearColor, true, true);
  10103. this._renderingManager.reset();
  10104. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10105. var mesh = this.renderList[meshIndex];
  10106. if (mesh) {
  10107. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10108. this.resetRefreshCounter();
  10109. continue;
  10110. }
  10111. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10112. mesh._activate(scene.getRenderId());
  10113. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10114. var subMesh = mesh.subMeshes[subIndex];
  10115. scene._activeVertices += subMesh.verticesCount;
  10116. this._renderingManager.dispatch(subMesh);
  10117. }
  10118. }
  10119. }
  10120. }
  10121. if (!this._doNotChangeAspectRatio) {
  10122. scene.updateTransformMatrix(true);
  10123. }
  10124. if (this.onBeforeRender) {
  10125. this.onBeforeRender();
  10126. }
  10127. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10128. if (useCameraPostProcess) {
  10129. scene.postProcessManager._finalizeFrame(false, this._texture);
  10130. }
  10131. if (this.onAfterRender) {
  10132. this.onAfterRender();
  10133. }
  10134. engine.unBindFramebuffer(this._texture);
  10135. if (!this._doNotChangeAspectRatio) {
  10136. scene.updateTransformMatrix(true);
  10137. }
  10138. };
  10139. RenderTargetTexture.prototype.clone = function () {
  10140. var textureSize = this.getSize();
  10141. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10142. newTexture.hasAlpha = this.hasAlpha;
  10143. newTexture.level = this.level;
  10144. newTexture.coordinatesMode = this.coordinatesMode;
  10145. newTexture.renderList = this.renderList.slice(0);
  10146. return newTexture;
  10147. };
  10148. return RenderTargetTexture;
  10149. })(BABYLON.Texture);
  10150. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10151. })(BABYLON || (BABYLON = {}));
  10152. var __extends = this.__extends || function (d, b) {
  10153. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10154. function __() { this.constructor = d; }
  10155. __.prototype = b.prototype;
  10156. d.prototype = new __();
  10157. };
  10158. var BABYLON;
  10159. (function (BABYLON) {
  10160. var ProceduralTexture = (function (_super) {
  10161. __extends(ProceduralTexture, _super);
  10162. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10163. _super.call(this, null, scene, !generateMipMaps);
  10164. this._currentRefreshId = -1;
  10165. this._refreshRate = 1;
  10166. this._vertexDeclaration = [2];
  10167. this._vertexStrideSize = 2 * 4;
  10168. this._uniforms = new Array();
  10169. this._samplers = new Array();
  10170. this._textures = new Array();
  10171. this._floats = new Array();
  10172. this._floatsArrays = {};
  10173. this._colors3 = new Array();
  10174. this._colors4 = new Array();
  10175. this._vectors2 = new Array();
  10176. this._vectors3 = new Array();
  10177. this._matrices = new Array();
  10178. scene._proceduralTextures.push(this);
  10179. this.name = name;
  10180. this.isRenderTarget = true;
  10181. this._size = size;
  10182. this._generateMipMaps = generateMipMaps;
  10183. this._fragment = fragment;
  10184. this._fallbackTexture = fallbackTexture;
  10185. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10186. var vertices = [];
  10187. vertices.push(1, 1);
  10188. vertices.push(-1, 1);
  10189. vertices.push(-1, -1);
  10190. vertices.push(1, -1);
  10191. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10192. var indices = [];
  10193. indices.push(0);
  10194. indices.push(1);
  10195. indices.push(2);
  10196. indices.push(0);
  10197. indices.push(2);
  10198. indices.push(3);
  10199. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10200. }
  10201. ProceduralTexture.prototype.isReady = function () {
  10202. var _this = this;
  10203. var engine = this.getScene().getEngine();
  10204. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10205. _this.releaseInternalTexture();
  10206. _this._texture = _this._fallbackTexture._texture;
  10207. _this._texture.references++;
  10208. });
  10209. return this._effect.isReady();
  10210. };
  10211. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10212. this._currentRefreshId = -1;
  10213. };
  10214. ProceduralTexture.prototype.setFragment = function (fragment) {
  10215. this._fragment = fragment;
  10216. };
  10217. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10218. get: function () {
  10219. return this._refreshRate;
  10220. },
  10221. set: function (value) {
  10222. this._refreshRate = value;
  10223. this.resetRefreshCounter();
  10224. },
  10225. enumerable: true,
  10226. configurable: true
  10227. });
  10228. ProceduralTexture.prototype._shouldRender = function () {
  10229. if (!this.isReady() || !this._texture) {
  10230. return false;
  10231. }
  10232. if (this._currentRefreshId === -1) {
  10233. this._currentRefreshId = 1;
  10234. return true;
  10235. }
  10236. if (this.refreshRate == this._currentRefreshId) {
  10237. this._currentRefreshId = 1;
  10238. return true;
  10239. }
  10240. this._currentRefreshId++;
  10241. return false;
  10242. };
  10243. ProceduralTexture.prototype.getRenderSize = function () {
  10244. return this._size;
  10245. };
  10246. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10247. this.releaseInternalTexture();
  10248. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10249. };
  10250. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10251. if (this._uniforms.indexOf(uniformName) === -1) {
  10252. this._uniforms.push(uniformName);
  10253. }
  10254. };
  10255. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10256. if (this._samplers.indexOf(name) === -1) {
  10257. this._samplers.push(name);
  10258. }
  10259. this._textures[name] = texture;
  10260. return this;
  10261. };
  10262. ProceduralTexture.prototype.setFloat = function (name, value) {
  10263. this._checkUniform(name);
  10264. this._floats[name] = value;
  10265. return this;
  10266. };
  10267. ProceduralTexture.prototype.setFloats = function (name, value) {
  10268. this._checkUniform(name);
  10269. this._floatsArrays[name] = value;
  10270. return this;
  10271. };
  10272. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10273. this._checkUniform(name);
  10274. this._colors3[name] = value;
  10275. return this;
  10276. };
  10277. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10278. this._checkUniform(name);
  10279. this._colors4[name] = value;
  10280. return this;
  10281. };
  10282. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10283. this._checkUniform(name);
  10284. this._vectors2[name] = value;
  10285. return this;
  10286. };
  10287. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10288. this._checkUniform(name);
  10289. this._vectors3[name] = value;
  10290. return this;
  10291. };
  10292. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10293. this._checkUniform(name);
  10294. this._matrices[name] = value;
  10295. return this;
  10296. };
  10297. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10298. var scene = this.getScene();
  10299. var engine = scene.getEngine();
  10300. engine.bindFramebuffer(this._texture);
  10301. engine.clear(scene.clearColor, true, true);
  10302. engine.enableEffect(this._effect);
  10303. engine.setState(false);
  10304. for (var name in this._textures) {
  10305. this._effect.setTexture(name, this._textures[name]);
  10306. }
  10307. for (name in this._floats) {
  10308. this._effect.setFloat(name, this._floats[name]);
  10309. }
  10310. for (name in this._floatsArrays) {
  10311. this._effect.setArray(name, this._floatsArrays[name]);
  10312. }
  10313. for (name in this._colors3) {
  10314. this._effect.setColor3(name, this._colors3[name]);
  10315. }
  10316. for (name in this._colors4) {
  10317. var color = this._colors4[name];
  10318. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10319. }
  10320. for (name in this._vectors2) {
  10321. this._effect.setVector2(name, this._vectors2[name]);
  10322. }
  10323. for (name in this._vectors3) {
  10324. this._effect.setVector3(name, this._vectors3[name]);
  10325. }
  10326. for (name in this._matrices) {
  10327. this._effect.setMatrix(name, this._matrices[name]);
  10328. }
  10329. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10330. engine.draw(true, 0, 6);
  10331. engine.unBindFramebuffer(this._texture);
  10332. };
  10333. ProceduralTexture.prototype.clone = function () {
  10334. var textureSize = this.getSize();
  10335. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10336. newTexture.hasAlpha = this.hasAlpha;
  10337. newTexture.level = this.level;
  10338. newTexture.coordinatesMode = this.coordinatesMode;
  10339. return newTexture;
  10340. };
  10341. ProceduralTexture.prototype.dispose = function () {
  10342. var index = this.getScene()._proceduralTextures.indexOf(this);
  10343. if (index >= 0) {
  10344. this.getScene()._proceduralTextures.splice(index, 1);
  10345. }
  10346. _super.prototype.dispose.call(this);
  10347. };
  10348. return ProceduralTexture;
  10349. })(BABYLON.Texture);
  10350. BABYLON.ProceduralTexture = ProceduralTexture;
  10351. })(BABYLON || (BABYLON = {}));
  10352. var __extends = this.__extends || function (d, b) {
  10353. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10354. function __() { this.constructor = d; }
  10355. __.prototype = b.prototype;
  10356. d.prototype = new __();
  10357. };
  10358. var BABYLON;
  10359. (function (BABYLON) {
  10360. var WoodProceduralTexture = (function (_super) {
  10361. __extends(WoodProceduralTexture, _super);
  10362. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10363. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10364. this._ampScale = 100.0;
  10365. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  10366. this.updateShaderUniforms();
  10367. this.refreshRate = 0;
  10368. }
  10369. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10370. this.setFloat("ampScale", this._ampScale);
  10371. this.setColor3("woodColor", this._woodColor);
  10372. };
  10373. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10374. get: function () {
  10375. return this._ampScale;
  10376. },
  10377. set: function (value) {
  10378. this._ampScale = value;
  10379. this.updateShaderUniforms();
  10380. },
  10381. enumerable: true,
  10382. configurable: true
  10383. });
  10384. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  10385. get: function () {
  10386. return this._woodColor;
  10387. },
  10388. set: function (value) {
  10389. this._woodColor = value;
  10390. this.updateShaderUniforms();
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. return WoodProceduralTexture;
  10396. })(BABYLON.ProceduralTexture);
  10397. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10398. var FireProceduralTexture = (function (_super) {
  10399. __extends(FireProceduralTexture, _super);
  10400. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10401. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10402. this._time = 0.0;
  10403. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10404. this._shift = 1.6;
  10405. this._alpha = 1.0;
  10406. this._autoGenerateTime = true;
  10407. this._fireColors = FireProceduralTexture.RedFireColors;
  10408. this.updateShaderUniforms();
  10409. this.refreshRate = 1;
  10410. }
  10411. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10412. this.setFloat("iGlobalTime", this._time);
  10413. this.setVector2("speed", this._speed);
  10414. this.setFloat("shift", this._shift);
  10415. this.setFloat("alpha", this._alpha);
  10416. this.setColor3("c1", new BABYLON.Color3(this._fireColors[0][0], this._fireColors[0][1], this._fireColors[0][2]));
  10417. this.setColor3("c2", new BABYLON.Color3(this._fireColors[1][0], this._fireColors[1][1], this._fireColors[1][2]));
  10418. this.setColor3("c3", new BABYLON.Color3(this._fireColors[2][0], this._fireColors[2][1], this._fireColors[2][2]));
  10419. this.setColor3("c4", new BABYLON.Color3(this._fireColors[3][0], this._fireColors[3][1], this._fireColors[3][2]));
  10420. this.setColor3("c5", new BABYLON.Color3(this._fireColors[4][0], this._fireColors[4][1], this._fireColors[4][2]));
  10421. this.setColor3("c6", new BABYLON.Color3(this._fireColors[5][0], this._fireColors[5][1], this._fireColors[5][2]));
  10422. };
  10423. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10424. if (this._autoGenerateTime) {
  10425. this._time += this.getScene().getAnimationRatio() * 0.03;
  10426. this.updateShaderUniforms();
  10427. }
  10428. _super.prototype.render.call(this, useCameraPostProcess);
  10429. };
  10430. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10431. get: function () {
  10432. return [
  10433. [0.5, 0.0, 1.0],
  10434. [0.9, 0.0, 1.0],
  10435. [0.2, 0.0, 1.0],
  10436. [1.0, 0.9, 1.0],
  10437. [0.1, 0.1, 1.0],
  10438. [0.9, 0.9, 1.0]
  10439. ];
  10440. },
  10441. enumerable: true,
  10442. configurable: true
  10443. });
  10444. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10445. get: function () {
  10446. return [
  10447. [0.5, 1.0, 0.0],
  10448. [0.5, 1.0, 0.0],
  10449. [0.3, 0.4, 0.0],
  10450. [0.5, 1.0, 0.0],
  10451. [0.2, 0.0, 0.0],
  10452. [0.5, 1.0, 0.0]
  10453. ];
  10454. },
  10455. enumerable: true,
  10456. configurable: true
  10457. });
  10458. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10459. get: function () {
  10460. return [
  10461. [0.5, 0.0, 0.1],
  10462. [0.9, 0.0, 0.0],
  10463. [0.2, 0.0, 0.0],
  10464. [1.0, 0.9, 0.0],
  10465. [0.1, 0.1, 0.1],
  10466. [0.9, 0.9, 0.9]
  10467. ];
  10468. },
  10469. enumerable: true,
  10470. configurable: true
  10471. });
  10472. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10473. get: function () {
  10474. return [
  10475. [0.1, 0.0, 0.5],
  10476. [0.0, 0.0, 0.5],
  10477. [0.1, 0.0, 0.2],
  10478. [0.0, 0.0, 1.0],
  10479. [0.1, 0.2, 0.3],
  10480. [0.0, 0.2, 0.9]
  10481. ];
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10487. get: function () {
  10488. return this._fireColors;
  10489. },
  10490. set: function (value) {
  10491. this._fireColors = value;
  10492. this.updateShaderUniforms();
  10493. },
  10494. enumerable: true,
  10495. configurable: true
  10496. });
  10497. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10498. get: function () {
  10499. return this._time;
  10500. },
  10501. set: function (value) {
  10502. this._time = value;
  10503. this.updateShaderUniforms();
  10504. },
  10505. enumerable: true,
  10506. configurable: true
  10507. });
  10508. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10509. get: function () {
  10510. return this._speed;
  10511. },
  10512. set: function (value) {
  10513. this._speed = value;
  10514. this.updateShaderUniforms();
  10515. },
  10516. enumerable: true,
  10517. configurable: true
  10518. });
  10519. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10520. get: function () {
  10521. return this._shift;
  10522. },
  10523. set: function (value) {
  10524. this._shift = value;
  10525. this.updateShaderUniforms();
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10531. get: function () {
  10532. return this._alpha;
  10533. },
  10534. set: function (value) {
  10535. this._alpha = value;
  10536. this.updateShaderUniforms();
  10537. },
  10538. enumerable: true,
  10539. configurable: true
  10540. });
  10541. return FireProceduralTexture;
  10542. })(BABYLON.ProceduralTexture);
  10543. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10544. var CloudProceduralTexture = (function (_super) {
  10545. __extends(CloudProceduralTexture, _super);
  10546. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10547. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10548. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  10549. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  10550. this.updateShaderUniforms();
  10551. this.refreshRate = 0;
  10552. }
  10553. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  10554. this.setColor3("skyColor", this._skyColor);
  10555. this.setColor3("cloudColor", this._cloudColor);
  10556. };
  10557. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  10558. get: function () {
  10559. return this._skyColor;
  10560. },
  10561. set: function (value) {
  10562. this._skyColor = value;
  10563. this.updateShaderUniforms();
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  10569. get: function () {
  10570. return this._cloudColor;
  10571. },
  10572. set: function (value) {
  10573. this._cloudColor = value;
  10574. this.updateShaderUniforms();
  10575. },
  10576. enumerable: true,
  10577. configurable: true
  10578. });
  10579. return CloudProceduralTexture;
  10580. })(BABYLON.ProceduralTexture);
  10581. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10582. var GrassProceduralTexture = (function (_super) {
  10583. __extends(GrassProceduralTexture, _super);
  10584. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10585. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  10586. this.refreshRate = 0;
  10587. }
  10588. return GrassProceduralTexture;
  10589. })(BABYLON.ProceduralTexture);
  10590. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  10591. var RockProceduralTexture = (function (_super) {
  10592. __extends(RockProceduralTexture, _super);
  10593. function RockProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10594. _super.call(this, name, size, "rock", scene, fallbackTexture, generateMipMaps);
  10595. this.refreshRate = 0;
  10596. }
  10597. return RockProceduralTexture;
  10598. })(BABYLON.ProceduralTexture);
  10599. BABYLON.RockProceduralTexture = RockProceduralTexture;
  10600. var RoadProceduralTexture = (function (_super) {
  10601. __extends(RoadProceduralTexture, _super);
  10602. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10603. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  10604. this.refreshRate = 0;
  10605. }
  10606. return RoadProceduralTexture;
  10607. })(BABYLON.ProceduralTexture);
  10608. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  10609. var BrickProceduralTexture = (function (_super) {
  10610. __extends(BrickProceduralTexture, _super);
  10611. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10612. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  10613. this._numberOfBricksHeight = 15;
  10614. this._numberOfBricksWidth = 5;
  10615. this.updateShaderUniforms();
  10616. this.refreshRate = 0;
  10617. }
  10618. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  10619. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10620. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10621. };
  10622. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  10623. get: function () {
  10624. return this._numberOfBricksHeight;
  10625. },
  10626. enumerable: true,
  10627. configurable: true
  10628. });
  10629. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  10630. set: function (value) {
  10631. this._numberOfBricksHeight = value;
  10632. this.updateShaderUniforms();
  10633. },
  10634. enumerable: true,
  10635. configurable: true
  10636. });
  10637. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  10638. get: function () {
  10639. return this._numberOfBricksWidth;
  10640. },
  10641. set: function (value) {
  10642. this._numberOfBricksHeight = value;
  10643. this.updateShaderUniforms();
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. return BrickProceduralTexture;
  10649. })(BABYLON.ProceduralTexture);
  10650. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  10651. var MarbleProceduralTexture = (function (_super) {
  10652. __extends(MarbleProceduralTexture, _super);
  10653. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10654. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  10655. this._numberOfBricksHeight = 3;
  10656. this._numberOfBricksWidth = 3;
  10657. this.updateShaderUniforms();
  10658. this.refreshRate = 0;
  10659. }
  10660. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  10661. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10662. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10663. };
  10664. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfBricksHeight", {
  10665. get: function () {
  10666. return this._numberOfBricksHeight;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(MarbleProceduralTexture.prototype, "cloudColor", {
  10672. set: function (value) {
  10673. this._numberOfBricksHeight = value;
  10674. this.updateShaderUniforms();
  10675. },
  10676. enumerable: true,
  10677. configurable: true
  10678. });
  10679. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfBricksWidth", {
  10680. get: function () {
  10681. return this._numberOfBricksWidth;
  10682. },
  10683. set: function (value) {
  10684. this._numberOfBricksHeight = value;
  10685. this.updateShaderUniforms();
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. return MarbleProceduralTexture;
  10691. })(BABYLON.ProceduralTexture);
  10692. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  10693. })(BABYLON || (BABYLON = {}));
  10694. var __extends = this.__extends || function (d, b) {
  10695. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10696. function __() { this.constructor = d; }
  10697. __.prototype = b.prototype;
  10698. d.prototype = new __();
  10699. };
  10700. var BABYLON;
  10701. (function (BABYLON) {
  10702. var CustomProceduralTexture = (function (_super) {
  10703. __extends(CustomProceduralTexture, _super);
  10704. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  10705. _super.call(this, name, size, "empty", scene, fallbackTexture, generateMipMaps);
  10706. this._generateTime = true;
  10707. this._time = 0;
  10708. this._shaderLoaded = false;
  10709. this._texturePath = texturePath;
  10710. this.loadJson(texturePath);
  10711. this.refreshRate = 0;
  10712. }
  10713. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  10714. var _this = this;
  10715. function noConfigFile() {
  10716. BABYLON.Tools.Log("No config file found in " + jsonUrl);
  10717. }
  10718. var that = this;
  10719. var configFileUrl = jsonUrl + "/config.json";
  10720. var xhr = new XMLHttpRequest();
  10721. xhr.open("GET", configFileUrl, true);
  10722. xhr.addEventListener("load", function () {
  10723. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  10724. try {
  10725. that._config = JSON.parse(xhr.response);
  10726. that.updateShaderUniforms();
  10727. that.setFragment(jsonUrl + "/custom");
  10728. that._generateTime = that._config.generateTime;
  10729. if (that._generateTime)
  10730. _this.refreshRate = 1;
  10731. that._shaderLoaded = true;
  10732. that.render();
  10733. } catch (ex) {
  10734. noConfigFile();
  10735. }
  10736. } else {
  10737. noConfigFile();
  10738. }
  10739. }, false);
  10740. xhr.addEventListener("error", function (event) {
  10741. noConfigFile();
  10742. }, false);
  10743. try {
  10744. xhr.send();
  10745. } catch (ex) {
  10746. BABYLON.Tools.Error("Error on XHR send request.");
  10747. }
  10748. };
  10749. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10750. if (!this._shaderLoaded)
  10751. return;
  10752. if (this._generateTime) {
  10753. this._time += this.getScene().getAnimationRatio() * 0.03;
  10754. this.updateShaderUniforms();
  10755. }
  10756. _super.prototype.render.call(this, useCameraPostProcess);
  10757. };
  10758. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  10759. for (var i = 0; i < this._config.texture2Ds.length; i++) {
  10760. this.setTexture(this._config.texture2Ds[i].textureName, new BABYLON.Texture(this._texturePath + "/" + this._config.texture2Ds[i].textureRelativeUrl, this.getScene()));
  10761. }
  10762. for (var j = 0; j < this._config.uniforms.length; j++) {
  10763. var uniform = this._config.uniforms[j];
  10764. switch (uniform.type) {
  10765. case "float":
  10766. this.setFloat(uniform.name, uniform.value);
  10767. break;
  10768. case "color3":
  10769. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  10770. break;
  10771. case "color4":
  10772. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  10773. break;
  10774. case "vector2":
  10775. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  10776. break;
  10777. case "vector3":
  10778. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  10779. break;
  10780. }
  10781. }
  10782. };
  10783. Object.defineProperty(CustomProceduralTexture.prototype, "generateTime", {
  10784. get: function () {
  10785. return this.generateTime;
  10786. },
  10787. set: function (value) {
  10788. this.generateTime = value;
  10789. this.updateShaderUniforms();
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. return CustomProceduralTexture;
  10795. })(BABYLON.ProceduralTexture);
  10796. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  10797. })(BABYLON || (BABYLON = {}));
  10798. var __extends = this.__extends || function (d, b) {
  10799. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10800. function __() { this.constructor = d; }
  10801. __.prototype = b.prototype;
  10802. d.prototype = new __();
  10803. };
  10804. var BABYLON;
  10805. (function (BABYLON) {
  10806. var MirrorTexture = (function (_super) {
  10807. __extends(MirrorTexture, _super);
  10808. function MirrorTexture(name, size, scene, generateMipMaps) {
  10809. var _this = this;
  10810. _super.call(this, name, size, scene, generateMipMaps, true);
  10811. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  10812. this._transformMatrix = BABYLON.Matrix.Zero();
  10813. this._mirrorMatrix = BABYLON.Matrix.Zero();
  10814. this.onBeforeRender = function () {
  10815. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  10816. _this._savedViewMatrix = scene.getViewMatrix();
  10817. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  10818. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  10819. scene.clipPlane = _this.mirrorPlane;
  10820. scene.getEngine().cullBackFaces = false;
  10821. };
  10822. this.onAfterRender = function () {
  10823. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  10824. scene.getEngine().cullBackFaces = true;
  10825. delete scene.clipPlane;
  10826. };
  10827. }
  10828. MirrorTexture.prototype.clone = function () {
  10829. var textureSize = this.getSize();
  10830. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10831. newTexture.hasAlpha = this.hasAlpha;
  10832. newTexture.level = this.level;
  10833. newTexture.mirrorPlane = this.mirrorPlane.clone();
  10834. newTexture.renderList = this.renderList.slice(0);
  10835. return newTexture;
  10836. };
  10837. return MirrorTexture;
  10838. })(BABYLON.RenderTargetTexture);
  10839. BABYLON.MirrorTexture = MirrorTexture;
  10840. })(BABYLON || (BABYLON = {}));
  10841. var __extends = this.__extends || function (d, b) {
  10842. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10843. function __() { this.constructor = d; }
  10844. __.prototype = b.prototype;
  10845. d.prototype = new __();
  10846. };
  10847. var BABYLON;
  10848. (function (BABYLON) {
  10849. var DynamicTexture = (function (_super) {
  10850. __extends(DynamicTexture, _super);
  10851. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  10852. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10853. _super.call(this, null, scene, !generateMipMaps);
  10854. this.name = name;
  10855. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10856. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10857. this._generateMipMaps = generateMipMaps;
  10858. if (options.getContext) {
  10859. this._canvas = options;
  10860. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10861. } else {
  10862. this._canvas = document.createElement("canvas");
  10863. if (options.width) {
  10864. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  10865. } else {
  10866. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  10867. }
  10868. }
  10869. var textureSize = this.getSize();
  10870. this._canvas.width = textureSize.width;
  10871. this._canvas.height = textureSize.height;
  10872. this._context = this._canvas.getContext("2d");
  10873. }
  10874. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  10875. get: function () {
  10876. return true;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. DynamicTexture.prototype.scale = function (ratio) {
  10882. var textureSize = this.getSize();
  10883. textureSize.width *= ratio;
  10884. textureSize.height *= ratio;
  10885. this._canvas.width = textureSize.width;
  10886. this._canvas.height = textureSize.height;
  10887. this.releaseInternalTexture();
  10888. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  10889. };
  10890. DynamicTexture.prototype.getContext = function () {
  10891. return this._context;
  10892. };
  10893. DynamicTexture.prototype.update = function (invertY) {
  10894. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  10895. };
  10896. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  10897. var size = this.getSize();
  10898. if (clearColor) {
  10899. this._context.fillStyle = clearColor;
  10900. this._context.fillRect(0, 0, size.width, size.height);
  10901. }
  10902. this._context.font = font;
  10903. if (x === null) {
  10904. var textSize = this._context.measureText(text);
  10905. x = (size.width - textSize.width) / 2;
  10906. }
  10907. this._context.fillStyle = color;
  10908. this._context.fillText(text, x, y);
  10909. this.update(invertY);
  10910. };
  10911. DynamicTexture.prototype.clone = function () {
  10912. var textureSize = this.getSize();
  10913. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10914. newTexture.hasAlpha = this.hasAlpha;
  10915. newTexture.level = this.level;
  10916. newTexture.wrapU = this.wrapU;
  10917. newTexture.wrapV = this.wrapV;
  10918. return newTexture;
  10919. };
  10920. return DynamicTexture;
  10921. })(BABYLON.Texture);
  10922. BABYLON.DynamicTexture = DynamicTexture;
  10923. })(BABYLON || (BABYLON = {}));
  10924. var __extends = this.__extends || function (d, b) {
  10925. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10926. function __() { this.constructor = d; }
  10927. __.prototype = b.prototype;
  10928. d.prototype = new __();
  10929. };
  10930. var BABYLON;
  10931. (function (BABYLON) {
  10932. var VideoTexture = (function (_super) {
  10933. __extends(VideoTexture, _super);
  10934. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  10935. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10936. var _this = this;
  10937. _super.call(this, null, scene, !generateMipMaps, invertY);
  10938. this._autoLaunch = true;
  10939. this.name = name;
  10940. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10941. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10942. var requiredWidth = size.width || size;
  10943. var requiredHeight = size.height || size;
  10944. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  10945. var textureSize = this.getSize();
  10946. this.video = document.createElement("video");
  10947. this.video.width = textureSize.width;
  10948. this.video.height = textureSize.height;
  10949. this.video.autoplay = false;
  10950. this.video.loop = true;
  10951. this.video.addEventListener("canplaythrough", function () {
  10952. if (_this._texture) {
  10953. _this._texture.isReady = true;
  10954. }
  10955. });
  10956. urls.forEach(function (url) {
  10957. var source = document.createElement("source");
  10958. source.src = url;
  10959. _this.video.appendChild(source);
  10960. });
  10961. this._lastUpdate = BABYLON.Tools.Now;
  10962. }
  10963. VideoTexture.prototype.update = function () {
  10964. if (this._autoLaunch) {
  10965. this._autoLaunch = false;
  10966. this.video.play();
  10967. }
  10968. var now = BABYLON.Tools.Now;
  10969. if (now - this._lastUpdate < 15) {
  10970. return false;
  10971. }
  10972. this._lastUpdate = now;
  10973. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  10974. return true;
  10975. };
  10976. return VideoTexture;
  10977. })(BABYLON.Texture);
  10978. BABYLON.VideoTexture = VideoTexture;
  10979. })(BABYLON || (BABYLON = {}));
  10980. var BABYLON;
  10981. (function (BABYLON) {
  10982. var EffectFallbacks = (function () {
  10983. function EffectFallbacks() {
  10984. this._defines = {};
  10985. this._currentRank = 32;
  10986. this._maxRank = -1;
  10987. }
  10988. EffectFallbacks.prototype.addFallback = function (rank, define) {
  10989. if (!this._defines[rank]) {
  10990. if (rank < this._currentRank) {
  10991. this._currentRank = rank;
  10992. }
  10993. if (rank > this._maxRank) {
  10994. this._maxRank = rank;
  10995. }
  10996. this._defines[rank] = new Array();
  10997. }
  10998. this._defines[rank].push(define);
  10999. };
  11000. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11001. get: function () {
  11002. return this._currentRank <= this._maxRank;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11008. var currentFallbacks = this._defines[this._currentRank];
  11009. for (var index = 0; index < currentFallbacks.length; index++) {
  11010. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11011. }
  11012. this._currentRank++;
  11013. return currentDefines;
  11014. };
  11015. return EffectFallbacks;
  11016. })();
  11017. BABYLON.EffectFallbacks = EffectFallbacks;
  11018. var Effect = (function () {
  11019. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11020. var _this = this;
  11021. this._isReady = false;
  11022. this._compilationError = "";
  11023. this._valueCache = [];
  11024. this._engine = engine;
  11025. this.name = baseName;
  11026. this.defines = defines;
  11027. this._uniformsNames = uniformsNames.concat(samplers);
  11028. this._samplers = samplers;
  11029. this._attributesNames = attributesNames;
  11030. this.onError = onError;
  11031. this.onCompiled = onCompiled;
  11032. var vertexSource;
  11033. var fragmentSource;
  11034. if (baseName.vertexElement) {
  11035. vertexSource = document.getElementById(baseName.vertexElement);
  11036. if (!vertexSource) {
  11037. vertexSource = baseName.vertexElement;
  11038. }
  11039. } else {
  11040. vertexSource = baseName.vertex || baseName;
  11041. }
  11042. if (baseName.fragmentElement) {
  11043. fragmentSource = document.getElementById(baseName.fragmentElement);
  11044. if (!fragmentSource) {
  11045. fragmentSource = baseName.fragmentElement;
  11046. }
  11047. } else {
  11048. fragmentSource = baseName.fragment || baseName;
  11049. }
  11050. this._loadVertexShader(vertexSource, function (vertexCode) {
  11051. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11052. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11053. });
  11054. });
  11055. }
  11056. Effect.prototype.isReady = function () {
  11057. return this._isReady;
  11058. };
  11059. Effect.prototype.getProgram = function () {
  11060. return this._program;
  11061. };
  11062. Effect.prototype.getAttributesNames = function () {
  11063. return this._attributesNames;
  11064. };
  11065. Effect.prototype.getAttributeLocation = function (index) {
  11066. return this._attributes[index];
  11067. };
  11068. Effect.prototype.getAttributeLocationByName = function (name) {
  11069. var index = this._attributesNames.indexOf(name);
  11070. return this._attributes[index];
  11071. };
  11072. Effect.prototype.getAttributesCount = function () {
  11073. return this._attributes.length;
  11074. };
  11075. Effect.prototype.getUniformIndex = function (uniformName) {
  11076. return this._uniformsNames.indexOf(uniformName);
  11077. };
  11078. Effect.prototype.getUniform = function (uniformName) {
  11079. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11080. };
  11081. Effect.prototype.getSamplers = function () {
  11082. return this._samplers;
  11083. };
  11084. Effect.prototype.getCompilationError = function () {
  11085. return this._compilationError;
  11086. };
  11087. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11088. if (vertex instanceof HTMLElement) {
  11089. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11090. callback(vertexCode);
  11091. return;
  11092. }
  11093. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  11094. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  11095. return;
  11096. }
  11097. var vertexShaderUrl;
  11098. if (vertex[0] === ".") {
  11099. vertexShaderUrl = vertex;
  11100. } else {
  11101. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11102. }
  11103. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11104. };
  11105. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11106. if (fragment instanceof HTMLElement) {
  11107. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11108. callback(fragmentCode);
  11109. return;
  11110. }
  11111. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  11112. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  11113. return;
  11114. }
  11115. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  11116. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  11117. return;
  11118. }
  11119. var fragmentShaderUrl;
  11120. if (fragment[0] === ".") {
  11121. fragmentShaderUrl = fragment;
  11122. } else {
  11123. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11124. }
  11125. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11126. };
  11127. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11128. try {
  11129. var engine = this._engine;
  11130. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11131. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11132. this._attributes = engine.getAttributes(this._program, attributesNames);
  11133. for (var index = 0; index < this._samplers.length; index++) {
  11134. var sampler = this.getUniform(this._samplers[index]);
  11135. if (sampler == null) {
  11136. this._samplers.splice(index, 1);
  11137. index--;
  11138. }
  11139. }
  11140. engine.bindSamplers(this);
  11141. this._isReady = true;
  11142. if (this.onCompiled) {
  11143. this.onCompiled(this);
  11144. }
  11145. } catch (e) {
  11146. if (e.message.indexOf("highp") !== -1) {
  11147. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  11148. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  11149. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11150. return;
  11151. }
  11152. if (fallbacks && fallbacks.isMoreFallbacks) {
  11153. defines = fallbacks.reduce(defines);
  11154. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11155. } else {
  11156. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  11157. BABYLON.Tools.Error("Defines: " + defines);
  11158. BABYLON.Tools.Error("Error: " + e.message);
  11159. this._compilationError = e.message;
  11160. if (this.onError) {
  11161. this.onError(this, this._compilationError);
  11162. }
  11163. }
  11164. }
  11165. };
  11166. Effect.prototype._bindTexture = function (channel, texture) {
  11167. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  11168. };
  11169. Effect.prototype.setTexture = function (channel, texture) {
  11170. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  11171. };
  11172. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11173. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  11174. };
  11175. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  11176. if (!this._valueCache[uniformName]) {
  11177. this._valueCache[uniformName] = [x, y];
  11178. return;
  11179. }
  11180. this._valueCache[uniformName][0] = x;
  11181. this._valueCache[uniformName][1] = y;
  11182. };
  11183. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  11184. if (!this._valueCache[uniformName]) {
  11185. this._valueCache[uniformName] = [x, y, z];
  11186. return;
  11187. }
  11188. this._valueCache[uniformName][0] = x;
  11189. this._valueCache[uniformName][1] = y;
  11190. this._valueCache[uniformName][2] = z;
  11191. };
  11192. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  11193. if (!this._valueCache[uniformName]) {
  11194. this._valueCache[uniformName] = [x, y, z, w];
  11195. return;
  11196. }
  11197. this._valueCache[uniformName][0] = x;
  11198. this._valueCache[uniformName][1] = y;
  11199. this._valueCache[uniformName][2] = z;
  11200. this._valueCache[uniformName][3] = w;
  11201. };
  11202. Effect.prototype.setArray = function (uniformName, array) {
  11203. this._engine.setArray(this.getUniform(uniformName), array);
  11204. return this;
  11205. };
  11206. Effect.prototype.setMatrices = function (uniformName, matrices) {
  11207. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  11208. return this;
  11209. };
  11210. Effect.prototype.setMatrix = function (uniformName, matrix) {
  11211. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  11212. return this;
  11213. };
  11214. Effect.prototype.setFloat = function (uniformName, value) {
  11215. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  11216. return this;
  11217. this._valueCache[uniformName] = value;
  11218. this._engine.setFloat(this.getUniform(uniformName), value);
  11219. return this;
  11220. };
  11221. Effect.prototype.setBool = function (uniformName, bool) {
  11222. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  11223. return this;
  11224. this._valueCache[uniformName] = bool;
  11225. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  11226. return this;
  11227. };
  11228. Effect.prototype.setVector2 = function (uniformName, vector2) {
  11229. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  11230. return this;
  11231. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  11232. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  11233. return this;
  11234. };
  11235. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  11236. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  11237. return this;
  11238. this._cacheFloat2(uniformName, x, y);
  11239. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  11240. return this;
  11241. };
  11242. Effect.prototype.setVector3 = function (uniformName, vector3) {
  11243. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  11244. return this;
  11245. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  11246. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  11247. return this;
  11248. };
  11249. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  11250. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  11251. return this;
  11252. this._cacheFloat3(uniformName, x, y, z);
  11253. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11254. return this;
  11255. };
  11256. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11257. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  11258. return this;
  11259. this._cacheFloat4(uniformName, x, y, z, w);
  11260. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11261. return this;
  11262. };
  11263. Effect.prototype.setColor3 = function (uniformName, color3) {
  11264. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  11265. return this;
  11266. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11267. this._engine.setColor3(this.getUniform(uniformName), color3);
  11268. return this;
  11269. };
  11270. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11271. 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)
  11272. return this;
  11273. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11274. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11275. return this;
  11276. };
  11277. 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}",
  11278. 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}",
  11279. 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}",
  11280. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n vec3 brick = vec3(0.77, 0.47, 0.40);\n vec3 joint = vec3(0.72, 0.72, 0.72);\n\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n\n vec3 color = brick;\n\n\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(joint, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(joint, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float momo = mod(floor(yi) + floor(xi), 3.0);\n\n if (momo == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (momo == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n\n\n //color = mix(momo, vec3(0.53, 0.2, 0.0), fbm(brickvUV * 2.0));\n }\n\n\n gl_FragColor = vec4(color, 1.0);\n}",
  11281. 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}",
  11282. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11283. 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}",
  11284. 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}",
  11285. 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}",
  11286. 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}",
  11287. 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}",
  11288. emptyPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvoid main(void)\n{\n \n}",
  11289. 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}",
  11290. 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}",
  11291. 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}",
  11292. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n\n vec3 herb1 = vec3(0.29, 0.38, 0.02);\n vec3 herb2 = vec3(0.36, 0.49, 0.09);\n vec3 herb3 = vec3(0.51, 0.6, 0.28);\n vec3 dirt = vec3(0.6, 0.46, 0.13);\n\n vec3 ground = vec3(1,1,1);\n \n ground = mix(ground, herb1, rand(gl_FragCoord.xy * 4.0));\n ground = mix(ground, herb2, rand(gl_FragCoord.xy * 8.0));\n ground = mix(ground, herb3, rand(gl_FragCoord.xy));\n ground = mix(ground, herb1, fbm(gl_FragCoord.xy * 16.0));\n\n gl_FragColor = vec4(ground, 1.0);\n}",
  11293. 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}",
  11294. 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}",
  11295. 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}",
  11296. 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}",
  11297. 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}",
  11298. 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}",
  11299. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth ;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\nvoid main()\n{\n\n vec3 brick = vec3(0.77, 0.47, 0.40);\n vec3 joint = vec3(0.72, 0.72, 0.72);\n\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n\n vec3 color = brick;\n\n\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(joint, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(joint, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n\n float amplitude = 9.0;\n\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n\n t = sin(t);\n color = marble_color(t);\n\n\n }\n\n gl_FragColor = vec4(color, 0.0);\n\n \n}",
  11300. 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}",
  11301. 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}",
  11302. 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}",
  11303. 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}",
  11304. 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}",
  11305. 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}",
  11306. 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}",
  11307. 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}",
  11308. 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}",
  11309. 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}",
  11310. rockPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nvec3 hash(vec3 x)\n{\n x = vec3(dot(x, vec3(127.1, 311.7, 74.7)),\n dot(x, vec3(269.5, 183.3, 246.1)),\n dot(x, vec3(113.5, 271.9, 124.6)));\n\n return fract(sin(x)*43758.5453123);\n}\n\n// returns closest, second closest, and cell id\nvec3 voronoi(in vec3 x)\n{\n vec3 p = floor(x);\n vec3 f = fract(x);\n\n float id = 0.0;\n vec2 res = vec2(100.0);\n for (int k = -1; k <= 1; k++)\n for (int j = -1; j <= 1; j++)\n for (int i = -1; i <= 1; i++)\n {\n vec3 b = vec3(float(i), float(j), float(k));\n vec3 r = vec3(b) - f + hash(p + b);\n float d = dot(r, r);\n\n if (d < res.x)\n {\n id = dot(p + b, vec3(1.0, 57.0, 113.0));\n res = vec2(d, res.x);\n }\n else if (d < res.y)\n {\n res.y = d;\n }\n }\n\n return vec3(sqrt(res), abs(id));\n}\n\nconst mat3 m = mat3(0.00, 0.80, 0.60,\n -0.80, 0.36, -0.48,\n -0.60, -0.48, 0.64);\n\nvoid main(void)\n{\n vec2 p = vUV;\n\n // camera movement \n float an = 0.5*0.1;\n vec3 ro = vec3(2.5*cos(an), 1.0, 2.5*sin(an));\n vec3 ta = vec3(0.0, 1.0, 0.0);\n // camera matrix\n vec3 ww = normalize(ta - ro);\n vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));\n vec3 vv = normalize(cross(uu, ww));\n // create view ray\n vec3 rd = normalize(p.x*uu + p.y*vv + 1.5*ww);\n\n // sphere center \n vec3 sc = vec3(0.0, 1.0, 0.0);\n\n // raytrace\n float tmin = 10000.0;\n vec3 nor = vec3(0.0);\n float occ = 1.0;\n vec3 pos = vec3(0.0);\n\n // raytrace-plane\n float h = (0.0 - ro.y) / rd.y;\n if (h>0.0)\n {\n tmin = h;\n nor = vec3(0.0, 1.0, 0.0);\n pos = ro + h*rd;\n vec3 di = sc - pos;\n float l = length(di);\n occ = 1.0 - dot(nor, di / l)*1.0*1.0 / (l*l);\n }\n\n // raytrace-sphere\n vec3 ce = ro - sc;\n float b = dot(rd, ce);\n float c = dot(ce, ce) - 1.0;\n h = b*b - c;\n if (h>0.0)\n {\n h = -b - sqrt(h);\n if (h<tmin)\n {\n tmin = h;\n nor = normalize(ro + h*rd - sc);\n occ = 0.5 + 0.5*nor.y;\n }\n }\n\n // shading/lighting \n vec3 col = vec3(0.9);\n if (tmin<100.0)\n {\n pos = ro + tmin*rd;\n\n float f = voronoi(4.0*pos).x;\n\n f *= occ;\n col = vec3(f*1.2);\n col = mix(col, vec3(0.9), 1.0 - exp(-0.003*tmin*tmin));\n }\n\n col = sqrt(col);\n\n\n gl_FragColor = vec4(col, 1.0);\n}",
  11311. 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}",
  11312. 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}",
  11313. 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}",
  11314. 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}",
  11315. 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}",
  11316. };
  11317. return Effect;
  11318. })();
  11319. BABYLON.Effect = Effect;
  11320. })(BABYLON || (BABYLON = {}));
  11321. var BABYLON;
  11322. (function (BABYLON) {
  11323. var Material = (function () {
  11324. function Material(name, scene, doNotAdd) {
  11325. this.name = name;
  11326. this.checkReadyOnEveryCall = true;
  11327. this.checkReadyOnlyOnce = false;
  11328. this.state = "";
  11329. this.alpha = 1.0;
  11330. this.backFaceCulling = true;
  11331. this._wasPreviouslyReady = false;
  11332. this._fillMode = Material.TriangleFillMode;
  11333. this.pointSize = 1.0;
  11334. this.id = name;
  11335. this._scene = scene;
  11336. if (!doNotAdd) {
  11337. scene.materials.push(this);
  11338. }
  11339. }
  11340. Object.defineProperty(Material, "TriangleFillMode", {
  11341. get: function () {
  11342. return Material._TriangleFillMode;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(Material, "WireFrameFillMode", {
  11348. get: function () {
  11349. return Material._WireFrameFillMode;
  11350. },
  11351. enumerable: true,
  11352. configurable: true
  11353. });
  11354. Object.defineProperty(Material, "PointFillMode", {
  11355. get: function () {
  11356. return Material._PointFillMode;
  11357. },
  11358. enumerable: true,
  11359. configurable: true
  11360. });
  11361. Object.defineProperty(Material.prototype, "wireframe", {
  11362. get: function () {
  11363. return this._fillMode === Material.WireFrameFillMode;
  11364. },
  11365. set: function (value) {
  11366. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11367. },
  11368. enumerable: true,
  11369. configurable: true
  11370. });
  11371. Object.defineProperty(Material.prototype, "pointsCloud", {
  11372. get: function () {
  11373. return this._fillMode === Material.PointFillMode;
  11374. },
  11375. set: function (value) {
  11376. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. Object.defineProperty(Material.prototype, "fillMode", {
  11382. get: function () {
  11383. return this._fillMode;
  11384. },
  11385. set: function (value) {
  11386. this._fillMode = value;
  11387. },
  11388. enumerable: true,
  11389. configurable: true
  11390. });
  11391. Material.prototype.isReady = function (mesh, useInstances) {
  11392. return true;
  11393. };
  11394. Material.prototype.getEffect = function () {
  11395. return this._effect;
  11396. };
  11397. Material.prototype.getScene = function () {
  11398. return this._scene;
  11399. };
  11400. Material.prototype.needAlphaBlending = function () {
  11401. return (this.alpha < 1.0);
  11402. };
  11403. Material.prototype.needAlphaTesting = function () {
  11404. return false;
  11405. };
  11406. Material.prototype.getAlphaTestTexture = function () {
  11407. return null;
  11408. };
  11409. Material.prototype.trackCreation = function (onCompiled, onError) {
  11410. };
  11411. Material.prototype._preBind = function () {
  11412. var engine = this._scene.getEngine();
  11413. engine.enableEffect(this._effect);
  11414. engine.setState(this.backFaceCulling);
  11415. };
  11416. Material.prototype.bind = function (world, mesh) {
  11417. };
  11418. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11419. };
  11420. Material.prototype.unbind = function () {
  11421. };
  11422. Material.prototype.dispose = function (forceDisposeEffect) {
  11423. var index = this._scene.materials.indexOf(this);
  11424. this._scene.materials.splice(index, 1);
  11425. if (forceDisposeEffect && this._effect) {
  11426. this._scene.getEngine()._releaseEffect(this._effect);
  11427. this._effect = null;
  11428. }
  11429. if (this.onDispose) {
  11430. this.onDispose();
  11431. }
  11432. };
  11433. Material._TriangleFillMode = 0;
  11434. Material._WireFrameFillMode = 1;
  11435. Material._PointFillMode = 2;
  11436. return Material;
  11437. })();
  11438. BABYLON.Material = Material;
  11439. })(BABYLON || (BABYLON = {}));
  11440. var __extends = this.__extends || function (d, b) {
  11441. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11442. function __() { this.constructor = d; }
  11443. __.prototype = b.prototype;
  11444. d.prototype = new __();
  11445. };
  11446. var BABYLON;
  11447. (function (BABYLON) {
  11448. var maxSimultaneousLights = 4;
  11449. var FresnelParameters = (function () {
  11450. function FresnelParameters() {
  11451. this.isEnabled = true;
  11452. this.leftColor = BABYLON.Color3.White();
  11453. this.rightColor = BABYLON.Color3.Black();
  11454. this.bias = 0;
  11455. this.power = 1;
  11456. }
  11457. return FresnelParameters;
  11458. })();
  11459. BABYLON.FresnelParameters = FresnelParameters;
  11460. var StandardMaterial = (function (_super) {
  11461. __extends(StandardMaterial, _super);
  11462. function StandardMaterial(name, scene) {
  11463. var _this = this;
  11464. _super.call(this, name, scene);
  11465. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11466. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11467. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11468. this.specularPower = 64;
  11469. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11470. this.useAlphaFromDiffuseTexture = false;
  11471. this.useSpecularOverAlpha = true;
  11472. this.fogEnabled = true;
  11473. this._cachedDefines = null;
  11474. this._renderTargets = new BABYLON.SmartArray(16);
  11475. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11476. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11477. this._scaledDiffuse = new BABYLON.Color3();
  11478. this._scaledSpecular = new BABYLON.Color3();
  11479. this.getRenderTargetTextures = function () {
  11480. _this._renderTargets.reset();
  11481. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11482. _this._renderTargets.push(_this.reflectionTexture);
  11483. }
  11484. return _this._renderTargets;
  11485. };
  11486. }
  11487. StandardMaterial.prototype.needAlphaBlending = function () {
  11488. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11489. };
  11490. StandardMaterial.prototype.needAlphaTesting = function () {
  11491. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11492. };
  11493. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11494. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11495. };
  11496. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11497. return this.diffuseTexture;
  11498. };
  11499. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11500. if (this.checkReadyOnlyOnce) {
  11501. if (this._wasPreviouslyReady) {
  11502. return true;
  11503. }
  11504. }
  11505. var scene = this.getScene();
  11506. if (!this.checkReadyOnEveryCall) {
  11507. if (this._renderId === scene.getRenderId()) {
  11508. return true;
  11509. }
  11510. }
  11511. var engine = scene.getEngine();
  11512. var defines = [];
  11513. var fallbacks = new BABYLON.EffectFallbacks();
  11514. if (scene.texturesEnabled) {
  11515. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11516. if (!this.diffuseTexture.isReady()) {
  11517. return false;
  11518. } else {
  11519. defines.push("#define DIFFUSE");
  11520. }
  11521. }
  11522. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11523. if (!this.ambientTexture.isReady()) {
  11524. return false;
  11525. } else {
  11526. defines.push("#define AMBIENT");
  11527. }
  11528. }
  11529. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11530. if (!this.opacityTexture.isReady()) {
  11531. return false;
  11532. } else {
  11533. defines.push("#define OPACITY");
  11534. if (this.opacityTexture.getAlphaFromRGB) {
  11535. defines.push("#define OPACITYRGB");
  11536. }
  11537. }
  11538. }
  11539. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11540. if (!this.reflectionTexture.isReady()) {
  11541. return false;
  11542. } else {
  11543. defines.push("#define REFLECTION");
  11544. fallbacks.addFallback(0, "REFLECTION");
  11545. }
  11546. }
  11547. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11548. if (!this.emissiveTexture.isReady()) {
  11549. return false;
  11550. } else {
  11551. defines.push("#define EMISSIVE");
  11552. }
  11553. }
  11554. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11555. if (!this.specularTexture.isReady()) {
  11556. return false;
  11557. } else {
  11558. defines.push("#define SPECULAR");
  11559. fallbacks.addFallback(0, "SPECULAR");
  11560. }
  11561. }
  11562. }
  11563. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11564. if (!this.bumpTexture.isReady()) {
  11565. return false;
  11566. } else {
  11567. defines.push("#define BUMP");
  11568. fallbacks.addFallback(0, "BUMP");
  11569. }
  11570. }
  11571. if (this.useSpecularOverAlpha) {
  11572. defines.push("#define SPECULAROVERALPHA");
  11573. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11574. }
  11575. if (scene.clipPlane) {
  11576. defines.push("#define CLIPPLANE");
  11577. }
  11578. if (engine.getAlphaTesting()) {
  11579. defines.push("#define ALPHATEST");
  11580. }
  11581. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11582. defines.push("#define ALPHAFROMDIFFUSE");
  11583. }
  11584. if (this.pointsCloud) {
  11585. defines.push("#define POINTSIZE");
  11586. }
  11587. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11588. defines.push("#define FOG");
  11589. fallbacks.addFallback(1, "FOG");
  11590. }
  11591. var shadowsActivated = false;
  11592. var lightIndex = 0;
  11593. if (scene.lightsEnabled) {
  11594. for (var index = 0; index < scene.lights.length; index++) {
  11595. var light = scene.lights[index];
  11596. if (!light.isEnabled()) {
  11597. continue;
  11598. }
  11599. if (light._excludedMeshesIds.length > 0) {
  11600. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11601. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11602. if (excludedMesh) {
  11603. light.excludedMeshes.push(excludedMesh);
  11604. }
  11605. }
  11606. light._excludedMeshesIds = [];
  11607. }
  11608. if (light._includedOnlyMeshesIds.length > 0) {
  11609. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11610. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11611. if (includedOnlyMesh) {
  11612. light.includedOnlyMeshes.push(includedOnlyMesh);
  11613. }
  11614. }
  11615. light._includedOnlyMeshesIds = [];
  11616. }
  11617. if (!light.canAffectMesh(mesh)) {
  11618. continue;
  11619. }
  11620. defines.push("#define LIGHT" + lightIndex);
  11621. if (lightIndex > 0) {
  11622. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11623. }
  11624. var type;
  11625. if (light instanceof BABYLON.SpotLight) {
  11626. type = "#define SPOTLIGHT" + lightIndex;
  11627. } else if (light instanceof BABYLON.HemisphericLight) {
  11628. type = "#define HEMILIGHT" + lightIndex;
  11629. } else {
  11630. type = "#define POINTDIRLIGHT" + lightIndex;
  11631. }
  11632. defines.push(type);
  11633. if (lightIndex > 0) {
  11634. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11635. }
  11636. if (scene.shadowsEnabled) {
  11637. var shadowGenerator = light.getShadowGenerator();
  11638. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11639. defines.push("#define SHADOW" + lightIndex);
  11640. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11641. if (!shadowsActivated) {
  11642. defines.push("#define SHADOWS");
  11643. shadowsActivated = true;
  11644. }
  11645. if (shadowGenerator.useVarianceShadowMap) {
  11646. defines.push("#define SHADOWVSM" + lightIndex);
  11647. if (lightIndex > 0) {
  11648. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11649. }
  11650. }
  11651. if (shadowGenerator.usePoissonSampling) {
  11652. defines.push("#define SHADOWPCF" + lightIndex);
  11653. if (lightIndex > 0) {
  11654. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11655. }
  11656. }
  11657. }
  11658. }
  11659. lightIndex++;
  11660. if (lightIndex == maxSimultaneousLights)
  11661. break;
  11662. }
  11663. }
  11664. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11665. var fresnelRank = 1;
  11666. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11667. defines.push("#define DIFFUSEFRESNEL");
  11668. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11669. fresnelRank++;
  11670. }
  11671. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11672. defines.push("#define OPACITYFRESNEL");
  11673. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11674. fresnelRank++;
  11675. }
  11676. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11677. defines.push("#define REFLECTIONFRESNEL");
  11678. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11679. fresnelRank++;
  11680. }
  11681. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11682. defines.push("#define EMISSIVEFRESNEL");
  11683. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11684. fresnelRank++;
  11685. }
  11686. defines.push("#define FRESNEL");
  11687. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  11688. }
  11689. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  11690. if (mesh) {
  11691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11692. attribs.push(BABYLON.VertexBuffer.UVKind);
  11693. defines.push("#define UV1");
  11694. }
  11695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11696. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11697. defines.push("#define UV2");
  11698. }
  11699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  11700. attribs.push(BABYLON.VertexBuffer.ColorKind);
  11701. defines.push("#define VERTEXCOLOR");
  11702. }
  11703. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11706. defines.push("#define BONES");
  11707. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11708. defines.push("#define BONES4");
  11709. fallbacks.addFallback(0, "BONES4");
  11710. }
  11711. if (useInstances) {
  11712. defines.push("#define INSTANCES");
  11713. attribs.push("world0");
  11714. attribs.push("world1");
  11715. attribs.push("world2");
  11716. attribs.push("world3");
  11717. }
  11718. }
  11719. var join = defines.join("\n");
  11720. if (this._cachedDefines != join) {
  11721. this._cachedDefines = join;
  11722. var shaderName = "default";
  11723. if (!scene.getEngine().getCaps().standardDerivatives) {
  11724. shaderName = "legacydefault";
  11725. }
  11726. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  11727. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  11728. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  11729. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  11730. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  11731. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  11732. "vFogInfos", "vFogColor", "pointSize",
  11733. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  11734. "mBones",
  11735. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  11736. "darkness0", "darkness1", "darkness2", "darkness3",
  11737. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  11738. ], [
  11739. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  11740. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  11741. ], join, fallbacks, this.onCompiled, this.onError);
  11742. }
  11743. if (!this._effect.isReady()) {
  11744. return false;
  11745. }
  11746. this._renderId = scene.getRenderId();
  11747. this._wasPreviouslyReady = true;
  11748. return true;
  11749. };
  11750. StandardMaterial.prototype.unbind = function () {
  11751. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  11752. this._effect.setTexture("reflection2DSampler", null);
  11753. }
  11754. };
  11755. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  11756. this._effect.setMatrix("world", world);
  11757. };
  11758. StandardMaterial.prototype.bind = function (world, mesh) {
  11759. var scene = this.getScene();
  11760. this.bindOnlyWorldMatrix(world);
  11761. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  11762. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  11763. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  11764. }
  11765. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11766. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  11767. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  11768. }
  11769. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11770. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  11771. }
  11772. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11773. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  11774. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  11775. }
  11776. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11777. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  11778. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  11779. }
  11780. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11781. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  11782. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  11783. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  11784. }
  11785. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11786. this._effect.setTexture("ambientSampler", this.ambientTexture);
  11787. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  11788. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  11789. }
  11790. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11791. this._effect.setTexture("opacitySampler", this.opacityTexture);
  11792. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  11793. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  11794. }
  11795. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11796. if (this.reflectionTexture.isCube) {
  11797. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  11798. } else {
  11799. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  11800. }
  11801. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  11802. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  11803. }
  11804. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11805. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  11806. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  11807. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  11808. }
  11809. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11810. this._effect.setTexture("specularSampler", this.specularTexture);
  11811. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  11812. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  11813. }
  11814. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11815. this._effect.setTexture("bumpSampler", this.bumpTexture);
  11816. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, this.bumpTexture.level);
  11817. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  11818. }
  11819. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  11820. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  11821. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  11822. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  11823. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  11824. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  11825. if (scene.lightsEnabled) {
  11826. var lightIndex = 0;
  11827. for (var index = 0; index < scene.lights.length; index++) {
  11828. var light = scene.lights[index];
  11829. if (!light.isEnabled()) {
  11830. continue;
  11831. }
  11832. if (!light.canAffectMesh(mesh)) {
  11833. continue;
  11834. }
  11835. if (light instanceof BABYLON.PointLight) {
  11836. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11837. } else if (light instanceof BABYLON.DirectionalLight) {
  11838. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  11839. } else if (light instanceof BABYLON.SpotLight) {
  11840. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  11841. } else if (light instanceof BABYLON.HemisphericLight) {
  11842. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  11843. }
  11844. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  11845. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  11846. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  11847. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  11848. if (scene.shadowsEnabled) {
  11849. var shadowGenerator = light.getShadowGenerator();
  11850. if (mesh.receiveShadows && shadowGenerator) {
  11851. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  11852. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  11853. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  11854. }
  11855. }
  11856. lightIndex++;
  11857. if (lightIndex == maxSimultaneousLights)
  11858. break;
  11859. }
  11860. }
  11861. if (scene.clipPlane) {
  11862. var clipPlane = scene.clipPlane;
  11863. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  11864. }
  11865. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  11866. this._effect.setMatrix("view", scene.getViewMatrix());
  11867. }
  11868. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  11869. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  11870. this._effect.setColor3("vFogColor", scene.fogColor);
  11871. }
  11872. if (this.pointsCloud) {
  11873. this._effect.setFloat("pointSize", this.pointSize);
  11874. }
  11875. };
  11876. StandardMaterial.prototype.getAnimatables = function () {
  11877. var results = [];
  11878. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  11879. results.push(this.diffuseTexture);
  11880. }
  11881. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  11882. results.push(this.ambientTexture);
  11883. }
  11884. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  11885. results.push(this.opacityTexture);
  11886. }
  11887. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  11888. results.push(this.reflectionTexture);
  11889. }
  11890. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  11891. results.push(this.emissiveTexture);
  11892. }
  11893. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  11894. results.push(this.specularTexture);
  11895. }
  11896. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  11897. results.push(this.bumpTexture);
  11898. }
  11899. return results;
  11900. };
  11901. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  11902. if (this.diffuseTexture) {
  11903. this.diffuseTexture.dispose();
  11904. }
  11905. if (this.ambientTexture) {
  11906. this.ambientTexture.dispose();
  11907. }
  11908. if (this.opacityTexture) {
  11909. this.opacityTexture.dispose();
  11910. }
  11911. if (this.reflectionTexture) {
  11912. this.reflectionTexture.dispose();
  11913. }
  11914. if (this.emissiveTexture) {
  11915. this.emissiveTexture.dispose();
  11916. }
  11917. if (this.specularTexture) {
  11918. this.specularTexture.dispose();
  11919. }
  11920. if (this.bumpTexture) {
  11921. this.bumpTexture.dispose();
  11922. }
  11923. _super.prototype.dispose.call(this, forceDisposeEffect);
  11924. };
  11925. StandardMaterial.prototype.clone = function (name) {
  11926. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  11927. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  11928. newStandardMaterial.alpha = this.alpha;
  11929. newStandardMaterial.fillMode = this.fillMode;
  11930. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  11931. if (this.diffuseTexture && this.diffuseTexture.clone) {
  11932. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  11933. }
  11934. if (this.ambientTexture && this.ambientTexture.clone) {
  11935. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  11936. }
  11937. if (this.opacityTexture && this.opacityTexture.clone) {
  11938. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  11939. }
  11940. if (this.reflectionTexture && this.reflectionTexture.clone) {
  11941. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  11942. }
  11943. if (this.emissiveTexture && this.emissiveTexture.clone) {
  11944. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  11945. }
  11946. if (this.specularTexture && this.specularTexture.clone) {
  11947. newStandardMaterial.specularTexture = this.specularTexture.clone();
  11948. }
  11949. if (this.bumpTexture && this.bumpTexture.clone) {
  11950. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  11951. }
  11952. newStandardMaterial.ambientColor = this.ambientColor.clone();
  11953. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  11954. newStandardMaterial.specularColor = this.specularColor.clone();
  11955. newStandardMaterial.specularPower = this.specularPower;
  11956. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  11957. return newStandardMaterial;
  11958. };
  11959. StandardMaterial.DiffuseTextureEnabled = true;
  11960. StandardMaterial.AmbientTextureEnabled = true;
  11961. StandardMaterial.OpacityTextureEnabled = true;
  11962. StandardMaterial.ReflectionTextureEnabled = true;
  11963. StandardMaterial.EmissiveTextureEnabled = true;
  11964. StandardMaterial.SpecularTextureEnabled = true;
  11965. StandardMaterial.BumpTextureEnabled = true;
  11966. return StandardMaterial;
  11967. })(BABYLON.Material);
  11968. BABYLON.StandardMaterial = StandardMaterial;
  11969. })(BABYLON || (BABYLON = {}));
  11970. var __extends = this.__extends || function (d, b) {
  11971. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11972. function __() { this.constructor = d; }
  11973. __.prototype = b.prototype;
  11974. d.prototype = new __();
  11975. };
  11976. var BABYLON;
  11977. (function (BABYLON) {
  11978. var MultiMaterial = (function (_super) {
  11979. __extends(MultiMaterial, _super);
  11980. function MultiMaterial(name, scene) {
  11981. _super.call(this, name, scene, true);
  11982. this.subMaterials = new Array();
  11983. scene.multiMaterials.push(this);
  11984. }
  11985. MultiMaterial.prototype.getSubMaterial = function (index) {
  11986. if (index < 0 || index >= this.subMaterials.length) {
  11987. return this.getScene().defaultMaterial;
  11988. }
  11989. return this.subMaterials[index];
  11990. };
  11991. MultiMaterial.prototype.isReady = function (mesh) {
  11992. for (var index = 0; index < this.subMaterials.length; index++) {
  11993. var subMaterial = this.subMaterials[index];
  11994. if (subMaterial) {
  11995. if (!this.subMaterials[index].isReady(mesh)) {
  11996. return false;
  11997. }
  11998. }
  11999. }
  12000. return true;
  12001. };
  12002. return MultiMaterial;
  12003. })(BABYLON.Material);
  12004. BABYLON.MultiMaterial = MultiMaterial;
  12005. })(BABYLON || (BABYLON = {}));
  12006. var BABYLON;
  12007. (function (BABYLON) {
  12008. var Database = (function () {
  12009. function Database(urlToScene, callbackManifestChecked) {
  12010. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  12011. this.callbackManifestChecked = callbackManifestChecked;
  12012. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  12013. this.db = null;
  12014. this.enableSceneOffline = false;
  12015. this.enableTexturesOffline = false;
  12016. this.manifestVersionFound = 0;
  12017. this.mustUpdateRessources = false;
  12018. this.hasReachedQuota = false;
  12019. this.checkManifestFile();
  12020. }
  12021. Database.prototype.checkManifestFile = function () {
  12022. var _this = this;
  12023. function noManifestFile() {
  12024. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  12025. that.enableSceneOffline = false;
  12026. that.enableTexturesOffline = false;
  12027. that.callbackManifestChecked(false);
  12028. }
  12029. var that = this;
  12030. var manifestURL = this.currentSceneUrl + ".manifest";
  12031. var xhr = new XMLHttpRequest();
  12032. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  12033. xhr.open("GET", manifestURLTimeStamped, true);
  12034. xhr.addEventListener("load", function () {
  12035. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12036. try {
  12037. var manifestFile = JSON.parse(xhr.response);
  12038. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  12039. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  12040. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  12041. _this.manifestVersionFound = manifestFile.version;
  12042. }
  12043. if (_this.callbackManifestChecked) {
  12044. _this.callbackManifestChecked(true);
  12045. }
  12046. } catch (ex) {
  12047. noManifestFile();
  12048. }
  12049. } else {
  12050. noManifestFile();
  12051. }
  12052. }, false);
  12053. xhr.addEventListener("error", function (event) {
  12054. noManifestFile();
  12055. }, false);
  12056. try {
  12057. xhr.send();
  12058. } catch (ex) {
  12059. BABYLON.Tools.Error("Error on XHR send request.");
  12060. that.callbackManifestChecked(false);
  12061. }
  12062. };
  12063. Database.prototype.openAsync = function (successCallback, errorCallback) {
  12064. var _this = this;
  12065. function handleError() {
  12066. that.isSupported = false;
  12067. if (errorCallback)
  12068. errorCallback();
  12069. }
  12070. var that = this;
  12071. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  12072. this.isSupported = false;
  12073. if (errorCallback)
  12074. errorCallback();
  12075. } else {
  12076. if (!this.db) {
  12077. this.hasReachedQuota = false;
  12078. this.isSupported = true;
  12079. var request = this.idbFactory.open("babylonjs", 1);
  12080. request.onerror = function (event) {
  12081. handleError();
  12082. };
  12083. request.onblocked = function (event) {
  12084. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  12085. handleError();
  12086. };
  12087. request.onsuccess = function (event) {
  12088. _this.db = request.result;
  12089. successCallback();
  12090. };
  12091. request.onupgradeneeded = function (event) {
  12092. _this.db = (event.target).result;
  12093. try {
  12094. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  12095. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  12096. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  12097. } catch (ex) {
  12098. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  12099. handleError();
  12100. }
  12101. };
  12102. } else {
  12103. if (successCallback)
  12104. successCallback();
  12105. }
  12106. }
  12107. };
  12108. Database.prototype.loadImageFromDB = function (url, image) {
  12109. var _this = this;
  12110. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  12111. var saveAndLoadImage = function () {
  12112. if (!_this.hasReachedQuota && _this.db !== null) {
  12113. _this._saveImageIntoDBAsync(completeURL, image);
  12114. } else {
  12115. image.src = url;
  12116. }
  12117. };
  12118. if (!this.mustUpdateRessources) {
  12119. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  12120. } else {
  12121. saveAndLoadImage();
  12122. }
  12123. };
  12124. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  12125. if (this.isSupported && this.db !== null) {
  12126. var texture;
  12127. var transaction = this.db.transaction(["textures"]);
  12128. transaction.onabort = function (event) {
  12129. image.src = url;
  12130. };
  12131. transaction.oncomplete = function (event) {
  12132. var blobTextureURL;
  12133. if (texture) {
  12134. var URL = window.URL || window.webkitURL;
  12135. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  12136. image.onerror = function () {
  12137. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  12138. image.src = url;
  12139. };
  12140. image.src = blobTextureURL;
  12141. } else {
  12142. notInDBCallback();
  12143. }
  12144. };
  12145. var getRequest = transaction.objectStore("textures").get(url);
  12146. getRequest.onsuccess = function (event) {
  12147. texture = (event.target).result;
  12148. };
  12149. getRequest.onerror = function (event) {
  12150. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  12151. image.src = url;
  12152. };
  12153. } else {
  12154. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12155. image.src = url;
  12156. }
  12157. };
  12158. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  12159. var _this = this;
  12160. if (this.isSupported) {
  12161. var generateBlobUrl = function () {
  12162. var blobTextureURL;
  12163. if (blob) {
  12164. var URL = window.URL || window.webkitURL;
  12165. try {
  12166. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  12167. } catch (ex) {
  12168. blobTextureURL = URL.createObjectURL(blob);
  12169. }
  12170. }
  12171. image.src = blobTextureURL;
  12172. };
  12173. if (BABYLON.Database.isUASupportingBlobStorage) {
  12174. var xhr = new XMLHttpRequest(), blob;
  12175. xhr.open("GET", url, true);
  12176. xhr.responseType = "blob";
  12177. xhr.addEventListener("load", function () {
  12178. if (xhr.status === 200) {
  12179. blob = xhr.response;
  12180. var transaction = _this.db.transaction(["textures"], "readwrite");
  12181. transaction.onabort = function (event) {
  12182. try {
  12183. if (event.srcElement.error.name === "QuotaExceededError") {
  12184. this.hasReachedQuota = true;
  12185. }
  12186. } catch (ex) {
  12187. }
  12188. generateBlobUrl();
  12189. };
  12190. transaction.oncomplete = function (event) {
  12191. generateBlobUrl();
  12192. };
  12193. var newTexture = { textureUrl: url, data: blob };
  12194. try {
  12195. var addRequest = transaction.objectStore("textures").put(newTexture);
  12196. addRequest.onsuccess = function (event) {
  12197. };
  12198. addRequest.onerror = function (event) {
  12199. generateBlobUrl();
  12200. };
  12201. } catch (ex) {
  12202. if (ex.code === 25) {
  12203. BABYLON.Database.isUASupportingBlobStorage = false;
  12204. }
  12205. image.src = url;
  12206. }
  12207. } else {
  12208. image.src = url;
  12209. }
  12210. }, false);
  12211. xhr.addEventListener("error", function (event) {
  12212. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  12213. image.src = url;
  12214. }, false);
  12215. xhr.send();
  12216. } else {
  12217. image.src = url;
  12218. }
  12219. } else {
  12220. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12221. image.src = url;
  12222. }
  12223. };
  12224. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  12225. var _this = this;
  12226. var updateVersion = function (event) {
  12227. _this._saveVersionIntoDBAsync(url, versionLoaded);
  12228. };
  12229. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  12230. };
  12231. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  12232. var _this = this;
  12233. if (this.isSupported) {
  12234. var version;
  12235. try {
  12236. var transaction = this.db.transaction(["versions"]);
  12237. transaction.oncomplete = function (event) {
  12238. if (version) {
  12239. if (_this.manifestVersionFound > version.data) {
  12240. _this.mustUpdateRessources = true;
  12241. updateInDBCallback();
  12242. } else {
  12243. callback(version.data);
  12244. }
  12245. } else {
  12246. _this.mustUpdateRessources = true;
  12247. updateInDBCallback();
  12248. }
  12249. };
  12250. transaction.onabort = function (event) {
  12251. callback(-1);
  12252. };
  12253. var getRequest = transaction.objectStore("versions").get(url);
  12254. getRequest.onsuccess = function (event) {
  12255. version = (event.target).result;
  12256. };
  12257. getRequest.onerror = function (event) {
  12258. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  12259. callback(-1);
  12260. };
  12261. } catch (ex) {
  12262. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  12263. callback(-1);
  12264. }
  12265. } else {
  12266. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12267. callback(-1);
  12268. }
  12269. };
  12270. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  12271. var _this = this;
  12272. if (this.isSupported && !this.hasReachedQuota) {
  12273. try {
  12274. var transaction = this.db.transaction(["versions"], "readwrite");
  12275. transaction.onabort = function (event) {
  12276. try {
  12277. if (event.srcElement.error.name === "QuotaExceededError") {
  12278. _this.hasReachedQuota = true;
  12279. }
  12280. } catch (ex) {
  12281. }
  12282. callback(-1);
  12283. };
  12284. transaction.oncomplete = function (event) {
  12285. callback(_this.manifestVersionFound);
  12286. };
  12287. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  12288. var addRequest = transaction.objectStore("versions").put(newVersion);
  12289. addRequest.onsuccess = function (event) {
  12290. };
  12291. addRequest.onerror = function (event) {
  12292. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  12293. };
  12294. } catch (ex) {
  12295. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  12296. callback(-1);
  12297. }
  12298. } else {
  12299. callback(-1);
  12300. }
  12301. };
  12302. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12303. var _this = this;
  12304. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12305. var saveAndLoadFile = function (event) {
  12306. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12307. };
  12308. this._checkVersionFromDB(completeUrl, function (version) {
  12309. if (version !== -1) {
  12310. if (!_this.mustUpdateRessources) {
  12311. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12312. } else {
  12313. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12314. }
  12315. } else {
  12316. errorCallback();
  12317. }
  12318. });
  12319. };
  12320. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12321. if (this.isSupported) {
  12322. var targetStore;
  12323. if (url.indexOf(".babylon") !== -1) {
  12324. targetStore = "scenes";
  12325. } else {
  12326. targetStore = "textures";
  12327. }
  12328. var file;
  12329. var transaction = this.db.transaction([targetStore]);
  12330. transaction.oncomplete = function (event) {
  12331. if (file) {
  12332. callback(file.data);
  12333. } else {
  12334. notInDBCallback();
  12335. }
  12336. };
  12337. transaction.onabort = function (event) {
  12338. notInDBCallback();
  12339. };
  12340. var getRequest = transaction.objectStore(targetStore).get(url);
  12341. getRequest.onsuccess = function (event) {
  12342. file = (event.target).result;
  12343. };
  12344. getRequest.onerror = function (event) {
  12345. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12346. notInDBCallback();
  12347. };
  12348. } else {
  12349. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12350. callback();
  12351. }
  12352. };
  12353. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12354. var _this = this;
  12355. if (this.isSupported) {
  12356. var targetStore;
  12357. if (url.indexOf(".babylon") !== -1) {
  12358. targetStore = "scenes";
  12359. } else {
  12360. targetStore = "textures";
  12361. }
  12362. var xhr = new XMLHttpRequest(), fileData;
  12363. xhr.open("GET", url, true);
  12364. if (useArrayBuffer) {
  12365. xhr.responseType = "arraybuffer";
  12366. }
  12367. xhr.onprogress = progressCallback;
  12368. xhr.addEventListener("load", function () {
  12369. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12370. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12371. if (!_this.hasReachedQuota) {
  12372. var transaction = _this.db.transaction([targetStore], "readwrite");
  12373. transaction.onabort = function (event) {
  12374. try {
  12375. if (event.srcElement.error.name === "QuotaExceededError") {
  12376. this.hasReachedQuota = true;
  12377. }
  12378. } catch (ex) {
  12379. }
  12380. callback(fileData);
  12381. };
  12382. transaction.oncomplete = function (event) {
  12383. callback(fileData);
  12384. };
  12385. var newFile;
  12386. if (targetStore === "scenes") {
  12387. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12388. } else {
  12389. newFile = { textureUrl: url, data: fileData };
  12390. }
  12391. try {
  12392. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12393. addRequest.onsuccess = function (event) {
  12394. };
  12395. addRequest.onerror = function (event) {
  12396. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12397. };
  12398. } catch (ex) {
  12399. callback(fileData);
  12400. }
  12401. } else {
  12402. callback(fileData);
  12403. }
  12404. } else {
  12405. callback();
  12406. }
  12407. }, false);
  12408. xhr.addEventListener("error", function (event) {
  12409. BABYLON.Tools.Error("error on XHR request.");
  12410. callback();
  12411. }, false);
  12412. xhr.send();
  12413. } else {
  12414. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12415. callback();
  12416. }
  12417. };
  12418. Database.isUASupportingBlobStorage = true;
  12419. Database.parseURL = function (url) {
  12420. var a = document.createElement('a');
  12421. a.href = url;
  12422. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12423. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12424. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12425. return absLocation;
  12426. };
  12427. Database.ReturnFullUrlLocation = function (url) {
  12428. if (url.indexOf("http:/") === -1) {
  12429. return (BABYLON.Database.parseURL(window.location.href) + url);
  12430. } else {
  12431. return url;
  12432. }
  12433. };
  12434. return Database;
  12435. })();
  12436. BABYLON.Database = Database;
  12437. })(BABYLON || (BABYLON = {}));
  12438. var BABYLON;
  12439. (function (BABYLON) {
  12440. var SpriteManager = (function () {
  12441. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12442. this.name = name;
  12443. this.cellSize = cellSize;
  12444. this.sprites = new Array();
  12445. this.renderingGroupId = 0;
  12446. this.fogEnabled = true;
  12447. this._vertexDeclaration = [3, 4, 4, 4];
  12448. this._vertexStrideSize = 15 * 4;
  12449. this._capacity = capacity;
  12450. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12451. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12452. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12453. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12454. this._scene = scene;
  12455. this._scene.spriteManagers.push(this);
  12456. this._vertexDeclaration = [3, 4, 4, 4];
  12457. this._vertexStrideSize = 15 * 4;
  12458. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12459. var indices = [];
  12460. var index = 0;
  12461. for (var count = 0; count < capacity; count++) {
  12462. indices.push(index);
  12463. indices.push(index + 1);
  12464. indices.push(index + 2);
  12465. indices.push(index);
  12466. indices.push(index + 2);
  12467. indices.push(index + 3);
  12468. index += 4;
  12469. }
  12470. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12471. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12472. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12473. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12474. }
  12475. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12476. var arrayOffset = index * 15;
  12477. if (offsetX == 0)
  12478. offsetX = this._epsilon;
  12479. else if (offsetX == 1)
  12480. offsetX = 1 - this._epsilon;
  12481. if (offsetY == 0)
  12482. offsetY = this._epsilon;
  12483. else if (offsetY == 1)
  12484. offsetY = 1 - this._epsilon;
  12485. this._vertices[arrayOffset] = sprite.position.x;
  12486. this._vertices[arrayOffset + 1] = sprite.position.y;
  12487. this._vertices[arrayOffset + 2] = sprite.position.z;
  12488. this._vertices[arrayOffset + 3] = sprite.angle;
  12489. this._vertices[arrayOffset + 4] = sprite.size;
  12490. this._vertices[arrayOffset + 5] = offsetX;
  12491. this._vertices[arrayOffset + 6] = offsetY;
  12492. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12493. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12494. var offset = (sprite.cellIndex / rowSize) >> 0;
  12495. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12496. this._vertices[arrayOffset + 10] = offset;
  12497. this._vertices[arrayOffset + 11] = sprite.color.r;
  12498. this._vertices[arrayOffset + 12] = sprite.color.g;
  12499. this._vertices[arrayOffset + 13] = sprite.color.b;
  12500. this._vertices[arrayOffset + 14] = sprite.color.a;
  12501. };
  12502. SpriteManager.prototype.render = function () {
  12503. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12504. return;
  12505. var engine = this._scene.getEngine();
  12506. var baseSize = this._spriteTexture.getBaseSize();
  12507. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12508. var max = Math.min(this._capacity, this.sprites.length);
  12509. var rowSize = baseSize.width / this.cellSize;
  12510. var offset = 0;
  12511. for (var index = 0; index < max; index++) {
  12512. var sprite = this.sprites[index];
  12513. if (!sprite) {
  12514. continue;
  12515. }
  12516. sprite._animate(deltaTime);
  12517. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12518. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12519. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12520. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12521. }
  12522. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12523. var effect = this._effectBase;
  12524. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12525. effect = this._effectFog;
  12526. }
  12527. engine.enableEffect(effect);
  12528. var viewMatrix = this._scene.getViewMatrix();
  12529. effect.setTexture("diffuseSampler", this._spriteTexture);
  12530. effect.setMatrix("view", viewMatrix);
  12531. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12532. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12533. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12534. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12535. effect.setColor3("vFogColor", this._scene.fogColor);
  12536. }
  12537. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12538. effect.setBool("alphaTest", true);
  12539. engine.setColorWrite(false);
  12540. engine.draw(true, 0, max * 6);
  12541. engine.setColorWrite(true);
  12542. effect.setBool("alphaTest", false);
  12543. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12544. engine.draw(true, 0, max * 6);
  12545. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12546. };
  12547. SpriteManager.prototype.dispose = function () {
  12548. if (this._vertexBuffer) {
  12549. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12550. this._vertexBuffer = null;
  12551. }
  12552. if (this._indexBuffer) {
  12553. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12554. this._indexBuffer = null;
  12555. }
  12556. if (this._spriteTexture) {
  12557. this._spriteTexture.dispose();
  12558. this._spriteTexture = null;
  12559. }
  12560. var index = this._scene.spriteManagers.indexOf(this);
  12561. this._scene.spriteManagers.splice(index, 1);
  12562. if (this.onDispose) {
  12563. this.onDispose();
  12564. }
  12565. };
  12566. return SpriteManager;
  12567. })();
  12568. BABYLON.SpriteManager = SpriteManager;
  12569. })(BABYLON || (BABYLON = {}));
  12570. var BABYLON;
  12571. (function (BABYLON) {
  12572. var Sprite = (function () {
  12573. function Sprite(name, manager) {
  12574. this.name = name;
  12575. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12576. this.size = 1.0;
  12577. this.angle = 0;
  12578. this.cellIndex = 0;
  12579. this.invertU = 0;
  12580. this.invertV = 0;
  12581. this.animations = new Array();
  12582. this._animationStarted = false;
  12583. this._loopAnimation = false;
  12584. this._fromIndex = 0;
  12585. this._toIndex = 0;
  12586. this._delay = 0;
  12587. this._direction = 1;
  12588. this._frameCount = 0;
  12589. this._time = 0;
  12590. this._manager = manager;
  12591. this._manager.sprites.push(this);
  12592. this.position = BABYLON.Vector3.Zero();
  12593. }
  12594. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12595. this._fromIndex = from;
  12596. this._toIndex = to;
  12597. this._loopAnimation = loop;
  12598. this._delay = delay;
  12599. this._animationStarted = true;
  12600. this._direction = from < to ? 1 : -1;
  12601. this.cellIndex = from;
  12602. this._time = 0;
  12603. };
  12604. Sprite.prototype.stopAnimation = function () {
  12605. this._animationStarted = false;
  12606. };
  12607. Sprite.prototype._animate = function (deltaTime) {
  12608. if (!this._animationStarted)
  12609. return;
  12610. this._time += deltaTime;
  12611. if (this._time > this._delay) {
  12612. this._time = this._time % this._delay;
  12613. this.cellIndex += this._direction;
  12614. if (this.cellIndex == this._toIndex) {
  12615. if (this._loopAnimation) {
  12616. this.cellIndex = this._fromIndex;
  12617. } else {
  12618. this._animationStarted = false;
  12619. if (this.disposeWhenFinishedAnimating) {
  12620. this.dispose();
  12621. }
  12622. }
  12623. }
  12624. }
  12625. };
  12626. Sprite.prototype.dispose = function () {
  12627. for (var i = 0; i < this._manager.sprites.length; i++) {
  12628. if (this._manager.sprites[i] == this) {
  12629. this._manager.sprites.splice(i, 1);
  12630. }
  12631. }
  12632. };
  12633. return Sprite;
  12634. })();
  12635. BABYLON.Sprite = Sprite;
  12636. })(BABYLON || (BABYLON = {}));
  12637. var BABYLON;
  12638. (function (BABYLON) {
  12639. var Layer = (function () {
  12640. function Layer(name, imgUrl, scene, isBackground, color) {
  12641. this.name = name;
  12642. this._vertexDeclaration = [2];
  12643. this._vertexStrideSize = 2 * 4;
  12644. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12645. this.isBackground = isBackground === undefined ? true : isBackground;
  12646. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12647. this._scene = scene;
  12648. this._scene.layers.push(this);
  12649. var vertices = [];
  12650. vertices.push(1, 1);
  12651. vertices.push(-1, 1);
  12652. vertices.push(-1, -1);
  12653. vertices.push(1, -1);
  12654. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12655. var indices = [];
  12656. indices.push(0);
  12657. indices.push(1);
  12658. indices.push(2);
  12659. indices.push(0);
  12660. indices.push(2);
  12661. indices.push(3);
  12662. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12663. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12664. }
  12665. Layer.prototype.render = function () {
  12666. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12667. return;
  12668. var engine = this._scene.getEngine();
  12669. engine.enableEffect(this._effect);
  12670. engine.setState(false);
  12671. this._effect.setTexture("textureSampler", this.texture);
  12672. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12673. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12674. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12675. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12676. engine.draw(true, 0, 6);
  12677. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12678. };
  12679. Layer.prototype.dispose = function () {
  12680. if (this._vertexBuffer) {
  12681. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12682. this._vertexBuffer = null;
  12683. }
  12684. if (this._indexBuffer) {
  12685. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12686. this._indexBuffer = null;
  12687. }
  12688. if (this.texture) {
  12689. this.texture.dispose();
  12690. this.texture = null;
  12691. }
  12692. var index = this._scene.layers.indexOf(this);
  12693. this._scene.layers.splice(index, 1);
  12694. if (this.onDispose) {
  12695. this.onDispose();
  12696. }
  12697. };
  12698. return Layer;
  12699. })();
  12700. BABYLON.Layer = Layer;
  12701. })(BABYLON || (BABYLON = {}));
  12702. var BABYLON;
  12703. (function (BABYLON) {
  12704. var Particle = (function () {
  12705. function Particle() {
  12706. this.position = BABYLON.Vector3.Zero();
  12707. this.direction = BABYLON.Vector3.Zero();
  12708. this.color = new BABYLON.Color4(0, 0, 0, 0);
  12709. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  12710. this.lifeTime = 1.0;
  12711. this.age = 0;
  12712. this.size = 0;
  12713. this.angle = 0;
  12714. this.angularSpeed = 0;
  12715. }
  12716. return Particle;
  12717. })();
  12718. BABYLON.Particle = Particle;
  12719. })(BABYLON || (BABYLON = {}));
  12720. var BABYLON;
  12721. (function (BABYLON) {
  12722. var randomNumber = function (min, max) {
  12723. if (min == max) {
  12724. return (min);
  12725. }
  12726. var random = Math.random();
  12727. return ((random * (max - min)) + min);
  12728. };
  12729. var ParticleSystem = (function () {
  12730. function ParticleSystem(name, capacity, scene, customEffect) {
  12731. var _this = this;
  12732. this.name = name;
  12733. this.renderingGroupId = 0;
  12734. this.emitter = null;
  12735. this.emitRate = 10;
  12736. this.manualEmitCount = -1;
  12737. this.updateSpeed = 0.01;
  12738. this.targetStopDuration = 0;
  12739. this.disposeOnStop = false;
  12740. this.minEmitPower = 1;
  12741. this.maxEmitPower = 1;
  12742. this.minLifeTime = 1;
  12743. this.maxLifeTime = 1;
  12744. this.minSize = 1;
  12745. this.maxSize = 1;
  12746. this.minAngularSpeed = 0;
  12747. this.maxAngularSpeed = 0;
  12748. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  12749. this.forceDepthWrite = false;
  12750. this.gravity = BABYLON.Vector3.Zero();
  12751. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  12752. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  12753. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  12754. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  12755. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12756. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12757. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  12758. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12759. this.particles = new Array();
  12760. this._vertexDeclaration = [3, 4, 4];
  12761. this._vertexStrideSize = 11 * 4;
  12762. this._stockParticles = new Array();
  12763. this._newPartsExcess = 0;
  12764. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  12765. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  12766. this._scaledDirection = BABYLON.Vector3.Zero();
  12767. this._scaledGravity = BABYLON.Vector3.Zero();
  12768. this._currentRenderId = -1;
  12769. this._started = false;
  12770. this._stopped = false;
  12771. this._actualFrame = 0;
  12772. this.id = name;
  12773. this._capacity = capacity;
  12774. this._scene = scene;
  12775. this._customEffect = customEffect;
  12776. scene.particleSystems.push(this);
  12777. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12778. var indices = [];
  12779. var index = 0;
  12780. for (var count = 0; count < capacity; count++) {
  12781. indices.push(index);
  12782. indices.push(index + 1);
  12783. indices.push(index + 2);
  12784. indices.push(index);
  12785. indices.push(index + 2);
  12786. indices.push(index + 3);
  12787. index += 4;
  12788. }
  12789. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12790. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12791. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  12792. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  12793. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  12794. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  12795. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  12796. };
  12797. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  12798. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  12799. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  12800. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  12801. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  12802. };
  12803. }
  12804. ParticleSystem.prototype.getCapacity = function () {
  12805. return this._capacity;
  12806. };
  12807. ParticleSystem.prototype.isAlive = function () {
  12808. return this._alive;
  12809. };
  12810. ParticleSystem.prototype.isStarted = function () {
  12811. return this._started;
  12812. };
  12813. ParticleSystem.prototype.start = function () {
  12814. this._started = true;
  12815. this._stopped = false;
  12816. this._actualFrame = 0;
  12817. };
  12818. ParticleSystem.prototype.stop = function () {
  12819. this._stopped = true;
  12820. };
  12821. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  12822. var offset = index * 11;
  12823. this._vertices[offset] = particle.position.x;
  12824. this._vertices[offset + 1] = particle.position.y;
  12825. this._vertices[offset + 2] = particle.position.z;
  12826. this._vertices[offset + 3] = particle.color.r;
  12827. this._vertices[offset + 4] = particle.color.g;
  12828. this._vertices[offset + 5] = particle.color.b;
  12829. this._vertices[offset + 6] = particle.color.a;
  12830. this._vertices[offset + 7] = particle.angle;
  12831. this._vertices[offset + 8] = particle.size;
  12832. this._vertices[offset + 9] = offsetX;
  12833. this._vertices[offset + 10] = offsetY;
  12834. };
  12835. ParticleSystem.prototype._update = function (newParticles) {
  12836. this._alive = this.particles.length > 0;
  12837. for (var index = 0; index < this.particles.length; index++) {
  12838. var particle = this.particles[index];
  12839. particle.age += this._scaledUpdateSpeed;
  12840. if (particle.age >= particle.lifeTime) {
  12841. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  12842. index--;
  12843. continue;
  12844. } else {
  12845. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  12846. particle.color.addInPlace(this._scaledColorStep);
  12847. if (particle.color.a < 0)
  12848. particle.color.a = 0;
  12849. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  12850. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  12851. particle.position.addInPlace(this._scaledDirection);
  12852. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  12853. particle.direction.addInPlace(this._scaledGravity);
  12854. }
  12855. }
  12856. var worldMatrix;
  12857. if (this.emitter.position) {
  12858. worldMatrix = this.emitter.getWorldMatrix();
  12859. } else {
  12860. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  12861. }
  12862. for (index = 0; index < newParticles; index++) {
  12863. if (this.particles.length == this._capacity) {
  12864. break;
  12865. }
  12866. if (this._stockParticles.length !== 0) {
  12867. particle = this._stockParticles.pop();
  12868. particle.age = 0;
  12869. } else {
  12870. particle = new BABYLON.Particle();
  12871. }
  12872. this.particles.push(particle);
  12873. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  12874. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  12875. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  12876. particle.size = randomNumber(this.minSize, this.maxSize);
  12877. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  12878. this.startPositionFunction(worldMatrix, particle.position);
  12879. var step = randomNumber(0, 1.0);
  12880. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  12881. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  12882. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  12883. }
  12884. };
  12885. ParticleSystem.prototype._getEffect = function () {
  12886. if (this._customEffect) {
  12887. return this._customEffect;
  12888. }
  12889. ;
  12890. var defines = [];
  12891. if (this._scene.clipPlane) {
  12892. defines.push("#define CLIPPLANE");
  12893. }
  12894. var join = defines.join("\n");
  12895. if (this._cachedDefines != join) {
  12896. this._cachedDefines = join;
  12897. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  12898. }
  12899. return this._effect;
  12900. };
  12901. ParticleSystem.prototype.animate = function () {
  12902. if (!this._started)
  12903. return;
  12904. var effect = this._getEffect();
  12905. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  12906. return;
  12907. if (this._currentRenderId === this._scene.getRenderId()) {
  12908. return;
  12909. }
  12910. this._currentRenderId = this._scene.getRenderId();
  12911. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  12912. var emitCout;
  12913. if (this.manualEmitCount > -1) {
  12914. emitCout = this.manualEmitCount;
  12915. this.manualEmitCount = 0;
  12916. } else {
  12917. emitCout = this.emitRate;
  12918. }
  12919. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  12920. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  12921. if (this._newPartsExcess > 1.0) {
  12922. newParticles += this._newPartsExcess >> 0;
  12923. this._newPartsExcess -= this._newPartsExcess >> 0;
  12924. }
  12925. this._alive = false;
  12926. if (!this._stopped) {
  12927. this._actualFrame += this._scaledUpdateSpeed;
  12928. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  12929. this.stop();
  12930. } else {
  12931. newParticles = 0;
  12932. }
  12933. this._update(newParticles);
  12934. if (this._stopped) {
  12935. if (!this._alive) {
  12936. this._started = false;
  12937. if (this.disposeOnStop) {
  12938. this._scene._toBeDisposed.push(this);
  12939. }
  12940. }
  12941. }
  12942. var offset = 0;
  12943. for (var index = 0; index < this.particles.length; index++) {
  12944. var particle = this.particles[index];
  12945. this._appendParticleVertex(offset++, particle, 0, 0);
  12946. this._appendParticleVertex(offset++, particle, 1, 0);
  12947. this._appendParticleVertex(offset++, particle, 1, 1);
  12948. this._appendParticleVertex(offset++, particle, 0, 1);
  12949. }
  12950. var engine = this._scene.getEngine();
  12951. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  12952. };
  12953. ParticleSystem.prototype.render = function () {
  12954. var effect = this._getEffect();
  12955. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  12956. return 0;
  12957. var engine = this._scene.getEngine();
  12958. engine.enableEffect(effect);
  12959. var viewMatrix = this._scene.getViewMatrix();
  12960. effect.setTexture("diffuseSampler", this.particleTexture);
  12961. effect.setMatrix("view", viewMatrix);
  12962. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12963. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  12964. if (this._scene.clipPlane) {
  12965. var clipPlane = this._scene.clipPlane;
  12966. var invView = viewMatrix.clone();
  12967. invView.invert();
  12968. effect.setMatrix("invView", invView);
  12969. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12970. }
  12971. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12972. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  12973. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  12974. } else {
  12975. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12976. }
  12977. if (this.forceDepthWrite) {
  12978. engine.setDepthWrite(true);
  12979. }
  12980. engine.draw(true, 0, this.particles.length * 6);
  12981. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12982. return this.particles.length;
  12983. };
  12984. ParticleSystem.prototype.dispose = function () {
  12985. if (this._vertexBuffer) {
  12986. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12987. this._vertexBuffer = null;
  12988. }
  12989. if (this._indexBuffer) {
  12990. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12991. this._indexBuffer = null;
  12992. }
  12993. if (this.particleTexture) {
  12994. this.particleTexture.dispose();
  12995. this.particleTexture = null;
  12996. }
  12997. var index = this._scene.particleSystems.indexOf(this);
  12998. this._scene.particleSystems.splice(index, 1);
  12999. if (this.onDispose) {
  13000. this.onDispose();
  13001. }
  13002. };
  13003. ParticleSystem.prototype.clone = function (name, newEmitter) {
  13004. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  13005. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  13006. if (newEmitter === undefined) {
  13007. newEmitter = this.emitter;
  13008. }
  13009. result.emitter = newEmitter;
  13010. if (this.particleTexture) {
  13011. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  13012. }
  13013. result.start();
  13014. return result;
  13015. };
  13016. ParticleSystem.BLENDMODE_ONEONE = 0;
  13017. ParticleSystem.BLENDMODE_STANDARD = 1;
  13018. return ParticleSystem;
  13019. })();
  13020. BABYLON.ParticleSystem = ParticleSystem;
  13021. })(BABYLON || (BABYLON = {}));
  13022. var BABYLON;
  13023. (function (BABYLON) {
  13024. var Animation = (function () {
  13025. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  13026. this.name = name;
  13027. this.targetProperty = targetProperty;
  13028. this.framePerSecond = framePerSecond;
  13029. this.dataType = dataType;
  13030. this.loopMode = loopMode;
  13031. this._offsetsCache = {};
  13032. this._highLimitsCache = {};
  13033. this._stopped = false;
  13034. this.targetPropertyPath = targetProperty.split(".");
  13035. this.dataType = dataType;
  13036. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  13037. }
  13038. Animation.prototype.isStopped = function () {
  13039. return this._stopped;
  13040. };
  13041. Animation.prototype.getKeys = function () {
  13042. return this._keys;
  13043. };
  13044. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  13045. return startValue + (endValue - startValue) * gradient;
  13046. };
  13047. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  13048. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  13049. };
  13050. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  13051. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  13052. };
  13053. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  13054. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  13055. };
  13056. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  13057. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  13058. };
  13059. Animation.prototype.clone = function () {
  13060. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  13061. clone.setKeys(this._keys);
  13062. return clone;
  13063. };
  13064. Animation.prototype.setKeys = function (values) {
  13065. this._keys = values.slice(0);
  13066. this._offsetsCache = {};
  13067. this._highLimitsCache = {};
  13068. };
  13069. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  13070. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  13071. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  13072. }
  13073. this.currentFrame = currentFrame;
  13074. for (var key = 0; key < this._keys.length; key++) {
  13075. if (this._keys[key + 1].frame >= currentFrame) {
  13076. var startValue = this._keys[key].value;
  13077. var endValue = this._keys[key + 1].value;
  13078. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  13079. switch (this.dataType) {
  13080. case Animation.ANIMATIONTYPE_FLOAT:
  13081. switch (loopMode) {
  13082. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13083. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13084. return this.floatInterpolateFunction(startValue, endValue, gradient);
  13085. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13086. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  13087. }
  13088. break;
  13089. case Animation.ANIMATIONTYPE_QUATERNION:
  13090. var quaternion = null;
  13091. switch (loopMode) {
  13092. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13093. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13094. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  13095. break;
  13096. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13097. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13098. break;
  13099. }
  13100. return quaternion;
  13101. case Animation.ANIMATIONTYPE_VECTOR3:
  13102. switch (loopMode) {
  13103. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13104. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13105. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  13106. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13107. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13108. }
  13109. case Animation.ANIMATIONTYPE_VECTOR2:
  13110. switch (loopMode) {
  13111. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13112. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13113. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  13114. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13115. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13116. }
  13117. case Animation.ANIMATIONTYPE_COLOR3:
  13118. switch (loopMode) {
  13119. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13120. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13121. return this.color3InterpolateFunction(startValue, endValue, gradient);
  13122. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13123. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13124. }
  13125. case Animation.ANIMATIONTYPE_MATRIX:
  13126. switch (loopMode) {
  13127. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13128. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13129. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13130. return startValue;
  13131. }
  13132. default:
  13133. break;
  13134. }
  13135. break;
  13136. }
  13137. }
  13138. return this._keys[this._keys.length - 1].value;
  13139. };
  13140. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  13141. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  13142. this._stopped = true;
  13143. return false;
  13144. }
  13145. var returnValue = true;
  13146. if (this._keys[0].frame != 0) {
  13147. var newKey = {
  13148. frame: 0,
  13149. value: this._keys[0].value
  13150. };
  13151. this._keys.splice(0, 0, newKey);
  13152. }
  13153. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  13154. from = this._keys[0].frame;
  13155. }
  13156. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  13157. to = this._keys[this._keys.length - 1].frame;
  13158. }
  13159. var range = to - from;
  13160. var offsetValue;
  13161. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  13162. if (ratio > range && !loop) {
  13163. returnValue = false;
  13164. highLimitValue = this._keys[this._keys.length - 1].value;
  13165. } else {
  13166. var highLimitValue = 0;
  13167. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  13168. var keyOffset = to.toString() + from.toString();
  13169. if (!this._offsetsCache[keyOffset]) {
  13170. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13171. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13172. switch (this.dataType) {
  13173. case Animation.ANIMATIONTYPE_FLOAT:
  13174. this._offsetsCache[keyOffset] = toValue - fromValue;
  13175. break;
  13176. case Animation.ANIMATIONTYPE_QUATERNION:
  13177. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13178. break;
  13179. case Animation.ANIMATIONTYPE_VECTOR3:
  13180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13181. case Animation.ANIMATIONTYPE_VECTOR2:
  13182. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13183. case Animation.ANIMATIONTYPE_COLOR3:
  13184. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13185. default:
  13186. break;
  13187. }
  13188. this._highLimitsCache[keyOffset] = toValue;
  13189. }
  13190. highLimitValue = this._highLimitsCache[keyOffset];
  13191. offsetValue = this._offsetsCache[keyOffset];
  13192. }
  13193. }
  13194. if (offsetValue === undefined) {
  13195. switch (this.dataType) {
  13196. case Animation.ANIMATIONTYPE_FLOAT:
  13197. offsetValue = 0;
  13198. break;
  13199. case Animation.ANIMATIONTYPE_QUATERNION:
  13200. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  13201. break;
  13202. case Animation.ANIMATIONTYPE_VECTOR3:
  13203. offsetValue = BABYLON.Vector3.Zero();
  13204. break;
  13205. case Animation.ANIMATIONTYPE_VECTOR2:
  13206. offsetValue = BABYLON.Vector2.Zero();
  13207. break;
  13208. case Animation.ANIMATIONTYPE_COLOR3:
  13209. offsetValue = BABYLON.Color3.Black();
  13210. }
  13211. }
  13212. var repeatCount = (ratio / range) >> 0;
  13213. var currentFrame = returnValue ? from + ratio % range : to;
  13214. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  13215. if (this.targetPropertyPath.length > 1) {
  13216. var property = this._target[this.targetPropertyPath[0]];
  13217. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  13218. property = property[this.targetPropertyPath[index]];
  13219. }
  13220. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  13221. } else {
  13222. this._target[this.targetPropertyPath[0]] = currentValue;
  13223. }
  13224. if (this._target.markAsDirty) {
  13225. this._target.markAsDirty(this.targetProperty);
  13226. }
  13227. if (!returnValue) {
  13228. this._stopped = true;
  13229. }
  13230. return returnValue;
  13231. };
  13232. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  13233. get: function () {
  13234. return Animation._ANIMATIONTYPE_FLOAT;
  13235. },
  13236. enumerable: true,
  13237. configurable: true
  13238. });
  13239. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  13240. get: function () {
  13241. return Animation._ANIMATIONTYPE_VECTOR3;
  13242. },
  13243. enumerable: true,
  13244. configurable: true
  13245. });
  13246. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  13247. get: function () {
  13248. return Animation._ANIMATIONTYPE_VECTOR2;
  13249. },
  13250. enumerable: true,
  13251. configurable: true
  13252. });
  13253. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  13254. get: function () {
  13255. return Animation._ANIMATIONTYPE_QUATERNION;
  13256. },
  13257. enumerable: true,
  13258. configurable: true
  13259. });
  13260. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13261. get: function () {
  13262. return Animation._ANIMATIONTYPE_MATRIX;
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13268. get: function () {
  13269. return Animation._ANIMATIONTYPE_COLOR3;
  13270. },
  13271. enumerable: true,
  13272. configurable: true
  13273. });
  13274. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13275. get: function () {
  13276. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13277. },
  13278. enumerable: true,
  13279. configurable: true
  13280. });
  13281. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13282. get: function () {
  13283. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13284. },
  13285. enumerable: true,
  13286. configurable: true
  13287. });
  13288. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13289. get: function () {
  13290. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13291. },
  13292. enumerable: true,
  13293. configurable: true
  13294. });
  13295. Animation._ANIMATIONTYPE_FLOAT = 0;
  13296. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13297. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13298. Animation._ANIMATIONTYPE_MATRIX = 3;
  13299. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13300. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13301. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13302. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13303. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13304. return Animation;
  13305. })();
  13306. BABYLON.Animation = Animation;
  13307. })(BABYLON || (BABYLON = {}));
  13308. var BABYLON;
  13309. (function (BABYLON) {
  13310. var Animatable = (function () {
  13311. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13312. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13313. if (typeof toFrame === "undefined") { toFrame = 100; }
  13314. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13315. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13316. this.target = target;
  13317. this.fromFrame = fromFrame;
  13318. this.toFrame = toFrame;
  13319. this.loopAnimation = loopAnimation;
  13320. this.speedRatio = speedRatio;
  13321. this.onAnimationEnd = onAnimationEnd;
  13322. this._animations = new Array();
  13323. this._paused = false;
  13324. this.animationStarted = false;
  13325. if (animations) {
  13326. this.appendAnimations(target, animations);
  13327. }
  13328. this._scene = scene;
  13329. scene._activeAnimatables.push(this);
  13330. }
  13331. Animatable.prototype.appendAnimations = function (target, animations) {
  13332. for (var index = 0; index < animations.length; index++) {
  13333. var animation = animations[index];
  13334. animation._target = target;
  13335. this._animations.push(animation);
  13336. }
  13337. };
  13338. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13339. var animations = this._animations;
  13340. for (var index = 0; index < animations.length; index++) {
  13341. if (animations[index].targetProperty === property) {
  13342. return animations[index];
  13343. }
  13344. }
  13345. return null;
  13346. };
  13347. Animatable.prototype.pause = function () {
  13348. if (this._paused) {
  13349. return;
  13350. }
  13351. this._paused = true;
  13352. };
  13353. Animatable.prototype.restart = function () {
  13354. this._paused = false;
  13355. };
  13356. Animatable.prototype.stop = function () {
  13357. var index = this._scene._activeAnimatables.indexOf(this);
  13358. if (index > -1) {
  13359. this._scene._activeAnimatables.splice(index, 1);
  13360. }
  13361. if (this.onAnimationEnd) {
  13362. this.onAnimationEnd();
  13363. }
  13364. };
  13365. Animatable.prototype._animate = function (delay) {
  13366. if (this._paused) {
  13367. if (!this._pausedDelay) {
  13368. this._pausedDelay = delay;
  13369. }
  13370. return true;
  13371. }
  13372. if (!this._localDelayOffset) {
  13373. this._localDelayOffset = delay;
  13374. } else if (this._pausedDelay) {
  13375. this._localDelayOffset += delay - this._pausedDelay;
  13376. this._pausedDelay = null;
  13377. }
  13378. var running = false;
  13379. var animations = this._animations;
  13380. for (var index = 0; index < animations.length; index++) {
  13381. var animation = animations[index];
  13382. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13383. running = running || isRunning;
  13384. }
  13385. if (!running && this.onAnimationEnd) {
  13386. this.onAnimationEnd();
  13387. }
  13388. return running;
  13389. };
  13390. return Animatable;
  13391. })();
  13392. BABYLON.Animatable = Animatable;
  13393. })(BABYLON || (BABYLON = {}));
  13394. var BABYLON;
  13395. (function (BABYLON) {
  13396. var Octree = (function () {
  13397. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13398. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13399. this.maxDepth = maxDepth;
  13400. this.dynamicContent = new Array();
  13401. this._maxBlockCapacity = maxBlockCapacity || 64;
  13402. this._selectionContent = new BABYLON.SmartArray(1024);
  13403. this._creationFunc = creationFunc;
  13404. }
  13405. Octree.prototype.update = function (worldMin, worldMax, entries) {
  13406. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  13407. };
  13408. Octree.prototype.addMesh = function (entry) {
  13409. for (var index = 0; index < this.blocks.length; index++) {
  13410. var block = this.blocks[index];
  13411. block.addEntry(entry);
  13412. }
  13413. };
  13414. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  13415. this._selectionContent.reset();
  13416. for (var index = 0; index < this.blocks.length; index++) {
  13417. var block = this.blocks[index];
  13418. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  13419. }
  13420. if (allowDuplicate) {
  13421. this._selectionContent.concat(this.dynamicContent);
  13422. } else {
  13423. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13424. }
  13425. return this._selectionContent;
  13426. };
  13427. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  13428. this._selectionContent.reset();
  13429. for (var index = 0; index < this.blocks.length; index++) {
  13430. var block = this.blocks[index];
  13431. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  13432. }
  13433. if (allowDuplicate) {
  13434. this._selectionContent.concat(this.dynamicContent);
  13435. } else {
  13436. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13437. }
  13438. return this._selectionContent;
  13439. };
  13440. Octree.prototype.intersectsRay = function (ray) {
  13441. this._selectionContent.reset();
  13442. for (var index = 0; index < this.blocks.length; index++) {
  13443. var block = this.blocks[index];
  13444. block.intersectsRay(ray, this._selectionContent);
  13445. }
  13446. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  13447. return this._selectionContent;
  13448. };
  13449. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  13450. target.blocks = new Array();
  13451. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  13452. for (var x = 0; x < 2; x++) {
  13453. for (var y = 0; y < 2; y++) {
  13454. for (var z = 0; z < 2; z++) {
  13455. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  13456. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  13457. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  13458. block.addEntries(entries);
  13459. target.blocks.push(block);
  13460. }
  13461. }
  13462. }
  13463. };
  13464. Octree.CreationFuncForMeshes = function (entry, block) {
  13465. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13466. block.entries.push(entry);
  13467. }
  13468. };
  13469. Octree.CreationFuncForSubMeshes = function (entry, block) {
  13470. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  13471. block.entries.push(entry);
  13472. }
  13473. };
  13474. return Octree;
  13475. })();
  13476. BABYLON.Octree = Octree;
  13477. })(BABYLON || (BABYLON = {}));
  13478. var BABYLON;
  13479. (function (BABYLON) {
  13480. var OctreeBlock = (function () {
  13481. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  13482. this.entries = new Array();
  13483. this._boundingVectors = new Array();
  13484. this._capacity = capacity;
  13485. this._depth = depth;
  13486. this._maxDepth = maxDepth;
  13487. this._creationFunc = creationFunc;
  13488. this._minPoint = minPoint;
  13489. this._maxPoint = maxPoint;
  13490. this._boundingVectors.push(minPoint.clone());
  13491. this._boundingVectors.push(maxPoint.clone());
  13492. this._boundingVectors.push(minPoint.clone());
  13493. this._boundingVectors[2].x = maxPoint.x;
  13494. this._boundingVectors.push(minPoint.clone());
  13495. this._boundingVectors[3].y = maxPoint.y;
  13496. this._boundingVectors.push(minPoint.clone());
  13497. this._boundingVectors[4].z = maxPoint.z;
  13498. this._boundingVectors.push(maxPoint.clone());
  13499. this._boundingVectors[5].z = minPoint.z;
  13500. this._boundingVectors.push(maxPoint.clone());
  13501. this._boundingVectors[6].x = minPoint.x;
  13502. this._boundingVectors.push(maxPoint.clone());
  13503. this._boundingVectors[7].y = minPoint.y;
  13504. }
  13505. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  13506. get: function () {
  13507. return this._capacity;
  13508. },
  13509. enumerable: true,
  13510. configurable: true
  13511. });
  13512. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  13513. get: function () {
  13514. return this._minPoint;
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  13520. get: function () {
  13521. return this._maxPoint;
  13522. },
  13523. enumerable: true,
  13524. configurable: true
  13525. });
  13526. OctreeBlock.prototype.addEntry = function (entry) {
  13527. if (this.blocks) {
  13528. for (var index = 0; index < this.blocks.length; index++) {
  13529. var block = this.blocks[index];
  13530. block.addEntry(entry);
  13531. }
  13532. return;
  13533. }
  13534. this._creationFunc(entry, this);
  13535. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  13536. this.createInnerBlocks();
  13537. }
  13538. };
  13539. OctreeBlock.prototype.addEntries = function (entries) {
  13540. for (var index = 0; index < entries.length; index++) {
  13541. var mesh = entries[index];
  13542. this.addEntry(mesh);
  13543. }
  13544. };
  13545. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  13546. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  13547. if (this.blocks) {
  13548. for (var index = 0; index < this.blocks.length; index++) {
  13549. var block = this.blocks[index];
  13550. block.select(frustumPlanes, selection, allowDuplicate);
  13551. }
  13552. return;
  13553. }
  13554. if (allowDuplicate) {
  13555. selection.concat(this.entries);
  13556. } else {
  13557. selection.concatWithNoDuplicate(this.entries);
  13558. }
  13559. }
  13560. };
  13561. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  13562. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  13563. if (this.blocks) {
  13564. for (var index = 0; index < this.blocks.length; index++) {
  13565. var block = this.blocks[index];
  13566. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  13567. }
  13568. return;
  13569. }
  13570. if (allowDuplicate) {
  13571. selection.concat(this.entries);
  13572. } else {
  13573. selection.concatWithNoDuplicate(this.entries);
  13574. }
  13575. }
  13576. };
  13577. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  13578. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  13579. if (this.blocks) {
  13580. for (var index = 0; index < this.blocks.length; index++) {
  13581. var block = this.blocks[index];
  13582. block.intersectsRay(ray, selection);
  13583. }
  13584. return;
  13585. }
  13586. selection.concatWithNoDuplicate(this.entries);
  13587. }
  13588. };
  13589. OctreeBlock.prototype.createInnerBlocks = function () {
  13590. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  13591. };
  13592. return OctreeBlock;
  13593. })();
  13594. BABYLON.OctreeBlock = OctreeBlock;
  13595. })(BABYLON || (BABYLON = {}));
  13596. var BABYLON;
  13597. (function (BABYLON) {
  13598. var Bone = (function () {
  13599. function Bone(name, skeleton, parentBone, matrix) {
  13600. this.name = name;
  13601. this.children = new Array();
  13602. this.animations = new Array();
  13603. this._worldTransform = new BABYLON.Matrix();
  13604. this._absoluteTransform = new BABYLON.Matrix();
  13605. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  13606. this._skeleton = skeleton;
  13607. this._matrix = matrix;
  13608. this._baseMatrix = matrix;
  13609. skeleton.bones.push(this);
  13610. if (parentBone) {
  13611. this._parent = parentBone;
  13612. parentBone.children.push(this);
  13613. } else {
  13614. this._parent = null;
  13615. }
  13616. this._updateDifferenceMatrix();
  13617. }
  13618. Bone.prototype.getParent = function () {
  13619. return this._parent;
  13620. };
  13621. Bone.prototype.getLocalMatrix = function () {
  13622. return this._matrix;
  13623. };
  13624. Bone.prototype.getBaseMatrix = function () {
  13625. return this._baseMatrix;
  13626. };
  13627. Bone.prototype.getWorldMatrix = function () {
  13628. return this._worldTransform;
  13629. };
  13630. Bone.prototype.getInvertedAbsoluteTransform = function () {
  13631. return this._invertedAbsoluteTransform;
  13632. };
  13633. Bone.prototype.getAbsoluteMatrix = function () {
  13634. var matrix = this._matrix.clone();
  13635. var parent = this._parent;
  13636. while (parent) {
  13637. matrix = matrix.multiply(parent.getLocalMatrix());
  13638. parent = parent.getParent();
  13639. }
  13640. return matrix;
  13641. };
  13642. Bone.prototype.updateMatrix = function (matrix) {
  13643. this._matrix = matrix;
  13644. this._skeleton._markAsDirty();
  13645. this._updateDifferenceMatrix();
  13646. };
  13647. Bone.prototype._updateDifferenceMatrix = function () {
  13648. if (this._parent) {
  13649. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  13650. } else {
  13651. this._absoluteTransform.copyFrom(this._matrix);
  13652. }
  13653. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  13654. for (var index = 0; index < this.children.length; index++) {
  13655. this.children[index]._updateDifferenceMatrix();
  13656. }
  13657. };
  13658. Bone.prototype.markAsDirty = function () {
  13659. this._skeleton._markAsDirty();
  13660. };
  13661. return Bone;
  13662. })();
  13663. BABYLON.Bone = Bone;
  13664. })(BABYLON || (BABYLON = {}));
  13665. var BABYLON;
  13666. (function (BABYLON) {
  13667. var Skeleton = (function () {
  13668. function Skeleton(name, id, scene) {
  13669. this.name = name;
  13670. this.id = id;
  13671. this.bones = new Array();
  13672. this._isDirty = true;
  13673. this._identity = BABYLON.Matrix.Identity();
  13674. this.bones = [];
  13675. this._scene = scene;
  13676. scene.skeletons.push(this);
  13677. }
  13678. Skeleton.prototype.getTransformMatrices = function () {
  13679. return this._transformMatrices;
  13680. };
  13681. Skeleton.prototype._markAsDirty = function () {
  13682. this._isDirty = true;
  13683. };
  13684. Skeleton.prototype.prepare = function () {
  13685. if (!this._isDirty) {
  13686. return;
  13687. }
  13688. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  13689. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  13690. }
  13691. for (var index = 0; index < this.bones.length; index++) {
  13692. var bone = this.bones[index];
  13693. var parentBone = bone.getParent();
  13694. if (parentBone) {
  13695. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  13696. } else {
  13697. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  13698. }
  13699. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  13700. }
  13701. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  13702. this._isDirty = false;
  13703. };
  13704. Skeleton.prototype.getAnimatables = function () {
  13705. if (!this._animatables || this._animatables.length != this.bones.length) {
  13706. this._animatables = [];
  13707. for (var index = 0; index < this.bones.length; index++) {
  13708. this._animatables.push(this.bones[index]);
  13709. }
  13710. }
  13711. return this._animatables;
  13712. };
  13713. Skeleton.prototype.clone = function (name, id) {
  13714. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  13715. for (var index = 0; index < this.bones.length; index++) {
  13716. var source = this.bones[index];
  13717. var parentBone = null;
  13718. if (source.getParent()) {
  13719. var parentIndex = this.bones.indexOf(source.getParent());
  13720. parentBone = result.bones[parentIndex];
  13721. }
  13722. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  13723. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  13724. }
  13725. return result;
  13726. };
  13727. return Skeleton;
  13728. })();
  13729. BABYLON.Skeleton = Skeleton;
  13730. })(BABYLON || (BABYLON = {}));
  13731. var BABYLON;
  13732. (function (BABYLON) {
  13733. var PostProcess = (function () {
  13734. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  13735. this.name = name;
  13736. this.width = -1;
  13737. this.height = -1;
  13738. this._reusable = false;
  13739. this._textures = new BABYLON.SmartArray(2);
  13740. this._currentRenderTextureInd = 0;
  13741. if (camera != null) {
  13742. this._camera = camera;
  13743. this._scene = camera.getScene();
  13744. camera.attachPostProcess(this);
  13745. this._engine = this._scene.getEngine();
  13746. } else {
  13747. this._engine = engine;
  13748. }
  13749. this._renderRatio = ratio;
  13750. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13751. this._reusable = reusable || false;
  13752. samplers = samplers || [];
  13753. samplers.push("textureSampler");
  13754. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  13755. }
  13756. PostProcess.prototype.isReusable = function () {
  13757. return this._reusable;
  13758. };
  13759. PostProcess.prototype.activate = function (camera, sourceTexture) {
  13760. camera = camera || this._camera;
  13761. var scene = camera.getScene();
  13762. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  13763. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  13764. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  13765. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  13766. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  13767. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  13768. if (this._textures.length > 0) {
  13769. for (var i = 0; i < this._textures.length; i++) {
  13770. this._engine._releaseTexture(this._textures.data[i]);
  13771. }
  13772. this._textures.reset();
  13773. }
  13774. this.width = desiredWidth;
  13775. this.height = desiredHeight;
  13776. 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 }));
  13777. if (this._reusable) {
  13778. 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 }));
  13779. }
  13780. if (this.onSizeChanged) {
  13781. this.onSizeChanged();
  13782. }
  13783. }
  13784. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  13785. if (this.onActivate) {
  13786. this.onActivate(camera);
  13787. }
  13788. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  13789. if (this._reusable) {
  13790. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  13791. }
  13792. };
  13793. PostProcess.prototype.apply = function () {
  13794. if (!this._effect.isReady())
  13795. return null;
  13796. this._engine.enableEffect(this._effect);
  13797. this._engine.setState(false);
  13798. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13799. this._engine.setDepthBuffer(false);
  13800. this._engine.setDepthWrite(false);
  13801. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  13802. if (this.onApply) {
  13803. this.onApply(this._effect);
  13804. }
  13805. return this._effect;
  13806. };
  13807. PostProcess.prototype.dispose = function (camera) {
  13808. camera = camera || this._camera;
  13809. if (this._textures.length > 0) {
  13810. for (var i = 0; i < this._textures.length; i++) {
  13811. this._engine._releaseTexture(this._textures.data[i]);
  13812. }
  13813. this._textures.reset();
  13814. }
  13815. camera.detachPostProcess(this);
  13816. var index = camera._postProcesses.indexOf(this);
  13817. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  13818. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  13819. }
  13820. };
  13821. return PostProcess;
  13822. })();
  13823. BABYLON.PostProcess = PostProcess;
  13824. })(BABYLON || (BABYLON = {}));
  13825. var BABYLON;
  13826. (function (BABYLON) {
  13827. var PostProcessManager = (function () {
  13828. function PostProcessManager(scene) {
  13829. this._vertexDeclaration = [2];
  13830. this._vertexStrideSize = 2 * 4;
  13831. this._scene = scene;
  13832. var vertices = [];
  13833. vertices.push(1, 1);
  13834. vertices.push(-1, 1);
  13835. vertices.push(-1, -1);
  13836. vertices.push(1, -1);
  13837. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13838. var indices = [];
  13839. indices.push(0);
  13840. indices.push(1);
  13841. indices.push(2);
  13842. indices.push(0);
  13843. indices.push(2);
  13844. indices.push(3);
  13845. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13846. }
  13847. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  13848. var postProcesses = this._scene.activeCamera._postProcesses;
  13849. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13850. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13851. return false;
  13852. }
  13853. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  13854. return true;
  13855. };
  13856. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  13857. var postProcesses = this._scene.activeCamera._postProcesses;
  13858. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  13859. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  13860. return;
  13861. }
  13862. var engine = this._scene.getEngine();
  13863. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  13864. if (index < postProcessesTakenIndices.length - 1) {
  13865. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  13866. } else {
  13867. if (targetTexture) {
  13868. engine.bindFramebuffer(targetTexture);
  13869. } else {
  13870. engine.restoreDefaultFramebuffer();
  13871. }
  13872. }
  13873. if (doNotPresent) {
  13874. break;
  13875. }
  13876. var pp = postProcesses[postProcessesTakenIndices[index]];
  13877. var effect = pp.apply();
  13878. if (effect) {
  13879. if (pp.onBeforeRender) {
  13880. pp.onBeforeRender(effect);
  13881. }
  13882. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13883. engine.draw(true, 0, 6);
  13884. }
  13885. }
  13886. engine.setDepthBuffer(true);
  13887. engine.setDepthWrite(true);
  13888. };
  13889. PostProcessManager.prototype.dispose = function () {
  13890. if (this._vertexBuffer) {
  13891. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13892. this._vertexBuffer = null;
  13893. }
  13894. if (this._indexBuffer) {
  13895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13896. this._indexBuffer = null;
  13897. }
  13898. };
  13899. return PostProcessManager;
  13900. })();
  13901. BABYLON.PostProcessManager = PostProcessManager;
  13902. })(BABYLON || (BABYLON = {}));
  13903. var __extends = this.__extends || function (d, b) {
  13904. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13905. function __() { this.constructor = d; }
  13906. __.prototype = b.prototype;
  13907. d.prototype = new __();
  13908. };
  13909. var BABYLON;
  13910. (function (BABYLON) {
  13911. var PassPostProcess = (function (_super) {
  13912. __extends(PassPostProcess, _super);
  13913. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  13914. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  13915. }
  13916. return PassPostProcess;
  13917. })(BABYLON.PostProcess);
  13918. BABYLON.PassPostProcess = PassPostProcess;
  13919. })(BABYLON || (BABYLON = {}));
  13920. var __extends = this.__extends || function (d, b) {
  13921. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13922. function __() { this.constructor = d; }
  13923. __.prototype = b.prototype;
  13924. d.prototype = new __();
  13925. };
  13926. var BABYLON;
  13927. (function (BABYLON) {
  13928. var BlurPostProcess = (function (_super) {
  13929. __extends(BlurPostProcess, _super);
  13930. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  13931. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  13932. var _this = this;
  13933. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  13934. this.direction = direction;
  13935. this.blurWidth = blurWidth;
  13936. this.onApply = function (effect) {
  13937. effect.setFloat2("screenSize", _this.width, _this.height);
  13938. effect.setVector2("direction", _this.direction);
  13939. effect.setFloat("blurWidth", _this.blurWidth);
  13940. };
  13941. }
  13942. return BlurPostProcess;
  13943. })(BABYLON.PostProcess);
  13944. BABYLON.BlurPostProcess = BlurPostProcess;
  13945. })(BABYLON || (BABYLON = {}));
  13946. var __extends = this.__extends || function (d, b) {
  13947. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13948. function __() { this.constructor = d; }
  13949. __.prototype = b.prototype;
  13950. d.prototype = new __();
  13951. };
  13952. var BABYLON;
  13953. (function (BABYLON) {
  13954. var FilterPostProcess = (function (_super) {
  13955. __extends(FilterPostProcess, _super);
  13956. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  13957. var _this = this;
  13958. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  13959. this.kernelMatrix = kernelMatrix;
  13960. this.onApply = function (effect) {
  13961. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  13962. };
  13963. }
  13964. return FilterPostProcess;
  13965. })(BABYLON.PostProcess);
  13966. BABYLON.FilterPostProcess = FilterPostProcess;
  13967. })(BABYLON || (BABYLON = {}));
  13968. var __extends = this.__extends || function (d, b) {
  13969. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13970. function __() { this.constructor = d; }
  13971. __.prototype = b.prototype;
  13972. d.prototype = new __();
  13973. };
  13974. var BABYLON;
  13975. (function (BABYLON) {
  13976. var RefractionPostProcess = (function (_super) {
  13977. __extends(RefractionPostProcess, _super);
  13978. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  13979. var _this = this;
  13980. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  13981. this.color = color;
  13982. this.depth = depth;
  13983. this.colorLevel = colorLevel;
  13984. this.onActivate = function (cam) {
  13985. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  13986. };
  13987. this.onApply = function (effect) {
  13988. effect.setColor3("baseColor", _this.color);
  13989. effect.setFloat("depth", _this.depth);
  13990. effect.setFloat("colorLevel", _this.colorLevel);
  13991. effect.setTexture("refractionSampler", _this._refRexture);
  13992. };
  13993. }
  13994. RefractionPostProcess.prototype.dispose = function (camera) {
  13995. if (this._refRexture) {
  13996. this._refRexture.dispose();
  13997. }
  13998. _super.prototype.dispose.call(this, camera);
  13999. };
  14000. return RefractionPostProcess;
  14001. })(BABYLON.PostProcess);
  14002. BABYLON.RefractionPostProcess = RefractionPostProcess;
  14003. })(BABYLON || (BABYLON = {}));
  14004. var __extends = this.__extends || function (d, b) {
  14005. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14006. function __() { this.constructor = d; }
  14007. __.prototype = b.prototype;
  14008. d.prototype = new __();
  14009. };
  14010. var BABYLON;
  14011. (function (BABYLON) {
  14012. var BlackAndWhitePostProcess = (function (_super) {
  14013. __extends(BlackAndWhitePostProcess, _super);
  14014. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14015. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  14016. }
  14017. return BlackAndWhitePostProcess;
  14018. })(BABYLON.PostProcess);
  14019. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  14020. })(BABYLON || (BABYLON = {}));
  14021. var __extends = this.__extends || function (d, b) {
  14022. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14023. function __() { this.constructor = d; }
  14024. __.prototype = b.prototype;
  14025. d.prototype = new __();
  14026. };
  14027. var BABYLON;
  14028. (function (BABYLON) {
  14029. var ConvolutionPostProcess = (function (_super) {
  14030. __extends(ConvolutionPostProcess, _super);
  14031. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  14032. var _this = this;
  14033. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  14034. this.kernel = kernel;
  14035. this.onApply = function (effect) {
  14036. effect.setFloat2("screenSize", _this.width, _this.height);
  14037. effect.setArray("kernel", _this.kernel);
  14038. };
  14039. }
  14040. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  14041. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  14042. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  14043. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  14044. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  14045. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  14046. return ConvolutionPostProcess;
  14047. })(BABYLON.PostProcess);
  14048. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  14049. })(BABYLON || (BABYLON = {}));
  14050. var __extends = this.__extends || function (d, b) {
  14051. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14052. function __() { this.constructor = d; }
  14053. __.prototype = b.prototype;
  14054. d.prototype = new __();
  14055. };
  14056. var BABYLON;
  14057. (function (BABYLON) {
  14058. var FxaaPostProcess = (function (_super) {
  14059. __extends(FxaaPostProcess, _super);
  14060. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14061. var _this = this;
  14062. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  14063. this.onSizeChanged = function () {
  14064. _this.texelWidth = 1.0 / _this.width;
  14065. _this.texelHeight = 1.0 / _this.height;
  14066. };
  14067. this.onApply = function (effect) {
  14068. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  14069. };
  14070. }
  14071. return FxaaPostProcess;
  14072. })(BABYLON.PostProcess);
  14073. BABYLON.FxaaPostProcess = FxaaPostProcess;
  14074. })(BABYLON || (BABYLON = {}));
  14075. var BABYLON;
  14076. (function (BABYLON) {
  14077. var LensFlare = (function () {
  14078. function LensFlare(size, position, color, imgUrl, system) {
  14079. this.size = size;
  14080. this.position = position;
  14081. this.dispose = function () {
  14082. if (this.texture) {
  14083. this.texture.dispose();
  14084. }
  14085. var index = this._system.lensFlares.indexOf(this);
  14086. this._system.lensFlares.splice(index, 1);
  14087. };
  14088. this.color = color || new BABYLON.Color3(1, 1, 1);
  14089. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  14090. this._system = system;
  14091. system.lensFlares.push(this);
  14092. }
  14093. return LensFlare;
  14094. })();
  14095. BABYLON.LensFlare = LensFlare;
  14096. })(BABYLON || (BABYLON = {}));
  14097. var BABYLON;
  14098. (function (BABYLON) {
  14099. var LensFlareSystem = (function () {
  14100. function LensFlareSystem(name, emitter, scene) {
  14101. this.name = name;
  14102. this.lensFlares = new Array();
  14103. this.borderLimit = 300;
  14104. this._vertexDeclaration = [2];
  14105. this._vertexStrideSize = 2 * 4;
  14106. this._isEnabled = true;
  14107. this._scene = scene;
  14108. this._emitter = emitter;
  14109. scene.lensFlareSystems.push(this);
  14110. this.meshesSelectionPredicate = function (m) {
  14111. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  14112. };
  14113. var vertices = [];
  14114. vertices.push(1, 1);
  14115. vertices.push(-1, 1);
  14116. vertices.push(-1, -1);
  14117. vertices.push(1, -1);
  14118. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14119. var indices = [];
  14120. indices.push(0);
  14121. indices.push(1);
  14122. indices.push(2);
  14123. indices.push(0);
  14124. indices.push(2);
  14125. indices.push(3);
  14126. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14127. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  14128. }
  14129. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  14130. get: function () {
  14131. return this._isEnabled;
  14132. },
  14133. set: function (value) {
  14134. this._isEnabled = value;
  14135. },
  14136. enumerable: true,
  14137. configurable: true
  14138. });
  14139. LensFlareSystem.prototype.getScene = function () {
  14140. return this._scene;
  14141. };
  14142. LensFlareSystem.prototype.getEmitter = function () {
  14143. return this._emitter;
  14144. };
  14145. LensFlareSystem.prototype.getEmitterPosition = function () {
  14146. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  14147. };
  14148. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  14149. var position = this.getEmitterPosition();
  14150. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  14151. this._positionX = position.x;
  14152. this._positionY = position.y;
  14153. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  14154. if (position.z > 0) {
  14155. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  14156. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  14157. return true;
  14158. }
  14159. }
  14160. return false;
  14161. };
  14162. LensFlareSystem.prototype._isVisible = function () {
  14163. if (!this._isEnabled) {
  14164. return false;
  14165. }
  14166. var emitterPosition = this.getEmitterPosition();
  14167. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  14168. var distance = direction.length();
  14169. direction.normalize();
  14170. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  14171. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  14172. return !pickInfo.hit || pickInfo.distance > distance;
  14173. };
  14174. LensFlareSystem.prototype.render = function () {
  14175. if (!this._effect.isReady())
  14176. return false;
  14177. var engine = this._scene.getEngine();
  14178. var viewport = this._scene.activeCamera.viewport;
  14179. var globalViewport = viewport.toGlobal(engine);
  14180. if (!this.computeEffectivePosition(globalViewport)) {
  14181. return false;
  14182. }
  14183. if (!this._isVisible()) {
  14184. return false;
  14185. }
  14186. var awayX;
  14187. var awayY;
  14188. if (this._positionX < this.borderLimit + globalViewport.x) {
  14189. awayX = this.borderLimit + globalViewport.x - this._positionX;
  14190. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  14191. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  14192. } else {
  14193. awayX = 0;
  14194. }
  14195. if (this._positionY < this.borderLimit + globalViewport.y) {
  14196. awayY = this.borderLimit + globalViewport.y - this._positionY;
  14197. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  14198. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  14199. } else {
  14200. awayY = 0;
  14201. }
  14202. var away = (awayX > awayY) ? awayX : awayY;
  14203. if (away > this.borderLimit) {
  14204. away = this.borderLimit;
  14205. }
  14206. var intensity = 1.0 - (away / this.borderLimit);
  14207. if (intensity < 0) {
  14208. return false;
  14209. }
  14210. if (intensity > 1.0) {
  14211. intensity = 1.0;
  14212. }
  14213. var centerX = globalViewport.x + globalViewport.width / 2;
  14214. var centerY = globalViewport.y + globalViewport.height / 2;
  14215. var distX = centerX - this._positionX;
  14216. var distY = centerY - this._positionY;
  14217. engine.enableEffect(this._effect);
  14218. engine.setState(false);
  14219. engine.setDepthBuffer(false);
  14220. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14221. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14222. for (var index = 0; index < this.lensFlares.length; index++) {
  14223. var flare = this.lensFlares[index];
  14224. var x = centerX - (distX * flare.position);
  14225. var y = centerY - (distY * flare.position);
  14226. var cw = flare.size;
  14227. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  14228. var cx = 2 * (x / globalViewport.width) - 1.0;
  14229. var cy = 1.0 - 2 * (y / globalViewport.height);
  14230. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  14231. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  14232. this._effect.setTexture("textureSampler", flare.texture);
  14233. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  14234. engine.draw(true, 0, 6);
  14235. }
  14236. engine.setDepthBuffer(true);
  14237. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14238. return true;
  14239. };
  14240. LensFlareSystem.prototype.dispose = function () {
  14241. if (this._vertexBuffer) {
  14242. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14243. this._vertexBuffer = null;
  14244. }
  14245. if (this._indexBuffer) {
  14246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14247. this._indexBuffer = null;
  14248. }
  14249. while (this.lensFlares.length) {
  14250. this.lensFlares[0].dispose();
  14251. }
  14252. var index = this._scene.lensFlareSystems.indexOf(this);
  14253. this._scene.lensFlareSystems.splice(index, 1);
  14254. };
  14255. return LensFlareSystem;
  14256. })();
  14257. BABYLON.LensFlareSystem = LensFlareSystem;
  14258. })(BABYLON || (BABYLON = {}));
  14259. var BABYLON;
  14260. (function (BABYLON) {
  14261. var IntersectionInfo = (function () {
  14262. function IntersectionInfo(bu, bv, distance) {
  14263. this.bu = bu;
  14264. this.bv = bv;
  14265. this.distance = distance;
  14266. this.faceId = 0;
  14267. }
  14268. return IntersectionInfo;
  14269. })();
  14270. BABYLON.IntersectionInfo = IntersectionInfo;
  14271. var PickingInfo = (function () {
  14272. function PickingInfo() {
  14273. this.hit = false;
  14274. this.distance = 0;
  14275. this.pickedPoint = null;
  14276. this.pickedMesh = null;
  14277. this.bu = 0;
  14278. this.bv = 0;
  14279. this.faceId = -1;
  14280. }
  14281. PickingInfo.prototype.getNormal = function () {
  14282. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14283. return null;
  14284. }
  14285. var indices = this.pickedMesh.getIndices();
  14286. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14287. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  14288. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  14289. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  14290. normal0 = normal0.scale(this.bu);
  14291. normal1 = normal1.scale(this.bv);
  14292. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  14293. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  14294. };
  14295. PickingInfo.prototype.getTextureCoordinates = function () {
  14296. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14297. return null;
  14298. }
  14299. var indices = this.pickedMesh.getIndices();
  14300. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14301. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  14302. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  14303. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  14304. uv0 = uv0.scale(this.bu);
  14305. uv1 = uv1.scale(this.bv);
  14306. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  14307. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  14308. };
  14309. return PickingInfo;
  14310. })();
  14311. BABYLON.PickingInfo = PickingInfo;
  14312. })(BABYLON || (BABYLON = {}));
  14313. var BABYLON;
  14314. (function (BABYLON) {
  14315. var FilesInput = (function () {
  14316. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  14317. this.engine = p_engine;
  14318. this.canvas = p_canvas;
  14319. this.currentScene = p_scene;
  14320. this.sceneLoadedCallback = p_sceneLoadedCallback;
  14321. this.progressCallback = p_progressCallback;
  14322. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  14323. this.textureLoadingCallback = p_textureLoadingCallback;
  14324. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  14325. }
  14326. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  14327. var _this = this;
  14328. if (p_elementToMonitor) {
  14329. this.elementToMonitor = p_elementToMonitor;
  14330. this.elementToMonitor.addEventListener("dragenter", function (e) {
  14331. _this.drag(e);
  14332. }, false);
  14333. this.elementToMonitor.addEventListener("dragover", function (e) {
  14334. _this.drag(e);
  14335. }, false);
  14336. this.elementToMonitor.addEventListener("drop", function (e) {
  14337. _this.drop(e);
  14338. }, false);
  14339. }
  14340. };
  14341. FilesInput.prototype.renderFunction = function () {
  14342. if (this.additionnalRenderLoopLogicCallback) {
  14343. this.additionnalRenderLoopLogicCallback();
  14344. }
  14345. if (this.currentScene) {
  14346. if (this.textureLoadingCallback) {
  14347. var remaining = this.currentScene.getWaitingItemsCount();
  14348. if (remaining > 0) {
  14349. this.textureLoadingCallback(remaining);
  14350. }
  14351. }
  14352. this.currentScene.render();
  14353. }
  14354. };
  14355. FilesInput.prototype.drag = function (e) {
  14356. e.stopPropagation();
  14357. e.preventDefault();
  14358. };
  14359. FilesInput.prototype.drop = function (eventDrop) {
  14360. eventDrop.stopPropagation();
  14361. eventDrop.preventDefault();
  14362. this.loadFiles(eventDrop);
  14363. };
  14364. FilesInput.prototype.loadFiles = function (event) {
  14365. var _this = this;
  14366. var that = this;
  14367. if (this.startingProcessingFilesCallback)
  14368. this.startingProcessingFilesCallback();
  14369. var sceneFileToLoad;
  14370. var filesToLoad;
  14371. if (event && event.dataTransfer && event.dataTransfer.files) {
  14372. filesToLoad = event.dataTransfer.files;
  14373. }
  14374. if (event && event.target && event.target.files) {
  14375. filesToLoad = event.target.files;
  14376. }
  14377. if (filesToLoad && filesToLoad.length > 0) {
  14378. for (var i = 0; i < filesToLoad.length; i++) {
  14379. switch (filesToLoad[i].type) {
  14380. case "image/jpeg":
  14381. case "image/png":
  14382. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  14383. break;
  14384. case "image/targa":
  14385. case "image/vnd.ms-dds":
  14386. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  14387. break;
  14388. default:
  14389. 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) {
  14390. sceneFileToLoad = filesToLoad[i];
  14391. }
  14392. break;
  14393. }
  14394. }
  14395. if (sceneFileToLoad) {
  14396. if (this.currentScene) {
  14397. this.engine.stopRenderLoop();
  14398. this.currentScene.dispose();
  14399. }
  14400. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  14401. that.currentScene = newScene;
  14402. that.currentScene.executeWhenReady(function () {
  14403. if (that.currentScene.activeCamera) {
  14404. that.currentScene.activeCamera.attachControl(that.canvas);
  14405. }
  14406. if (that.sceneLoadedCallback) {
  14407. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  14408. }
  14409. that.engine.runRenderLoop(function () {
  14410. that.renderFunction();
  14411. });
  14412. });
  14413. }, function (progress) {
  14414. if (_this.progressCallback) {
  14415. _this.progressCallback(progress);
  14416. }
  14417. });
  14418. } else {
  14419. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  14420. }
  14421. }
  14422. };
  14423. FilesInput.FilesTextures = new Array();
  14424. FilesInput.FilesToLoad = new Array();
  14425. return FilesInput;
  14426. })();
  14427. BABYLON.FilesInput = FilesInput;
  14428. })(BABYLON || (BABYLON = {}));
  14429. var BABYLON;
  14430. (function (BABYLON) {
  14431. var OimoJSPlugin = (function () {
  14432. function OimoJSPlugin() {
  14433. this._registeredMeshes = [];
  14434. /**
  14435. * Update the body position according to the mesh position
  14436. * @param mesh
  14437. */
  14438. this.updateBodyPosition = function (mesh) {
  14439. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14440. var registeredMesh = this._registeredMeshes[index];
  14441. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14442. var body = registeredMesh.body.body;
  14443. mesh.computeWorldMatrix(true);
  14444. var center = mesh.getBoundingInfo().boundingBox.center;
  14445. body.setPosition(center.x, center.y, center.z);
  14446. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  14447. return;
  14448. }
  14449. if (registeredMesh.mesh.parent === mesh) {
  14450. mesh.computeWorldMatrix(true);
  14451. registeredMesh.mesh.computeWorldMatrix(true);
  14452. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  14453. var absoluteRotation = mesh.rotation;
  14454. body = registeredMesh.body.body;
  14455. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  14456. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  14457. return;
  14458. }
  14459. }
  14460. };
  14461. }
  14462. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  14463. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  14464. };
  14465. OimoJSPlugin.prototype.initialize = function (iterations) {
  14466. this._world = new OIMO.World();
  14467. this._world.clear();
  14468. };
  14469. OimoJSPlugin.prototype.setGravity = function (gravity) {
  14470. this._world.gravity = gravity;
  14471. };
  14472. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  14473. var body = null;
  14474. this.unregisterMesh(mesh);
  14475. mesh.computeWorldMatrix(true);
  14476. switch (impostor) {
  14477. case BABYLON.PhysicsEngine.SphereImpostor:
  14478. var bbox = mesh.getBoundingInfo().boundingBox;
  14479. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14480. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14481. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14482. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14483. var deltaPosition = mesh.position.subtract(bbox.center);
  14484. body = new OIMO.Body({
  14485. type: 'sphere',
  14486. size: [size],
  14487. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14488. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14489. move: options.mass != 0,
  14490. config: [options.mass, options.friction, options.restitution],
  14491. world: this._world
  14492. });
  14493. this._registeredMeshes.push({
  14494. mesh: mesh,
  14495. body: body,
  14496. delta: deltaPosition
  14497. });
  14498. break;
  14499. case BABYLON.PhysicsEngine.PlaneImpostor:
  14500. case BABYLON.PhysicsEngine.BoxImpostor:
  14501. bbox = mesh.getBoundingInfo().boundingBox;
  14502. var min = bbox.minimumWorld;
  14503. var max = bbox.maximumWorld;
  14504. var box = max.subtract(min);
  14505. var sizeX = this._checkWithEpsilon(box.x);
  14506. var sizeY = this._checkWithEpsilon(box.y);
  14507. var sizeZ = this._checkWithEpsilon(box.z);
  14508. var deltaPosition = mesh.position.subtract(bbox.center);
  14509. body = new OIMO.Body({
  14510. type: 'box',
  14511. size: [sizeX, sizeY, sizeZ],
  14512. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  14513. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  14514. move: options.mass != 0,
  14515. config: [options.mass, options.friction, options.restitution],
  14516. world: this._world
  14517. });
  14518. this._registeredMeshes.push({
  14519. mesh: mesh,
  14520. body: body,
  14521. delta: deltaPosition
  14522. });
  14523. break;
  14524. }
  14525. return body;
  14526. };
  14527. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  14528. var types = [], sizes = [], positions = [], rotations = [];
  14529. var initialMesh = parts[0].mesh;
  14530. for (var index = 0; index < parts.length; index++) {
  14531. var part = parts[index];
  14532. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  14533. types.push(bodyParameters.type);
  14534. sizes.push.apply(sizes, bodyParameters.size);
  14535. positions.push.apply(positions, bodyParameters.pos);
  14536. rotations.push.apply(rotations, bodyParameters.rot);
  14537. }
  14538. var body = new OIMO.Body({
  14539. type: types,
  14540. size: sizes,
  14541. pos: positions,
  14542. rot: rotations,
  14543. move: options.mass != 0,
  14544. config: [options.mass, options.friction, options.restitution],
  14545. world: this._world
  14546. });
  14547. this._registeredMeshes.push({
  14548. mesh: initialMesh,
  14549. body: body
  14550. });
  14551. return body;
  14552. };
  14553. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  14554. var bodyParameters = null;
  14555. var mesh = part.mesh;
  14556. switch (part.impostor) {
  14557. case BABYLON.PhysicsEngine.SphereImpostor:
  14558. var bbox = mesh.getBoundingInfo().boundingBox;
  14559. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  14560. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  14561. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  14562. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  14563. bodyParameters = {
  14564. type: 'sphere',
  14565. /* bug with oimo : sphere needs 3 sizes in this case */
  14566. size: [size, -1, -1],
  14567. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  14568. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14569. };
  14570. break;
  14571. case BABYLON.PhysicsEngine.PlaneImpostor:
  14572. case BABYLON.PhysicsEngine.BoxImpostor:
  14573. bbox = mesh.getBoundingInfo().boundingBox;
  14574. var min = bbox.minimumWorld;
  14575. var max = bbox.maximumWorld;
  14576. var box = max.subtract(min);
  14577. var sizeX = this._checkWithEpsilon(box.x);
  14578. var sizeY = this._checkWithEpsilon(box.y);
  14579. var sizeZ = this._checkWithEpsilon(box.z);
  14580. var relativePosition = mesh.position;
  14581. bodyParameters = {
  14582. type: 'box',
  14583. size: [sizeX, sizeY, sizeZ],
  14584. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  14585. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  14586. };
  14587. break;
  14588. }
  14589. return bodyParameters;
  14590. };
  14591. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  14592. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14593. var registeredMesh = this._registeredMeshes[index];
  14594. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14595. if (registeredMesh.body) {
  14596. this._world.removeRigidBody(registeredMesh.body.body);
  14597. this._unbindBody(registeredMesh.body);
  14598. }
  14599. this._registeredMeshes.splice(index, 1);
  14600. return;
  14601. }
  14602. }
  14603. };
  14604. OimoJSPlugin.prototype._unbindBody = function (body) {
  14605. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14606. var registeredMesh = this._registeredMeshes[index];
  14607. if (registeredMesh.body === body) {
  14608. registeredMesh.body = null;
  14609. }
  14610. }
  14611. };
  14612. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  14613. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14614. var registeredMesh = this._registeredMeshes[index];
  14615. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  14616. var mass = registeredMesh.body.body.massInfo.mass;
  14617. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  14618. return;
  14619. }
  14620. }
  14621. };
  14622. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14623. var body1 = null, body2 = null;
  14624. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14625. var registeredMesh = this._registeredMeshes[index];
  14626. if (registeredMesh.mesh === mesh1) {
  14627. body1 = registeredMesh.body.body;
  14628. } else if (registeredMesh.mesh === mesh2) {
  14629. body2 = registeredMesh.body.body;
  14630. }
  14631. }
  14632. if (!body1 || !body2) {
  14633. return false;
  14634. }
  14635. if (!options) {
  14636. options = {};
  14637. }
  14638. new OIMO.Link({
  14639. type: options.type,
  14640. body1: body1,
  14641. body2: body2,
  14642. min: options.min,
  14643. max: options.max,
  14644. axe1: options.axe1,
  14645. axe2: options.axe2,
  14646. pos1: [pivot1.x, pivot1.y, pivot1.z],
  14647. pos2: [pivot2.x, pivot2.y, pivot2.z],
  14648. collision: options.collision,
  14649. spring: options.spring,
  14650. world: this._world
  14651. });
  14652. return true;
  14653. };
  14654. OimoJSPlugin.prototype.dispose = function () {
  14655. this._world.clear();
  14656. while (this._registeredMeshes.length) {
  14657. this.unregisterMesh(this._registeredMeshes[0].mesh);
  14658. }
  14659. };
  14660. OimoJSPlugin.prototype.isSupported = function () {
  14661. return OIMO !== undefined;
  14662. };
  14663. OimoJSPlugin.prototype._getLastShape = function (body) {
  14664. var lastShape = body.shapes;
  14665. while (lastShape.next) {
  14666. lastShape = lastShape.next;
  14667. }
  14668. return lastShape;
  14669. };
  14670. OimoJSPlugin.prototype.runOneStep = function (time) {
  14671. this._world.step();
  14672. var i = this._registeredMeshes.length;
  14673. var m;
  14674. while (i--) {
  14675. var body = this._registeredMeshes[i].body.body;
  14676. var mesh = this._registeredMeshes[i].mesh;
  14677. var delta = this._registeredMeshes[i].delta;
  14678. if (!body.sleeping) {
  14679. if (body.shapes.next) {
  14680. var parentShape = this._getLastShape(body);
  14681. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  14682. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  14683. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  14684. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  14685. if (!mesh.rotationQuaternion) {
  14686. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14687. }
  14688. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14689. } else {
  14690. m = body.getMatrix();
  14691. mtx = BABYLON.Matrix.FromArray(m);
  14692. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  14693. if (!delta) {
  14694. mesh.position.x = bodyX;
  14695. mesh.position.y = bodyY;
  14696. mesh.position.z = bodyZ;
  14697. } else {
  14698. mesh.position.x = bodyX + delta.x;
  14699. mesh.position.y = bodyY + delta.y;
  14700. mesh.position.z = bodyZ + delta.z;
  14701. }
  14702. if (!mesh.rotationQuaternion) {
  14703. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  14704. }
  14705. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  14706. }
  14707. }
  14708. }
  14709. };
  14710. return OimoJSPlugin;
  14711. })();
  14712. BABYLON.OimoJSPlugin = OimoJSPlugin;
  14713. })(BABYLON || (BABYLON = {}));
  14714. var BABYLON;
  14715. (function (BABYLON) {
  14716. var PhysicsEngine = (function () {
  14717. function PhysicsEngine(plugin) {
  14718. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  14719. }
  14720. PhysicsEngine.prototype._initialize = function (gravity) {
  14721. this._currentPlugin.initialize();
  14722. this._setGravity(gravity);
  14723. };
  14724. PhysicsEngine.prototype._runOneStep = function (delta) {
  14725. if (delta > 0.1) {
  14726. delta = 0.1;
  14727. } else if (delta <= 0) {
  14728. delta = 1.0 / 60.0;
  14729. }
  14730. this._currentPlugin.runOneStep(delta);
  14731. };
  14732. PhysicsEngine.prototype._setGravity = function (gravity) {
  14733. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  14734. this._currentPlugin.setGravity(this.gravity);
  14735. };
  14736. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  14737. return this._currentPlugin.registerMesh(mesh, impostor, options);
  14738. };
  14739. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  14740. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  14741. };
  14742. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  14743. this._currentPlugin.unregisterMesh(mesh);
  14744. };
  14745. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  14746. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  14747. };
  14748. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  14749. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  14750. };
  14751. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  14752. this._currentPlugin.updateBodyPosition(mesh);
  14753. };
  14754. PhysicsEngine.prototype.dispose = function () {
  14755. this._currentPlugin.dispose();
  14756. };
  14757. PhysicsEngine.prototype.isSupported = function () {
  14758. return this._currentPlugin.isSupported();
  14759. };
  14760. PhysicsEngine.NoImpostor = 0;
  14761. PhysicsEngine.SphereImpostor = 1;
  14762. PhysicsEngine.BoxImpostor = 2;
  14763. PhysicsEngine.PlaneImpostor = 3;
  14764. PhysicsEngine.MeshImpostor = 4;
  14765. PhysicsEngine.CapsuleImpostor = 5;
  14766. PhysicsEngine.ConeImpostor = 6;
  14767. PhysicsEngine.CylinderImpostor = 7;
  14768. PhysicsEngine.ConvexHullImpostor = 8;
  14769. PhysicsEngine.Epsilon = 0.001;
  14770. return PhysicsEngine;
  14771. })();
  14772. BABYLON.PhysicsEngine = PhysicsEngine;
  14773. })(BABYLON || (BABYLON = {}));
  14774. var BABYLON;
  14775. (function (BABYLON) {
  14776. var serializeLight = function (light) {
  14777. var serializationObject = {};
  14778. serializationObject.name = light.name;
  14779. serializationObject.id = light.id;
  14780. serializationObject.tags = BABYLON.Tags.GetTags(light);
  14781. if (light instanceof BABYLON.PointLight) {
  14782. serializationObject.type = 0;
  14783. serializationObject.position = light.position.asArray();
  14784. } else if (light instanceof BABYLON.DirectionalLight) {
  14785. serializationObject.type = 1;
  14786. var directionalLight = light;
  14787. serializationObject.position = directionalLight.position.asArray();
  14788. serializationObject.direction = directionalLight.direction.asArray();
  14789. } else if (light instanceof BABYLON.SpotLight) {
  14790. serializationObject.type = 2;
  14791. var spotLight = light;
  14792. serializationObject.position = spotLight.position.asArray();
  14793. serializationObject.direction = spotLight.position.asArray();
  14794. serializationObject.angle = spotLight.angle;
  14795. serializationObject.exponent = spotLight.exponent;
  14796. } else if (light instanceof BABYLON.HemisphericLight) {
  14797. serializationObject.type = 3;
  14798. var hemisphericLight = light;
  14799. serializationObject.direction = hemisphericLight.direction.asArray();
  14800. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  14801. }
  14802. if (light.intensity) {
  14803. serializationObject.intensity = light.intensity;
  14804. }
  14805. serializationObject.range = light.range;
  14806. serializationObject.diffuse = light.diffuse.asArray();
  14807. serializationObject.specular = light.specular.asArray();
  14808. return serializationObject;
  14809. };
  14810. var serializeFresnelParameter = function (fresnelParameter) {
  14811. var serializationObject = {};
  14812. serializationObject.isEnabled = fresnelParameter.isEnabled;
  14813. serializationObject.leftColor = fresnelParameter.leftColor;
  14814. serializationObject.rightColor = fresnelParameter.rightColor;
  14815. serializationObject.bias = fresnelParameter.bias;
  14816. serializationObject.power = fresnelParameter.power;
  14817. return serializationObject;
  14818. };
  14819. var serializeCamera = function (camera) {
  14820. var serializationObject = {};
  14821. serializationObject.name = camera.name;
  14822. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  14823. serializationObject.id = camera.id;
  14824. serializationObject.position = camera.position.asArray();
  14825. if (camera.parent) {
  14826. serializationObject.parentId = camera.parent.id;
  14827. }
  14828. serializationObject.rotation = camera.rotation.asArray();
  14829. if (camera.lockedTarget && camera.lockedTarget.id) {
  14830. serializationObject.lockedTargetId = camera.lockedTarget.id;
  14831. }
  14832. serializationObject.fov = camera.fov;
  14833. serializationObject.minZ = camera.minZ;
  14834. serializationObject.maxZ = camera.maxZ;
  14835. serializationObject.speed = camera.speed;
  14836. serializationObject.inertia = camera.inertia;
  14837. serializationObject.checkCollisions = camera.checkCollisions;
  14838. serializationObject.applyGravity = camera.applyGravity;
  14839. if (camera.ellipsoid) {
  14840. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  14841. }
  14842. appendAnimations(camera, serializationObject);
  14843. serializationObject.layerMask = camera.layerMask;
  14844. return serializationObject;
  14845. };
  14846. var appendAnimations = function (source, destination) {
  14847. if (source.animations) {
  14848. destination.animations = [];
  14849. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  14850. var animation = source.animations[animationIndex];
  14851. destination.animations.push(serializeAnimation(animation));
  14852. }
  14853. }
  14854. };
  14855. var serializeAnimation = function (animation) {
  14856. var serializationObject = {};
  14857. serializationObject.name = animation.name;
  14858. serializationObject.property = animation.targetProperty;
  14859. serializationObject.framePerSecond = animation.framePerSecond;
  14860. serializationObject.dataType = animation.dataType;
  14861. serializationObject.loopBehavior = animation.loopMode;
  14862. var dataType = animation.dataType;
  14863. serializationObject.keys = [];
  14864. var keys = animation.getKeys();
  14865. for (var index = 0; index < keys.length; index++) {
  14866. var animationKey = keys[index];
  14867. var key = {};
  14868. key.frame = animationKey.frame;
  14869. switch (dataType) {
  14870. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  14871. key.values = [animationKey.value];
  14872. break;
  14873. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  14874. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  14875. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  14876. key.values = animationKey.value.asArray();
  14877. break;
  14878. }
  14879. serializationObject.keys.push(key);
  14880. }
  14881. return serializationObject;
  14882. };
  14883. var serializeMultiMaterial = function (material) {
  14884. var serializationObject = {};
  14885. serializationObject.name = material.name;
  14886. serializationObject.id = material.id;
  14887. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14888. serializationObject.materials = [];
  14889. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  14890. var subMat = material.subMaterials[matIndex];
  14891. if (subMat) {
  14892. serializationObject.materials.push(subMat.id);
  14893. } else {
  14894. serializationObject.materials.push(null);
  14895. }
  14896. }
  14897. return serializationObject;
  14898. };
  14899. var serializeMaterial = function (material) {
  14900. var serializationObject = {};
  14901. serializationObject.name = material.name;
  14902. serializationObject.ambient = material.ambientColor.asArray();
  14903. serializationObject.diffuse = material.diffuseColor.asArray();
  14904. serializationObject.specular = material.specularColor.asArray();
  14905. serializationObject.specularPower = material.specularPower;
  14906. serializationObject.emissive = material.emissiveColor.asArray();
  14907. serializationObject.alpha = material.alpha;
  14908. serializationObject.id = material.id;
  14909. serializationObject.tags = BABYLON.Tags.GetTags(material);
  14910. serializationObject.backFaceCulling = material.backFaceCulling;
  14911. if (material.diffuseTexture) {
  14912. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  14913. }
  14914. if (material.diffuseFresnelParameters) {
  14915. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  14916. }
  14917. if (material.ambientTexture) {
  14918. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  14919. }
  14920. if (material.opacityTexture) {
  14921. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  14922. }
  14923. if (material.opacityFresnelParameters) {
  14924. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  14925. }
  14926. if (material.reflectionTexture) {
  14927. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  14928. }
  14929. if (material.reflectionFresnelParameters) {
  14930. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  14931. }
  14932. if (material.emissiveTexture) {
  14933. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  14934. }
  14935. if (material.emissiveFresnelParameters) {
  14936. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  14937. }
  14938. if (material.specularTexture) {
  14939. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  14940. }
  14941. if (material.bumpTexture) {
  14942. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  14943. }
  14944. return serializationObject;
  14945. };
  14946. var serializeTexture = function (texture) {
  14947. var serializationObject = {};
  14948. if (!texture.name) {
  14949. return null;
  14950. }
  14951. if (texture instanceof BABYLON.CubeTexture) {
  14952. serializationObject.name = texture.name;
  14953. serializationObject.hasAlpha = texture.hasAlpha;
  14954. serializationObject.level = texture.level;
  14955. serializationObject.coordinatesMode = texture.coordinatesMode;
  14956. return serializationObject;
  14957. }
  14958. if (texture instanceof BABYLON.MirrorTexture) {
  14959. var mirrorTexture = texture;
  14960. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  14961. serializationObject.renderList = [];
  14962. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  14963. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  14964. }
  14965. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  14966. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  14967. var renderTargetTexture = texture;
  14968. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  14969. serializationObject.renderList = [];
  14970. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  14971. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  14972. }
  14973. }
  14974. var regularTexture = texture;
  14975. serializationObject.name = texture.name;
  14976. serializationObject.hasAlpha = texture.hasAlpha;
  14977. serializationObject.level = texture.level;
  14978. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  14979. serializationObject.coordinatesMode = texture.coordinatesMode;
  14980. serializationObject.uOffset = regularTexture.uOffset;
  14981. serializationObject.vOffset = regularTexture.vOffset;
  14982. serializationObject.uScale = regularTexture.uScale;
  14983. serializationObject.vScale = regularTexture.vScale;
  14984. serializationObject.uAng = regularTexture.uAng;
  14985. serializationObject.vAng = regularTexture.vAng;
  14986. serializationObject.wAng = regularTexture.wAng;
  14987. serializationObject.wrapU = texture.wrapU;
  14988. serializationObject.wrapV = texture.wrapV;
  14989. appendAnimations(texture, serializationObject);
  14990. return serializationObject;
  14991. };
  14992. var serializeSkeleton = function (skeleton) {
  14993. var serializationObject = {};
  14994. serializationObject.name = skeleton.name;
  14995. serializationObject.id = skeleton.id;
  14996. serializationObject.bones = [];
  14997. for (var index = 0; index < skeleton.bones.length; index++) {
  14998. var bone = skeleton.bones[index];
  14999. var serializedBone = {
  15000. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  15001. name: bone.name,
  15002. matrix: bone.getLocalMatrix().toArray()
  15003. };
  15004. serializationObject.bones.push(serializedBone);
  15005. if (bone.animations && bone.animations.length > 0) {
  15006. serializedBone.animation = serializeAnimation(bone.animations[0]);
  15007. }
  15008. }
  15009. return serializationObject;
  15010. };
  15011. var serializeParticleSystem = function (particleSystem) {
  15012. var serializationObject = {};
  15013. serializationObject.emitterId = particleSystem.emitter.id;
  15014. serializationObject.capacity = particleSystem.getCapacity();
  15015. if (particleSystem.particleTexture) {
  15016. serializationObject.textureName = particleSystem.particleTexture.name;
  15017. }
  15018. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  15019. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  15020. serializationObject.minSize = particleSystem.minSize;
  15021. serializationObject.maxSize = particleSystem.maxSize;
  15022. serializationObject.minLifeTime = particleSystem.minLifeTime;
  15023. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  15024. serializationObject.emitRate = particleSystem.emitRate;
  15025. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  15026. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  15027. serializationObject.gravity = particleSystem.gravity.asArray();
  15028. serializationObject.direction1 = particleSystem.direction1.asArray();
  15029. serializationObject.direction2 = particleSystem.direction2.asArray();
  15030. serializationObject.color1 = particleSystem.color1.asArray();
  15031. serializationObject.color2 = particleSystem.color2.asArray();
  15032. serializationObject.colorDead = particleSystem.colorDead.asArray();
  15033. serializationObject.updateSpeed = particleSystem.updateSpeed;
  15034. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  15035. serializationObject.textureMask = particleSystem.textureMask.asArray();
  15036. serializationObject.blendMode = particleSystem.blendMode;
  15037. return serializationObject;
  15038. };
  15039. var serializeLensFlareSystem = function (lensFlareSystem) {
  15040. var serializationObject = {};
  15041. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  15042. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  15043. serializationObject.flares = [];
  15044. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  15045. var flare = lensFlareSystem.lensFlares[index];
  15046. serializationObject.flares.push({
  15047. size: flare.size,
  15048. position: flare.position,
  15049. color: flare.color.asArray(),
  15050. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  15051. });
  15052. }
  15053. return serializationObject;
  15054. };
  15055. var serializeShadowGenerator = function (light) {
  15056. var serializationObject = {};
  15057. var shadowGenerator = light.getShadowGenerator();
  15058. serializationObject.lightId = light.id;
  15059. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  15060. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  15061. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  15062. serializationObject.renderList = [];
  15063. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  15064. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  15065. serializationObject.renderList.push(mesh.id);
  15066. }
  15067. return serializationObject;
  15068. };
  15069. var serializedGeometries = [];
  15070. var serializeGeometry = function (geometry, serializationGeometries) {
  15071. if (serializedGeometries[geometry.id]) {
  15072. return;
  15073. }
  15074. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  15075. serializationGeometries.boxes.push(serializeBox(geometry));
  15076. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  15077. serializationGeometries.spheres.push(serializeSphere(geometry));
  15078. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  15079. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  15080. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  15081. serializationGeometries.toruses.push(serializeTorus(geometry));
  15082. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  15083. serializationGeometries.grounds.push(serializeGround(geometry));
  15084. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  15085. serializationGeometries.planes.push(serializePlane(geometry));
  15086. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  15087. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  15088. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  15089. throw new Error("Unknow primitive type");
  15090. } else {
  15091. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  15092. }
  15093. serializedGeometries[geometry.id] = true;
  15094. };
  15095. var serializeGeometryBase = function (geometry) {
  15096. var serializationObject = {};
  15097. serializationObject.id = geometry.id;
  15098. if (BABYLON.Tags.HasTags(geometry)) {
  15099. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  15100. }
  15101. return serializationObject;
  15102. };
  15103. var serializeVertexData = function (vertexData) {
  15104. var serializationObject = serializeGeometryBase(vertexData);
  15105. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15106. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15107. }
  15108. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15109. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15110. }
  15111. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15112. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15113. }
  15114. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15115. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15116. }
  15117. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15118. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15119. }
  15120. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15121. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15122. serializationObject.matricesIndices._isExpanded = true;
  15123. }
  15124. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15125. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15126. }
  15127. serializationObject.indices = vertexData.getIndices();
  15128. return serializationObject;
  15129. };
  15130. var serializePrimitive = function (primitive) {
  15131. var serializationObject = serializeGeometryBase(primitive);
  15132. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  15133. return serializationObject;
  15134. };
  15135. var serializeBox = function (box) {
  15136. var serializationObject = serializePrimitive(box);
  15137. serializationObject.size = box.size;
  15138. return serializationObject;
  15139. };
  15140. var serializeSphere = function (sphere) {
  15141. var serializationObject = serializePrimitive(sphere);
  15142. serializationObject.segments = sphere.segments;
  15143. serializationObject.diameter = sphere.diameter;
  15144. return serializationObject;
  15145. };
  15146. var serializeCylinder = function (cylinder) {
  15147. var serializationObject = serializePrimitive(cylinder);
  15148. serializationObject.height = cylinder.height;
  15149. serializationObject.diameterTop = cylinder.diameterTop;
  15150. serializationObject.diameterBottom = cylinder.diameterBottom;
  15151. serializationObject.tessellation = cylinder.tessellation;
  15152. return serializationObject;
  15153. };
  15154. var serializeTorus = function (torus) {
  15155. var serializationObject = serializePrimitive(torus);
  15156. serializationObject.diameter = torus.diameter;
  15157. serializationObject.thickness = torus.thickness;
  15158. serializationObject.tessellation = torus.tessellation;
  15159. return serializationObject;
  15160. };
  15161. var serializeGround = function (ground) {
  15162. var serializationObject = serializePrimitive(ground);
  15163. serializationObject.width = ground.width;
  15164. serializationObject.height = ground.height;
  15165. serializationObject.subdivisions = ground.subdivisions;
  15166. return serializationObject;
  15167. };
  15168. var serializePlane = function (plane) {
  15169. var serializationObject = serializePrimitive(plane);
  15170. serializationObject.size = plane.size;
  15171. return serializationObject;
  15172. };
  15173. var serializeTorusKnot = function (torusKnot) {
  15174. var serializationObject = serializePrimitive(torusKnot);
  15175. serializationObject.radius = torusKnot.radius;
  15176. serializationObject.tube = torusKnot.tube;
  15177. serializationObject.radialSegments = torusKnot.radialSegments;
  15178. serializationObject.tubularSegments = torusKnot.tubularSegments;
  15179. serializationObject.p = torusKnot.p;
  15180. serializationObject.q = torusKnot.q;
  15181. return serializationObject;
  15182. };
  15183. var serializeMesh = function (mesh, serializationScene) {
  15184. var serializationObject = {};
  15185. serializationObject.name = mesh.name;
  15186. serializationObject.id = mesh.id;
  15187. if (BABYLON.Tags.HasTags(mesh)) {
  15188. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  15189. }
  15190. serializationObject.position = mesh.position.asArray();
  15191. if (mesh.rotationQuaternion) {
  15192. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  15193. } else if (mesh.rotation) {
  15194. serializationObject.rotation = mesh.rotation.asArray();
  15195. }
  15196. serializationObject.scaling = mesh.scaling.asArray();
  15197. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  15198. serializationObject.isEnabled = mesh.isEnabled();
  15199. serializationObject.isVisible = mesh.isVisible;
  15200. serializationObject.infiniteDistance = mesh.infiniteDistance;
  15201. serializationObject.pickable = mesh.isPickable;
  15202. serializationObject.receiveShadows = mesh.receiveShadows;
  15203. serializationObject.billboardMode = mesh.billboardMode;
  15204. serializationObject.visibility = mesh.visibility;
  15205. serializationObject.checkCollisions = mesh.checkCollisions;
  15206. if (mesh.parent) {
  15207. serializationObject.parentId = mesh.parent.id;
  15208. }
  15209. var geometry = mesh._geometry;
  15210. if (geometry) {
  15211. var geometryId = geometry.id;
  15212. serializationObject.geometryId = geometryId;
  15213. if (!mesh.getScene().getGeometryByID(geometryId)) {
  15214. serializeGeometry(geometry, serializationScene.geometries);
  15215. }
  15216. serializationObject.subMeshes = [];
  15217. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15218. var subMesh = mesh.subMeshes[subIndex];
  15219. serializationObject.subMeshes.push({
  15220. materialIndex: subMesh.materialIndex,
  15221. verticesStart: subMesh.verticesStart,
  15222. verticesCount: subMesh.verticesCount,
  15223. indexStart: subMesh.indexStart,
  15224. indexCount: subMesh.indexCount
  15225. });
  15226. }
  15227. }
  15228. if (mesh.material) {
  15229. serializationObject.materialId = mesh.material.id;
  15230. } else {
  15231. mesh.material = null;
  15232. }
  15233. if (mesh.skeleton) {
  15234. serializationObject.skeletonId = mesh.skeleton.id;
  15235. }
  15236. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  15237. serializationObject.physicsMass = mesh.getPhysicsMass();
  15238. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  15239. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  15240. switch (mesh.getPhysicsImpostor()) {
  15241. case BABYLON.PhysicsEngine.BoxImpostor:
  15242. serializationObject.physicsImpostor = 1;
  15243. break;
  15244. case BABYLON.PhysicsEngine.SphereImpostor:
  15245. serializationObject.physicsImpostor = 2;
  15246. break;
  15247. }
  15248. }
  15249. serializationObject.instances = [];
  15250. for (var index = 0; index < mesh.instances.length; index++) {
  15251. var instance = mesh.instances[index];
  15252. var serializationInstance = {
  15253. name: instance.name,
  15254. position: instance.position,
  15255. rotation: instance.rotation,
  15256. rotationQuaternion: instance.rotationQuaternion,
  15257. scaling: instance.scaling
  15258. };
  15259. serializationObject.instances.push(serializationInstance);
  15260. appendAnimations(instance, serializationInstance);
  15261. }
  15262. appendAnimations(mesh, serializationObject);
  15263. serializationObject.layerMask = mesh.layerMask;
  15264. return serializationObject;
  15265. };
  15266. var SceneSerializer = (function () {
  15267. function SceneSerializer() {
  15268. }
  15269. SceneSerializer.Serialize = function (scene) {
  15270. var serializationObject = {};
  15271. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15272. serializationObject.autoClear = scene.autoClear;
  15273. serializationObject.clearColor = scene.clearColor.asArray();
  15274. serializationObject.ambientColor = scene.ambientColor.asArray();
  15275. serializationObject.gravity = scene.gravity.asArray();
  15276. if (scene.fogMode && scene.fogMode !== 0) {
  15277. serializationObject.fogMode = scene.fogMode;
  15278. serializationObject.fogColor = scene.fogColor.asArray();
  15279. serializationObject.fogStart = scene.fogStart;
  15280. serializationObject.fogEnd = scene.fogEnd;
  15281. serializationObject.fogDensity = scene.fogDensity;
  15282. }
  15283. serializationObject.lights = [];
  15284. for (var index = 0; index < scene.lights.length; index++) {
  15285. var light = scene.lights[index];
  15286. serializationObject.lights.push(serializeLight(light));
  15287. }
  15288. serializationObject.cameras = [];
  15289. for (index = 0; index < scene.cameras.length; index++) {
  15290. var camera = scene.cameras[index];
  15291. if (camera instanceof BABYLON.FreeCamera) {
  15292. serializationObject.cameras.push(serializeCamera(camera));
  15293. }
  15294. }
  15295. if (scene.activeCamera) {
  15296. serializationObject.activeCameraID = scene.activeCamera.id;
  15297. }
  15298. serializationObject.materials = [];
  15299. serializationObject.multiMaterials = [];
  15300. for (index = 0; index < scene.materials.length; index++) {
  15301. var material = scene.materials[index];
  15302. if (material instanceof BABYLON.StandardMaterial) {
  15303. serializationObject.materials.push(serializeMaterial(material));
  15304. } else if (material instanceof BABYLON.MultiMaterial) {
  15305. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15306. }
  15307. }
  15308. serializationObject.skeletons = [];
  15309. for (index = 0; index < scene.skeletons.length; index++) {
  15310. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15311. }
  15312. serializationObject.geometries = {};
  15313. serializationObject.geometries.boxes = [];
  15314. serializationObject.geometries.spheres = [];
  15315. serializationObject.geometries.cylinders = [];
  15316. serializationObject.geometries.toruses = [];
  15317. serializationObject.geometries.grounds = [];
  15318. serializationObject.geometries.planes = [];
  15319. serializationObject.geometries.torusKnots = [];
  15320. serializationObject.geometries.vertexData = [];
  15321. serializedGeometries = [];
  15322. var geometries = scene.getGeometries();
  15323. for (var index = 0; index < geometries.length; index++) {
  15324. var geometry = geometries[index];
  15325. if (geometry.isReady()) {
  15326. serializeGeometry(geometry, serializationObject.geometries);
  15327. }
  15328. }
  15329. serializationObject.meshes = [];
  15330. for (index = 0; index < scene.meshes.length; index++) {
  15331. var abstractMesh = scene.meshes[index];
  15332. if (abstractMesh instanceof BABYLON.Mesh) {
  15333. var mesh = abstractMesh;
  15334. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  15335. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  15336. }
  15337. }
  15338. }
  15339. serializationObject.particleSystems = [];
  15340. for (index = 0; index < scene.particleSystems.length; index++) {
  15341. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  15342. }
  15343. serializationObject.lensFlareSystems = [];
  15344. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  15345. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  15346. }
  15347. serializationObject.shadowGenerators = [];
  15348. for (index = 0; index < scene.lights.length; index++) {
  15349. light = scene.lights[index];
  15350. if (light.getShadowGenerator()) {
  15351. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  15352. }
  15353. }
  15354. return serializationObject;
  15355. };
  15356. return SceneSerializer;
  15357. })();
  15358. BABYLON.SceneSerializer = SceneSerializer;
  15359. })(BABYLON || (BABYLON = {}));
  15360. var BABYLON;
  15361. (function (BABYLON) {
  15362. var SceneLoader = (function () {
  15363. function SceneLoader() {
  15364. }
  15365. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  15366. get: function () {
  15367. return SceneLoader._ForceFullSceneLoadingForIncremental;
  15368. },
  15369. set: function (value) {
  15370. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  15371. },
  15372. enumerable: true,
  15373. configurable: true
  15374. });
  15375. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  15376. get: function () {
  15377. return SceneLoader._ShowLoadingScreen;
  15378. },
  15379. set: function (value) {
  15380. SceneLoader._ShowLoadingScreen = value;
  15381. },
  15382. enumerable: true,
  15383. configurable: true
  15384. });
  15385. SceneLoader._getPluginForFilename = function (sceneFilename) {
  15386. var dotPosition = sceneFilename.lastIndexOf(".");
  15387. var queryStringPosition = sceneFilename.indexOf("?");
  15388. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  15389. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15390. var plugin = this._registeredPlugins[index];
  15391. if (plugin.extensions.indexOf(extension) !== -1) {
  15392. return plugin;
  15393. }
  15394. }
  15395. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15396. };
  15397. SceneLoader.RegisterPlugin = function (plugin) {
  15398. plugin.extensions = plugin.extensions.toLowerCase();
  15399. SceneLoader._registeredPlugins.push(plugin);
  15400. };
  15401. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15402. var manifestChecked = function (success) {
  15403. scene.database = database;
  15404. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  15405. var importMeshFromData = function (data) {
  15406. var meshes = [];
  15407. var particleSystems = [];
  15408. var skeletons = [];
  15409. try {
  15410. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  15411. if (onerror) {
  15412. onerror(scene);
  15413. }
  15414. return;
  15415. }
  15416. } catch (e) {
  15417. if (onerror) {
  15418. onerror(scene);
  15419. }
  15420. return;
  15421. }
  15422. if (onsuccess) {
  15423. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  15424. onsuccess(meshes, particleSystems, skeletons);
  15425. }
  15426. };
  15427. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15428. importMeshFromData(sceneFilename.substr(5));
  15429. return;
  15430. }
  15431. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  15432. importMeshFromData(data);
  15433. }, progressCallBack, database);
  15434. };
  15435. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15436. };
  15437. /**
  15438. * Load a scene
  15439. * @param rootUrl a string that defines the root url for scene and resources
  15440. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15441. * @param engine is the instance of BABYLON.Engine to use to create the scene
  15442. */
  15443. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  15444. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  15445. };
  15446. /**
  15447. * Append a scene
  15448. * @param rootUrl a string that defines the root url for scene and resources
  15449. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  15450. * @param scene is the instance of BABYLON.Scene to append to
  15451. */
  15452. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  15453. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  15454. var database;
  15455. if (SceneLoader.ShowLoadingScreen) {
  15456. scene.getEngine().displayLoadingUI();
  15457. }
  15458. var loadSceneFromData = function (data) {
  15459. scene.database = database;
  15460. if (!plugin.load(scene, data, rootUrl)) {
  15461. if (onerror) {
  15462. onerror(scene);
  15463. }
  15464. scene.getEngine().hideLoadingUI();
  15465. return;
  15466. }
  15467. if (onsuccess) {
  15468. onsuccess(scene);
  15469. }
  15470. if (SceneLoader.ShowLoadingScreen) {
  15471. scene.executeWhenReady(function () {
  15472. scene.getEngine().hideLoadingUI();
  15473. });
  15474. }
  15475. };
  15476. var manifestChecked = function (success) {
  15477. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  15478. };
  15479. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  15480. loadSceneFromData(sceneFilename.substr(5));
  15481. return;
  15482. }
  15483. if (rootUrl.indexOf("file:") === -1) {
  15484. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  15485. } else {
  15486. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  15487. }
  15488. };
  15489. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  15490. SceneLoader._ShowLoadingScreen = true;
  15491. SceneLoader._registeredPlugins = new Array();
  15492. return SceneLoader;
  15493. })();
  15494. BABYLON.SceneLoader = SceneLoader;
  15495. ;
  15496. })(BABYLON || (BABYLON = {}));
  15497. var BABYLON;
  15498. (function (BABYLON) {
  15499. (function (Internals) {
  15500. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  15501. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  15502. texture.name = parsedTexture.name;
  15503. texture.hasAlpha = parsedTexture.hasAlpha;
  15504. texture.level = parsedTexture.level;
  15505. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15506. return texture;
  15507. };
  15508. var loadTexture = function (rootUrl, parsedTexture, scene) {
  15509. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  15510. return null;
  15511. }
  15512. if (parsedTexture.isCube) {
  15513. return loadCubeTexture(rootUrl, parsedTexture, scene);
  15514. }
  15515. var texture;
  15516. if (parsedTexture.mirrorPlane) {
  15517. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15518. texture._waitingRenderList = parsedTexture.renderList;
  15519. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  15520. } else if (parsedTexture.isRenderTarget) {
  15521. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  15522. texture._waitingRenderList = parsedTexture.renderList;
  15523. } else {
  15524. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  15525. }
  15526. texture.name = parsedTexture.name;
  15527. texture.hasAlpha = parsedTexture.hasAlpha;
  15528. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  15529. texture.level = parsedTexture.level;
  15530. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  15531. texture.coordinatesMode = parsedTexture.coordinatesMode;
  15532. texture.uOffset = parsedTexture.uOffset;
  15533. texture.vOffset = parsedTexture.vOffset;
  15534. texture.uScale = parsedTexture.uScale;
  15535. texture.vScale = parsedTexture.vScale;
  15536. texture.uAng = parsedTexture.uAng;
  15537. texture.vAng = parsedTexture.vAng;
  15538. texture.wAng = parsedTexture.wAng;
  15539. texture.wrapU = parsedTexture.wrapU;
  15540. texture.wrapV = parsedTexture.wrapV;
  15541. if (parsedTexture.animations) {
  15542. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  15543. var parsedAnimation = parsedTexture.animations[animationIndex];
  15544. texture.animations.push(parseAnimation(parsedAnimation));
  15545. }
  15546. }
  15547. return texture;
  15548. };
  15549. var parseSkeleton = function (parsedSkeleton, scene) {
  15550. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  15551. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  15552. var parsedBone = parsedSkeleton.bones[index];
  15553. var parentBone = null;
  15554. if (parsedBone.parentBoneIndex > -1) {
  15555. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  15556. }
  15557. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  15558. if (parsedBone.animation) {
  15559. bone.animations.push(parseAnimation(parsedBone.animation));
  15560. }
  15561. }
  15562. return skeleton;
  15563. };
  15564. var parseFresnelParameters = function (parsedFresnelParameters) {
  15565. var fresnelParameters = new BABYLON.FresnelParameters();
  15566. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  15567. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  15568. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  15569. fresnelParameters.bias = parsedFresnelParameters.bias;
  15570. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  15571. return fresnelParameters;
  15572. };
  15573. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  15574. var material;
  15575. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  15576. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  15577. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  15578. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  15579. material.specularPower = parsedMaterial.specularPower;
  15580. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  15581. material.alpha = parsedMaterial.alpha;
  15582. material.id = parsedMaterial.id;
  15583. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  15584. material.backFaceCulling = parsedMaterial.backFaceCulling;
  15585. material.wireframe = parsedMaterial.wireframe;
  15586. if (parsedMaterial.diffuseTexture) {
  15587. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  15588. }
  15589. if (parsedMaterial.diffuseFresnelParameters) {
  15590. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  15591. }
  15592. if (parsedMaterial.ambientTexture) {
  15593. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  15594. }
  15595. if (parsedMaterial.opacityTexture) {
  15596. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  15597. }
  15598. if (parsedMaterial.opacityFresnelParameters) {
  15599. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  15600. }
  15601. if (parsedMaterial.reflectionTexture) {
  15602. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  15603. }
  15604. if (parsedMaterial.reflectionFresnelParameters) {
  15605. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  15606. }
  15607. if (parsedMaterial.emissiveTexture) {
  15608. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  15609. }
  15610. if (parsedMaterial.emissiveFresnelParameters) {
  15611. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  15612. }
  15613. if (parsedMaterial.specularTexture) {
  15614. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  15615. }
  15616. if (parsedMaterial.bumpTexture) {
  15617. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  15618. }
  15619. return material;
  15620. };
  15621. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  15622. for (var index = 0; index < parsedData.materials.length; index++) {
  15623. var parsedMaterial = parsedData.materials[index];
  15624. if (parsedMaterial.id === id) {
  15625. return parseMaterial(parsedMaterial, scene, rootUrl);
  15626. }
  15627. }
  15628. return null;
  15629. };
  15630. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  15631. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  15632. multiMaterial.id = parsedMultiMaterial.id;
  15633. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  15634. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  15635. var subMatId = parsedMultiMaterial.materials[matIndex];
  15636. if (subMatId) {
  15637. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  15638. } else {
  15639. multiMaterial.subMaterials.push(null);
  15640. }
  15641. }
  15642. return multiMaterial;
  15643. };
  15644. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  15645. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  15646. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  15647. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  15648. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  15649. var parsedFlare = parsedLensFlareSystem.flares[index];
  15650. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  15651. }
  15652. return lensFlareSystem;
  15653. };
  15654. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  15655. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  15656. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  15657. if (parsedParticleSystem.textureName) {
  15658. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  15659. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  15660. }
  15661. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  15662. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  15663. particleSystem.minSize = parsedParticleSystem.minSize;
  15664. particleSystem.maxSize = parsedParticleSystem.maxSize;
  15665. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  15666. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  15667. particleSystem.emitter = emitter;
  15668. particleSystem.emitRate = parsedParticleSystem.emitRate;
  15669. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  15670. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  15671. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  15672. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  15673. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  15674. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  15675. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  15676. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  15677. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  15678. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  15679. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  15680. particleSystem.blendMode = parsedParticleSystem.blendMode;
  15681. particleSystem.start();
  15682. return particleSystem;
  15683. };
  15684. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  15685. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15686. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15687. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15688. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  15689. shadowGenerator.getShadowMap().renderList.push(mesh);
  15690. }
  15691. if (parsedShadowGenerator.usePoissonSampling) {
  15692. shadowGenerator.usePoissonSampling = true;
  15693. } else {
  15694. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  15695. }
  15696. return shadowGenerator;
  15697. };
  15698. var parseAnimation = function (parsedAnimation) {
  15699. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  15700. var dataType = parsedAnimation.dataType;
  15701. var keys = [];
  15702. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  15703. var key = parsedAnimation.keys[index];
  15704. var data;
  15705. switch (dataType) {
  15706. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15707. data = key.values[0];
  15708. break;
  15709. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15710. data = BABYLON.Quaternion.FromArray(key.values);
  15711. break;
  15712. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15713. data = BABYLON.Matrix.FromArray(key.values);
  15714. break;
  15715. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15716. default:
  15717. data = BABYLON.Vector3.FromArray(key.values);
  15718. break;
  15719. }
  15720. keys.push({
  15721. frame: key.frame,
  15722. value: data
  15723. });
  15724. }
  15725. animation.setKeys(keys);
  15726. return animation;
  15727. };
  15728. var parseLight = function (parsedLight, scene) {
  15729. var light;
  15730. switch (parsedLight.type) {
  15731. case 0:
  15732. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  15733. break;
  15734. case 1:
  15735. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15736. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  15737. break;
  15738. case 2:
  15739. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  15740. break;
  15741. case 3:
  15742. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  15743. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  15744. break;
  15745. }
  15746. light.id = parsedLight.id;
  15747. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  15748. if (parsedLight.intensity !== undefined) {
  15749. light.intensity = parsedLight.intensity;
  15750. }
  15751. if (parsedLight.range) {
  15752. light.range = parsedLight.range;
  15753. }
  15754. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  15755. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  15756. if (parsedLight.excludedMeshesIds) {
  15757. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15758. }
  15759. if (parsedLight.parentId) {
  15760. light._waitingParentId = parsedLight.parentId;
  15761. }
  15762. if (parsedLight.includedOnlyMeshesIds) {
  15763. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15764. }
  15765. if (parsedLight.animations) {
  15766. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15767. var parsedAnimation = parsedLight.animations[animationIndex];
  15768. light.animations.push(parseAnimation(parsedAnimation));
  15769. }
  15770. }
  15771. if (parsedLight.autoAnimate) {
  15772. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  15773. }
  15774. };
  15775. var parseCamera = function (parsedCamera, scene) {
  15776. var camera;
  15777. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  15778. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  15779. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  15780. var alpha = parsedCamera.alpha;
  15781. var beta = parsedCamera.beta;
  15782. var radius = parsedCamera.radius;
  15783. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  15784. var eye_space = parsedCamera.eye_space;
  15785. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  15786. } else {
  15787. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  15788. }
  15789. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  15790. var eye_space = parsedCamera.eye_space;
  15791. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  15792. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  15793. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  15794. } else if (parsedCamera.type === "FollowCamera") {
  15795. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  15796. camera.heightOffset = parsedCamera.heightOffset;
  15797. camera.radius = parsedCamera.radius;
  15798. camera.rotationOffset = parsedCamera.rotationOffset;
  15799. if (lockedTargetMesh)
  15800. camera.target = lockedTargetMesh;
  15801. } else if (parsedCamera.type === "GamepadCamera") {
  15802. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  15803. } else if (parsedCamera.type === "OculusCamera") {
  15804. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  15805. } else if (parsedCamera.type === "TouchCamera") {
  15806. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  15807. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  15808. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  15809. } else if (parsedCamera.type === "WebVRCamera") {
  15810. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  15811. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  15812. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  15813. } else {
  15814. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  15815. }
  15816. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  15817. camera.lockedTarget = lockedTargetMesh;
  15818. }
  15819. camera.id = parsedCamera.id;
  15820. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  15821. if (parsedCamera.parentId) {
  15822. camera._waitingParentId = parsedCamera.parentId;
  15823. }
  15824. if (parsedCamera.target) {
  15825. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15826. } else {
  15827. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  15828. }
  15829. camera.fov = parsedCamera.fov;
  15830. camera.minZ = parsedCamera.minZ;
  15831. camera.maxZ = parsedCamera.maxZ;
  15832. camera.speed = parsedCamera.speed;
  15833. camera.inertia = parsedCamera.inertia;
  15834. camera.checkCollisions = parsedCamera.checkCollisions;
  15835. camera.applyGravity = parsedCamera.applyGravity;
  15836. if (parsedCamera.ellipsoid) {
  15837. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  15838. }
  15839. if (parsedCamera.animations) {
  15840. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15841. var parsedAnimation = parsedCamera.animations[animationIndex];
  15842. camera.animations.push(parseAnimation(parsedAnimation));
  15843. }
  15844. }
  15845. if (parsedCamera.autoAnimate) {
  15846. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  15847. }
  15848. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  15849. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  15850. } else {
  15851. camera.layerMask = 0xFFFFFFFF;
  15852. }
  15853. return camera;
  15854. };
  15855. var parseGeometry = function (parsedGeometry, scene) {
  15856. var id = parsedGeometry.id;
  15857. return scene.getGeometryByID(id);
  15858. };
  15859. var parseBox = function (parsedBox, scene) {
  15860. if (parseGeometry(parsedBox, scene)) {
  15861. return null;
  15862. }
  15863. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  15864. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  15865. scene.pushGeometry(box, true);
  15866. return box;
  15867. };
  15868. var parseSphere = function (parsedSphere, scene) {
  15869. if (parseGeometry(parsedSphere, scene)) {
  15870. return null;
  15871. }
  15872. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  15873. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  15874. scene.pushGeometry(sphere, true);
  15875. return sphere;
  15876. };
  15877. var parseCylinder = function (parsedCylinder, scene) {
  15878. if (parseGeometry(parsedCylinder, scene)) {
  15879. return null;
  15880. }
  15881. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  15882. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  15883. scene.pushGeometry(cylinder, true);
  15884. return cylinder;
  15885. };
  15886. var parseTorus = function (parsedTorus, scene) {
  15887. if (parseGeometry(parsedTorus, scene)) {
  15888. return null;
  15889. }
  15890. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  15891. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  15892. scene.pushGeometry(torus, true);
  15893. return torus;
  15894. };
  15895. var parseGround = function (parsedGround, scene) {
  15896. if (parseGeometry(parsedGround, scene)) {
  15897. return null;
  15898. }
  15899. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  15900. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  15901. scene.pushGeometry(ground, true);
  15902. return ground;
  15903. };
  15904. var parsePlane = function (parsedPlane, scene) {
  15905. if (parseGeometry(parsedPlane, scene)) {
  15906. return null;
  15907. }
  15908. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  15909. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  15910. scene.pushGeometry(plane, true);
  15911. return plane;
  15912. };
  15913. var parseTorusKnot = function (parsedTorusKnot, scene) {
  15914. if (parseGeometry(parsedTorusKnot, scene)) {
  15915. return null;
  15916. }
  15917. 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);
  15918. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  15919. scene.pushGeometry(torusKnot, true);
  15920. return torusKnot;
  15921. };
  15922. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  15923. if (parseGeometry(parsedVertexData, scene)) {
  15924. return null;
  15925. }
  15926. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  15927. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  15928. if (parsedVertexData.delayLoadingFile) {
  15929. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15930. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  15931. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  15932. geometry._delayInfo = [];
  15933. if (parsedVertexData.hasUVs) {
  15934. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15935. }
  15936. if (parsedVertexData.hasUVs2) {
  15937. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15938. }
  15939. if (parsedVertexData.hasColors) {
  15940. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15941. }
  15942. if (parsedVertexData.hasMatricesIndices) {
  15943. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15944. }
  15945. if (parsedVertexData.hasMatricesWeights) {
  15946. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15947. }
  15948. geometry._delayLoadingFunction = importVertexData;
  15949. } else {
  15950. importVertexData(parsedVertexData, geometry);
  15951. }
  15952. scene.pushGeometry(geometry, true);
  15953. return geometry;
  15954. };
  15955. var parseMesh = function (parsedMesh, scene, rootUrl) {
  15956. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  15957. mesh.id = parsedMesh.id;
  15958. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15959. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15960. if (parsedMesh.rotationQuaternion) {
  15961. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15962. } else if (parsedMesh.rotation) {
  15963. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15964. }
  15965. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15966. if (parsedMesh.localMatrix) {
  15967. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15968. } else if (parsedMesh.pivotMatrix) {
  15969. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15970. }
  15971. mesh.setEnabled(parsedMesh.isEnabled);
  15972. mesh.isVisible = parsedMesh.isVisible;
  15973. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15974. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15975. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15976. if (parsedMesh.pickable !== undefined) {
  15977. mesh.isPickable = parsedMesh.pickable;
  15978. }
  15979. mesh.receiveShadows = parsedMesh.receiveShadows;
  15980. mesh.billboardMode = parsedMesh.billboardMode;
  15981. if (parsedMesh.visibility !== undefined) {
  15982. mesh.visibility = parsedMesh.visibility;
  15983. }
  15984. mesh.checkCollisions = parsedMesh.checkCollisions;
  15985. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15986. if (parsedMesh.parentId) {
  15987. mesh._waitingParentId = parsedMesh.parentId;
  15988. }
  15989. if (parsedMesh.delayLoadingFile) {
  15990. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15991. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15992. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15993. if (parsedMesh._binaryInfo) {
  15994. mesh._binaryInfo = parsedMesh._binaryInfo;
  15995. }
  15996. mesh._delayInfo = [];
  15997. if (parsedMesh.hasUVs) {
  15998. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15999. }
  16000. if (parsedMesh.hasUVs2) {
  16001. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16002. }
  16003. if (parsedMesh.hasColors) {
  16004. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16005. }
  16006. if (parsedMesh.hasMatricesIndices) {
  16007. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16008. }
  16009. if (parsedMesh.hasMatricesWeights) {
  16010. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16011. }
  16012. mesh._delayLoadingFunction = importGeometry;
  16013. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16014. mesh._checkDelayState();
  16015. }
  16016. } else {
  16017. importGeometry(parsedMesh, mesh);
  16018. }
  16019. if (parsedMesh.materialId) {
  16020. mesh.setMaterialByID(parsedMesh.materialId);
  16021. } else {
  16022. mesh.material = null;
  16023. }
  16024. if (parsedMesh.skeletonId > -1) {
  16025. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16026. }
  16027. if (parsedMesh.physicsImpostor) {
  16028. if (!scene.isPhysicsEnabled()) {
  16029. scene.enablePhysics();
  16030. }
  16031. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16032. }
  16033. if (parsedMesh.animations) {
  16034. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16035. var parsedAnimation = parsedMesh.animations[animationIndex];
  16036. mesh.animations.push(parseAnimation(parsedAnimation));
  16037. }
  16038. }
  16039. if (parsedMesh.autoAnimate) {
  16040. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16041. }
  16042. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16043. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16044. } else {
  16045. mesh.layerMask = 0xFFFFFFFF;
  16046. }
  16047. if (parsedMesh.instances) {
  16048. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16049. var parsedInstance = parsedMesh.instances[index];
  16050. var instance = mesh.createInstance(parsedInstance.name);
  16051. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16052. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16053. if (parsedInstance.rotationQuaternion) {
  16054. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16055. } else if (parsedInstance.rotation) {
  16056. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16057. }
  16058. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16059. instance.checkCollisions = mesh.checkCollisions;
  16060. if (parsedMesh.animations) {
  16061. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16062. parsedAnimation = parsedMesh.animations[animationIndex];
  16063. instance.animations.push(parseAnimation(parsedAnimation));
  16064. }
  16065. }
  16066. }
  16067. }
  16068. return mesh;
  16069. };
  16070. var isDescendantOf = function (mesh, names, hierarchyIds) {
  16071. names = (names instanceof Array) ? names : [names];
  16072. for (var i in names) {
  16073. if (mesh.name === names[i]) {
  16074. hierarchyIds.push(mesh.id);
  16075. return true;
  16076. }
  16077. }
  16078. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  16079. hierarchyIds.push(mesh.id);
  16080. return true;
  16081. }
  16082. return false;
  16083. };
  16084. var importVertexData = function (parsedVertexData, geometry) {
  16085. var vertexData = new BABYLON.VertexData();
  16086. var positions = parsedVertexData.positions;
  16087. if (positions) {
  16088. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  16089. }
  16090. var normals = parsedVertexData.normals;
  16091. if (normals) {
  16092. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  16093. }
  16094. var uvs = parsedVertexData.uvs;
  16095. if (uvs) {
  16096. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  16097. }
  16098. var uv2s = parsedVertexData.uv2s;
  16099. if (uv2s) {
  16100. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  16101. }
  16102. var colors = parsedVertexData.colors;
  16103. if (colors) {
  16104. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  16105. }
  16106. var matricesIndices = parsedVertexData.matricesIndices;
  16107. if (matricesIndices) {
  16108. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  16109. }
  16110. var matricesWeights = parsedVertexData.matricesWeights;
  16111. if (matricesWeights) {
  16112. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  16113. }
  16114. var indices = parsedVertexData.indices;
  16115. if (indices) {
  16116. vertexData.indices = indices;
  16117. }
  16118. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  16119. };
  16120. var importGeometry = function (parsedGeometry, mesh) {
  16121. var scene = mesh.getScene();
  16122. var geometryId = parsedGeometry.geometryId;
  16123. if (geometryId) {
  16124. var geometry = scene.getGeometryByID(geometryId);
  16125. if (geometry) {
  16126. geometry.applyToMesh(mesh);
  16127. }
  16128. } else if (parsedGeometry instanceof ArrayBuffer) {
  16129. var binaryInfo = mesh._binaryInfo;
  16130. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  16131. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  16132. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  16133. }
  16134. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  16135. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  16136. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  16137. }
  16138. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  16139. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  16140. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  16141. }
  16142. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  16143. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  16144. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  16145. }
  16146. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  16147. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  16148. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  16149. }
  16150. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  16151. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  16152. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  16153. }
  16154. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  16155. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  16156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  16157. }
  16158. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  16159. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  16160. mesh.setIndices(indicesData);
  16161. }
  16162. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  16163. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  16164. mesh.subMeshes = [];
  16165. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  16166. var materialIndex = subMeshesData[(i * 5) + 0];
  16167. var verticesStart = subMeshesData[(i * 5) + 1];
  16168. var verticesCount = subMeshesData[(i * 5) + 2];
  16169. var indexStart = subMeshesData[(i * 5) + 3];
  16170. var indexCount = subMeshesData[(i * 5) + 4];
  16171. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  16172. }
  16173. }
  16174. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  16175. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  16176. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  16177. if (parsedGeometry.uvs) {
  16178. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  16179. }
  16180. if (parsedGeometry.uvs2) {
  16181. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  16182. }
  16183. if (parsedGeometry.colors) {
  16184. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, parsedGeometry.colors, false);
  16185. }
  16186. if (parsedGeometry.matricesIndices) {
  16187. if (!parsedGeometry.matricesIndices._isExpanded) {
  16188. var floatIndices = [];
  16189. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  16190. var matricesIndex = parsedGeometry.matricesIndices[i];
  16191. floatIndices.push(matricesIndex & 0x000000FF);
  16192. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  16193. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  16194. floatIndices.push(matricesIndex >> 24);
  16195. }
  16196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  16197. } else {
  16198. delete parsedGeometry.matricesIndices._isExpanded;
  16199. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  16200. }
  16201. }
  16202. if (parsedGeometry.matricesWeights) {
  16203. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  16204. }
  16205. mesh.setIndices(parsedGeometry.indices);
  16206. if (parsedGeometry.subMeshes) {
  16207. mesh.subMeshes = [];
  16208. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  16209. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  16210. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  16211. }
  16212. }
  16213. }
  16214. if (mesh._shouldGenerateFlatShading) {
  16215. mesh.convertToFlatShadedMesh();
  16216. delete mesh._shouldGenerateFlatShading;
  16217. }
  16218. mesh.computeWorldMatrix(true);
  16219. if (scene._selectionOctree) {
  16220. scene._selectionOctree.addMesh(mesh);
  16221. }
  16222. };
  16223. BABYLON.SceneLoader.RegisterPlugin({
  16224. extensions: ".babylon",
  16225. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  16226. var parsedData = JSON.parse(data);
  16227. var loadedSkeletonsIds = [];
  16228. var loadedMaterialsIds = [];
  16229. var hierarchyIds = [];
  16230. for (var index = 0; index < parsedData.meshes.length; index++) {
  16231. var parsedMesh = parsedData.meshes[index];
  16232. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  16233. if (meshesNames instanceof Array) {
  16234. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  16235. }
  16236. if (parsedMesh.materialId) {
  16237. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  16238. if (!materialFound) {
  16239. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  16240. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  16241. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  16242. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16243. var subMatId = parsedMultiMaterial.materials[matIndex];
  16244. loadedMaterialsIds.push(subMatId);
  16245. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  16246. }
  16247. loadedMaterialsIds.push(parsedMultiMaterial.id);
  16248. parseMultiMaterial(parsedMultiMaterial, scene);
  16249. materialFound = true;
  16250. break;
  16251. }
  16252. }
  16253. }
  16254. if (!materialFound) {
  16255. loadedMaterialsIds.push(parsedMesh.materialId);
  16256. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  16257. }
  16258. }
  16259. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  16260. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  16261. if (!skeletonAlreadyLoaded) {
  16262. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  16263. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  16264. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  16265. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  16266. loadedSkeletonsIds.push(parsedSkeleton.id);
  16267. }
  16268. }
  16269. }
  16270. }
  16271. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  16272. meshes.push(mesh);
  16273. }
  16274. }
  16275. for (index = 0; index < scene.meshes.length; index++) {
  16276. var currentMesh = scene.meshes[index];
  16277. if (currentMesh._waitingParentId) {
  16278. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  16279. currentMesh._waitingParentId = undefined;
  16280. }
  16281. }
  16282. if (parsedData.particleSystems) {
  16283. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16284. var parsedParticleSystem = parsedData.particleSystems[index];
  16285. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  16286. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  16287. }
  16288. }
  16289. }
  16290. return true;
  16291. },
  16292. load: function (scene, data, rootUrl) {
  16293. var parsedData = JSON.parse(data);
  16294. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  16295. scene.autoClear = parsedData.autoClear;
  16296. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  16297. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  16298. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  16299. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  16300. scene.fogMode = parsedData.fogMode;
  16301. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  16302. scene.fogStart = parsedData.fogStart;
  16303. scene.fogEnd = parsedData.fogEnd;
  16304. scene.fogDensity = parsedData.fogDensity;
  16305. }
  16306. for (var index = 0; index < parsedData.lights.length; index++) {
  16307. var parsedLight = parsedData.lights[index];
  16308. parseLight(parsedLight, scene);
  16309. }
  16310. if (parsedData.materials) {
  16311. for (index = 0; index < parsedData.materials.length; index++) {
  16312. var parsedMaterial = parsedData.materials[index];
  16313. parseMaterial(parsedMaterial, scene, rootUrl);
  16314. }
  16315. }
  16316. if (parsedData.multiMaterials) {
  16317. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  16318. var parsedMultiMaterial = parsedData.multiMaterials[index];
  16319. parseMultiMaterial(parsedMultiMaterial, scene);
  16320. }
  16321. }
  16322. if (parsedData.skeletons) {
  16323. for (index = 0; index < parsedData.skeletons.length; index++) {
  16324. var parsedSkeleton = parsedData.skeletons[index];
  16325. parseSkeleton(parsedSkeleton, scene);
  16326. }
  16327. }
  16328. var geometries = parsedData.geometries;
  16329. if (geometries) {
  16330. var boxes = geometries.boxes;
  16331. if (boxes) {
  16332. for (index = 0; index < boxes.length; index++) {
  16333. var parsedBox = boxes[index];
  16334. parseBox(parsedBox, scene);
  16335. }
  16336. }
  16337. var spheres = geometries.spheres;
  16338. if (spheres) {
  16339. for (index = 0; index < spheres.length; index++) {
  16340. var parsedSphere = spheres[index];
  16341. parseSphere(parsedSphere, scene);
  16342. }
  16343. }
  16344. var cylinders = geometries.cylinders;
  16345. if (cylinders) {
  16346. for (index = 0; index < cylinders.length; index++) {
  16347. var parsedCylinder = cylinders[index];
  16348. parseCylinder(parsedCylinder, scene);
  16349. }
  16350. }
  16351. var toruses = geometries.toruses;
  16352. if (toruses) {
  16353. for (index = 0; index < toruses.length; index++) {
  16354. var parsedTorus = toruses[index];
  16355. parseTorus(parsedTorus, scene);
  16356. }
  16357. }
  16358. var grounds = geometries.grounds;
  16359. if (grounds) {
  16360. for (index = 0; index < grounds.length; index++) {
  16361. var parsedGround = grounds[index];
  16362. parseGround(parsedGround, scene);
  16363. }
  16364. }
  16365. var planes = geometries.planes;
  16366. if (planes) {
  16367. for (index = 0; index < planes.length; index++) {
  16368. var parsedPlane = planes[index];
  16369. parsePlane(parsedPlane, scene);
  16370. }
  16371. }
  16372. var torusKnots = geometries.torusKnots;
  16373. if (torusKnots) {
  16374. for (index = 0; index < torusKnots.length; index++) {
  16375. var parsedTorusKnot = torusKnots[index];
  16376. parseTorusKnot(parsedTorusKnot, scene);
  16377. }
  16378. }
  16379. var vertexData = geometries.vertexData;
  16380. if (vertexData) {
  16381. for (index = 0; index < vertexData.length; index++) {
  16382. var parsedVertexData = vertexData[index];
  16383. parseVertexData(parsedVertexData, scene, rootUrl);
  16384. }
  16385. }
  16386. }
  16387. for (index = 0; index < parsedData.meshes.length; index++) {
  16388. var parsedMesh = parsedData.meshes[index];
  16389. parseMesh(parsedMesh, scene, rootUrl);
  16390. }
  16391. for (index = 0; index < parsedData.cameras.length; index++) {
  16392. var parsedCamera = parsedData.cameras[index];
  16393. parseCamera(parsedCamera, scene);
  16394. }
  16395. if (parsedData.activeCameraID) {
  16396. scene.setActiveCameraByID(parsedData.activeCameraID);
  16397. }
  16398. for (index = 0; index < scene.cameras.length; index++) {
  16399. var camera = scene.cameras[index];
  16400. if (camera._waitingParentId) {
  16401. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  16402. camera._waitingParentId = undefined;
  16403. }
  16404. }
  16405. for (index = 0; index < scene.lights.length; index++) {
  16406. var light = scene.lights[index];
  16407. if (light._waitingParentId) {
  16408. light.parent = scene.getLastEntryByID(light._waitingParentId);
  16409. light._waitingParentId = undefined;
  16410. }
  16411. }
  16412. for (index = 0; index < scene.meshes.length; index++) {
  16413. var mesh = scene.meshes[index];
  16414. if (mesh._waitingParentId) {
  16415. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  16416. mesh._waitingParentId = undefined;
  16417. }
  16418. }
  16419. if (parsedData.particleSystems) {
  16420. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16421. var parsedParticleSystem = parsedData.particleSystems[index];
  16422. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  16423. }
  16424. }
  16425. if (parsedData.lensFlareSystems) {
  16426. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  16427. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  16428. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  16429. }
  16430. }
  16431. if (parsedData.shadowGenerators) {
  16432. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  16433. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  16434. parseShadowGenerator(parsedShadowGenerator, scene);
  16435. }
  16436. }
  16437. return true;
  16438. }
  16439. });
  16440. })(BABYLON.Internals || (BABYLON.Internals = {}));
  16441. var Internals = BABYLON.Internals;
  16442. })(BABYLON || (BABYLON = {}));
  16443. var BABYLON;
  16444. (function (BABYLON) {
  16445. var currentCSGMeshId = 0;
  16446. var Vertex = (function () {
  16447. function Vertex(pos, normal, uv) {
  16448. this.pos = pos;
  16449. this.normal = normal;
  16450. this.uv = uv;
  16451. }
  16452. Vertex.prototype.clone = function () {
  16453. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  16454. };
  16455. Vertex.prototype.flip = function () {
  16456. this.normal = this.normal.scale(-1);
  16457. };
  16458. Vertex.prototype.interpolate = function (other, t) {
  16459. 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));
  16460. };
  16461. return Vertex;
  16462. })();
  16463. var Plane = (function () {
  16464. function Plane(normal, w) {
  16465. this.normal = normal;
  16466. this.w = w;
  16467. }
  16468. Plane.FromPoints = function (a, b, c) {
  16469. var v0 = c.subtract(a);
  16470. var v1 = b.subtract(a);
  16471. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  16472. return null;
  16473. }
  16474. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  16475. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  16476. };
  16477. Plane.prototype.clone = function () {
  16478. return new Plane(this.normal.clone(), this.w);
  16479. };
  16480. Plane.prototype.flip = function () {
  16481. this.normal.scaleInPlace(-1);
  16482. this.w = -this.w;
  16483. };
  16484. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  16485. var COPLANAR = 0;
  16486. var FRONT = 1;
  16487. var BACK = 2;
  16488. var SPANNING = 3;
  16489. var polygonType = 0;
  16490. var types = [];
  16491. for (var i = 0; i < polygon.vertices.length; i++) {
  16492. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  16493. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  16494. polygonType |= type;
  16495. types.push(type);
  16496. }
  16497. switch (polygonType) {
  16498. case COPLANAR:
  16499. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  16500. break;
  16501. case FRONT:
  16502. front.push(polygon);
  16503. break;
  16504. case BACK:
  16505. back.push(polygon);
  16506. break;
  16507. case SPANNING:
  16508. var f = [], b = [];
  16509. for (i = 0; i < polygon.vertices.length; i++) {
  16510. var j = (i + 1) % polygon.vertices.length;
  16511. var ti = types[i], tj = types[j];
  16512. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  16513. if (ti != BACK)
  16514. f.push(vi);
  16515. if (ti != FRONT)
  16516. b.push(ti != BACK ? vi.clone() : vi);
  16517. if ((ti | tj) == SPANNING) {
  16518. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  16519. var v = vi.interpolate(vj, t);
  16520. f.push(v);
  16521. b.push(v.clone());
  16522. }
  16523. }
  16524. if (f.length >= 3) {
  16525. var poly = new Polygon(f, polygon.shared);
  16526. if (poly.plane)
  16527. front.push(poly);
  16528. }
  16529. if (b.length >= 3) {
  16530. poly = new Polygon(b, polygon.shared);
  16531. if (poly.plane)
  16532. back.push(poly);
  16533. }
  16534. break;
  16535. }
  16536. };
  16537. Plane.EPSILON = 1e-5;
  16538. return Plane;
  16539. })();
  16540. var Polygon = (function () {
  16541. function Polygon(vertices, shared) {
  16542. this.vertices = vertices;
  16543. this.shared = shared;
  16544. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  16545. }
  16546. Polygon.prototype.clone = function () {
  16547. var vertices = this.vertices.map(function (v) {
  16548. return v.clone();
  16549. });
  16550. return new Polygon(vertices, this.shared);
  16551. };
  16552. Polygon.prototype.flip = function () {
  16553. this.vertices.reverse().map(function (v) {
  16554. v.flip();
  16555. });
  16556. this.plane.flip();
  16557. };
  16558. return Polygon;
  16559. })();
  16560. var Node = (function () {
  16561. function Node(polygons) {
  16562. this.plane = null;
  16563. this.front = null;
  16564. this.back = null;
  16565. this.polygons = [];
  16566. if (polygons) {
  16567. this.build(polygons);
  16568. }
  16569. }
  16570. Node.prototype.clone = function () {
  16571. var node = new Node();
  16572. node.plane = this.plane && this.plane.clone();
  16573. node.front = this.front && this.front.clone();
  16574. node.back = this.back && this.back.clone();
  16575. node.polygons = this.polygons.map(function (p) {
  16576. return p.clone();
  16577. });
  16578. return node;
  16579. };
  16580. Node.prototype.invert = function () {
  16581. for (var i = 0; i < this.polygons.length; i++) {
  16582. this.polygons[i].flip();
  16583. }
  16584. if (this.plane) {
  16585. this.plane.flip();
  16586. }
  16587. if (this.front) {
  16588. this.front.invert();
  16589. }
  16590. if (this.back) {
  16591. this.back.invert();
  16592. }
  16593. var temp = this.front;
  16594. this.front = this.back;
  16595. this.back = temp;
  16596. };
  16597. Node.prototype.clipPolygons = function (polygons) {
  16598. if (!this.plane)
  16599. return polygons.slice();
  16600. var front = [], back = [];
  16601. for (var i = 0; i < polygons.length; i++) {
  16602. this.plane.splitPolygon(polygons[i], front, back, front, back);
  16603. }
  16604. if (this.front) {
  16605. front = this.front.clipPolygons(front);
  16606. }
  16607. if (this.back) {
  16608. back = this.back.clipPolygons(back);
  16609. } else {
  16610. back = [];
  16611. }
  16612. return front.concat(back);
  16613. };
  16614. Node.prototype.clipTo = function (bsp) {
  16615. this.polygons = bsp.clipPolygons(this.polygons);
  16616. if (this.front)
  16617. this.front.clipTo(bsp);
  16618. if (this.back)
  16619. this.back.clipTo(bsp);
  16620. };
  16621. Node.prototype.allPolygons = function () {
  16622. var polygons = this.polygons.slice();
  16623. if (this.front)
  16624. polygons = polygons.concat(this.front.allPolygons());
  16625. if (this.back)
  16626. polygons = polygons.concat(this.back.allPolygons());
  16627. return polygons;
  16628. };
  16629. Node.prototype.build = function (polygons) {
  16630. if (!polygons.length)
  16631. return;
  16632. if (!this.plane)
  16633. this.plane = polygons[0].plane.clone();
  16634. var front = [], back = [];
  16635. for (var i = 0; i < polygons.length; i++) {
  16636. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  16637. }
  16638. if (front.length) {
  16639. if (!this.front)
  16640. this.front = new Node();
  16641. this.front.build(front);
  16642. }
  16643. if (back.length) {
  16644. if (!this.back)
  16645. this.back = new Node();
  16646. this.back.build(back);
  16647. }
  16648. };
  16649. return Node;
  16650. })();
  16651. var CSG = (function () {
  16652. function CSG() {
  16653. this.polygons = new Array();
  16654. }
  16655. CSG.FromMesh = function (mesh) {
  16656. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  16657. if (mesh instanceof BABYLON.Mesh) {
  16658. mesh.computeWorldMatrix(true);
  16659. var matrix = mesh.getWorldMatrix();
  16660. var meshPosition = mesh.position.clone();
  16661. var meshRotation = mesh.rotation.clone();
  16662. var meshScaling = mesh.scaling.clone();
  16663. } else {
  16664. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  16665. }
  16666. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16667. var subMeshes = mesh.subMeshes;
  16668. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  16669. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  16670. vertices = [];
  16671. for (var j = 0; j < 3; j++) {
  16672. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  16673. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  16674. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  16675. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  16676. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  16677. vertex = new Vertex(position, normal, uv);
  16678. vertices.push(vertex);
  16679. }
  16680. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  16681. if (polygon.plane)
  16682. polygons.push(polygon);
  16683. }
  16684. }
  16685. var csg = CSG.FromPolygons(polygons);
  16686. csg.matrix = matrix;
  16687. csg.position = meshPosition;
  16688. csg.rotation = meshRotation;
  16689. csg.scaling = meshScaling;
  16690. currentCSGMeshId++;
  16691. return csg;
  16692. };
  16693. CSG.FromPolygons = function (polygons) {
  16694. var csg = new BABYLON.CSG();
  16695. csg.polygons = polygons;
  16696. return csg;
  16697. };
  16698. CSG.prototype.clone = function () {
  16699. var csg = new BABYLON.CSG();
  16700. csg.polygons = this.polygons.map(function (p) {
  16701. return p.clone();
  16702. });
  16703. csg.copyTransformAttributes(this);
  16704. return csg;
  16705. };
  16706. CSG.prototype.toPolygons = function () {
  16707. return this.polygons;
  16708. };
  16709. CSG.prototype.union = function (csg) {
  16710. var a = new Node(this.clone().polygons);
  16711. var b = new Node(csg.clone().polygons);
  16712. a.clipTo(b);
  16713. b.clipTo(a);
  16714. b.invert();
  16715. b.clipTo(a);
  16716. b.invert();
  16717. a.build(b.allPolygons());
  16718. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16719. };
  16720. CSG.prototype.unionInPlace = function (csg) {
  16721. var a = new Node(this.polygons);
  16722. var b = new Node(csg.polygons);
  16723. a.clipTo(b);
  16724. b.clipTo(a);
  16725. b.invert();
  16726. b.clipTo(a);
  16727. b.invert();
  16728. a.build(b.allPolygons());
  16729. this.polygons = a.allPolygons();
  16730. };
  16731. CSG.prototype.subtract = function (csg) {
  16732. var a = new Node(this.clone().polygons);
  16733. var b = new Node(csg.clone().polygons);
  16734. a.invert();
  16735. a.clipTo(b);
  16736. b.clipTo(a);
  16737. b.invert();
  16738. b.clipTo(a);
  16739. b.invert();
  16740. a.build(b.allPolygons());
  16741. a.invert();
  16742. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16743. };
  16744. CSG.prototype.subtractInPlace = function (csg) {
  16745. var a = new Node(this.polygons);
  16746. var b = new Node(csg.polygons);
  16747. a.invert();
  16748. a.clipTo(b);
  16749. b.clipTo(a);
  16750. b.invert();
  16751. b.clipTo(a);
  16752. b.invert();
  16753. a.build(b.allPolygons());
  16754. a.invert();
  16755. this.polygons = a.allPolygons();
  16756. };
  16757. CSG.prototype.intersect = function (csg) {
  16758. var a = new Node(this.clone().polygons);
  16759. var b = new Node(csg.clone().polygons);
  16760. a.invert();
  16761. b.clipTo(a);
  16762. b.invert();
  16763. a.clipTo(b);
  16764. b.clipTo(a);
  16765. a.build(b.allPolygons());
  16766. a.invert();
  16767. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  16768. };
  16769. CSG.prototype.intersectInPlace = function (csg) {
  16770. var a = new Node(this.polygons);
  16771. var b = new Node(csg.polygons);
  16772. a.invert();
  16773. b.clipTo(a);
  16774. b.invert();
  16775. a.clipTo(b);
  16776. b.clipTo(a);
  16777. a.build(b.allPolygons());
  16778. a.invert();
  16779. this.polygons = a.allPolygons();
  16780. };
  16781. CSG.prototype.inverse = function () {
  16782. var csg = this.clone();
  16783. csg.inverseInPlace();
  16784. return csg;
  16785. };
  16786. CSG.prototype.inverseInPlace = function () {
  16787. this.polygons.map(function (p) {
  16788. p.flip();
  16789. });
  16790. };
  16791. CSG.prototype.copyTransformAttributes = function (csg) {
  16792. this.matrix = csg.matrix;
  16793. this.position = csg.position;
  16794. this.rotation = csg.rotation;
  16795. this.scaling = csg.scaling;
  16796. return this;
  16797. };
  16798. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  16799. var matrix = this.matrix.clone();
  16800. matrix.invert();
  16801. 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;
  16802. if (keepSubMeshes) {
  16803. polygons.sort(function (a, b) {
  16804. if (a.shared.meshId === b.shared.meshId) {
  16805. return a.shared.subMeshId - b.shared.subMeshId;
  16806. } else {
  16807. return a.shared.meshId - b.shared.meshId;
  16808. }
  16809. });
  16810. }
  16811. for (var i = 0, il = polygons.length; i < il; i++) {
  16812. polygon = polygons[i];
  16813. if (!subMesh_dict[polygon.shared.meshId]) {
  16814. subMesh_dict[polygon.shared.meshId] = {};
  16815. }
  16816. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  16817. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  16818. indexStart: +Infinity,
  16819. indexEnd: -Infinity,
  16820. materialIndex: polygon.shared.materialIndex
  16821. };
  16822. }
  16823. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  16824. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  16825. polygonIndices[0] = 0;
  16826. polygonIndices[1] = j - 1;
  16827. polygonIndices[2] = j;
  16828. for (var k = 0; k < 3; k++) {
  16829. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  16830. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  16831. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  16832. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  16833. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  16834. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  16835. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  16836. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  16837. uvs.push(uv.x, uv.y);
  16838. normals.push(normal.x, normal.y, normal.z);
  16839. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  16840. }
  16841. indices.push(vertex_idx);
  16842. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  16843. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  16844. currentIndex++;
  16845. }
  16846. }
  16847. }
  16848. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  16849. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  16850. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  16851. mesh.setIndices(indices);
  16852. if (keepSubMeshes) {
  16853. var materialIndexOffset = 0, materialMaxIndex;
  16854. mesh.subMeshes.length = 0;
  16855. for (var m in subMesh_dict) {
  16856. materialMaxIndex = -1;
  16857. for (var sm in subMesh_dict[m]) {
  16858. subMesh_obj = subMesh_dict[m][sm];
  16859. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  16860. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  16861. }
  16862. materialIndexOffset += ++materialMaxIndex;
  16863. }
  16864. }
  16865. return mesh;
  16866. };
  16867. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  16868. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  16869. mesh.material = material;
  16870. mesh.position.copyFrom(this.position);
  16871. mesh.rotation.copyFrom(this.rotation);
  16872. mesh.scaling.copyFrom(this.scaling);
  16873. mesh.computeWorldMatrix(true);
  16874. return mesh;
  16875. };
  16876. return CSG;
  16877. })();
  16878. BABYLON.CSG = CSG;
  16879. })(BABYLON || (BABYLON = {}));
  16880. var __extends = this.__extends || function (d, b) {
  16881. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16882. function __() { this.constructor = d; }
  16883. __.prototype = b.prototype;
  16884. d.prototype = new __();
  16885. };
  16886. var BABYLON;
  16887. (function (BABYLON) {
  16888. var OculusDistortionCorrectionPostProcess = (function (_super) {
  16889. __extends(OculusDistortionCorrectionPostProcess, _super);
  16890. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  16891. var _this = this;
  16892. _super.call(this, name, "oculusDistortionCorrection", [
  16893. 'LensCenter',
  16894. 'Scale',
  16895. 'ScaleIn',
  16896. 'HmdWarpParam'
  16897. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  16898. this._isRightEye = isRightEye;
  16899. this._distortionFactors = cameraSettings.DistortionK;
  16900. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  16901. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  16902. this.onSizeChanged = function () {
  16903. _this.aspectRatio = _this.width * .5 / _this.height;
  16904. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  16905. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  16906. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  16907. };
  16908. this.onApply = function (effect) {
  16909. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  16910. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  16911. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  16912. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  16913. };
  16914. }
  16915. return OculusDistortionCorrectionPostProcess;
  16916. })(BABYLON.PostProcess);
  16917. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  16918. })(BABYLON || (BABYLON = {}));
  16919. var BABYLON;
  16920. (function (BABYLON) {
  16921. (function (JoystickAxis) {
  16922. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  16923. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  16924. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  16925. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  16926. var JoystickAxis = BABYLON.JoystickAxis;
  16927. var VirtualJoystick = (function () {
  16928. function VirtualJoystick(leftJoystick) {
  16929. var _this = this;
  16930. if (leftJoystick) {
  16931. this._leftJoystick = true;
  16932. } else {
  16933. this._leftJoystick = false;
  16934. }
  16935. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  16936. VirtualJoystick._globalJoystickIndex++;
  16937. this._axisTargetedByLeftAndRight = 0 /* X */;
  16938. this._axisTargetedByUpAndDown = 1 /* Y */;
  16939. this.reverseLeftRight = false;
  16940. this.reverseUpDown = false;
  16941. this._touches = new BABYLON.VirtualJoystick.Collection();
  16942. this.deltaPosition = BABYLON.Vector3.Zero();
  16943. this._joystickSensibility = 25;
  16944. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  16945. this._rotationSpeed = 25;
  16946. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  16947. this._rotateOnAxisRelativeToMesh = false;
  16948. if (!VirtualJoystick.vjCanvas) {
  16949. window.addEventListener("resize", function () {
  16950. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16951. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16952. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  16953. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  16954. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  16955. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  16956. }, false);
  16957. VirtualJoystick.vjCanvas = document.createElement("canvas");
  16958. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  16959. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  16960. VirtualJoystick.vjCanvas.width = window.innerWidth;
  16961. VirtualJoystick.vjCanvas.height = window.innerHeight;
  16962. VirtualJoystick.vjCanvas.style.width = "100%";
  16963. VirtualJoystick.vjCanvas.style.height = "100%";
  16964. VirtualJoystick.vjCanvas.style.position = "absolute";
  16965. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  16966. VirtualJoystick.vjCanvas.style.top = "0px";
  16967. VirtualJoystick.vjCanvas.style.left = "0px";
  16968. VirtualJoystick.vjCanvas.style.zIndex = "5";
  16969. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  16970. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  16971. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  16972. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  16973. document.body.appendChild(VirtualJoystick.vjCanvas);
  16974. }
  16975. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  16976. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  16977. this.pressed = false;
  16978. this._joystickColor = "cyan";
  16979. this._joystickPointerID = -1;
  16980. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  16981. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  16982. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  16983. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  16984. _this._onPointerDown(evt);
  16985. }, false);
  16986. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  16987. _this._onPointerMove(evt);
  16988. }, false);
  16989. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  16990. _this._onPointerUp(evt);
  16991. }, false);
  16992. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  16993. _this._onPointerUp(evt);
  16994. }, false);
  16995. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  16996. evt.preventDefault();
  16997. }, false);
  16998. requestAnimationFrame(function () {
  16999. _this._drawVirtualJoystick();
  17000. });
  17001. }
  17002. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  17003. this._joystickSensibility = newJoystickSensibility;
  17004. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17005. };
  17006. VirtualJoystick.prototype._onPointerDown = function (e) {
  17007. var positionOnScreenCondition;
  17008. e.preventDefault();
  17009. if (this._leftJoystick === true) {
  17010. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  17011. } else {
  17012. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  17013. }
  17014. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  17015. this._joystickPointerID = e.pointerId;
  17016. this._joystickPointerStartPos.x = e.clientX;
  17017. this._joystickPointerStartPos.y = e.clientY;
  17018. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  17019. this._deltaJoystickVector.x = 0;
  17020. this._deltaJoystickVector.y = 0;
  17021. this.pressed = true;
  17022. this._touches.add(e.pointerId.toString(), e);
  17023. } else {
  17024. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  17025. this._action();
  17026. this._touches.add(e.pointerId.toString(), e);
  17027. }
  17028. }
  17029. };
  17030. VirtualJoystick.prototype._onPointerMove = function (e) {
  17031. if (this._joystickPointerID == e.pointerId) {
  17032. this._joystickPointerPos.x = e.clientX;
  17033. this._joystickPointerPos.y = e.clientY;
  17034. this._deltaJoystickVector = this._joystickPointerPos.clone();
  17035. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  17036. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  17037. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  17038. switch (this._axisTargetedByLeftAndRight) {
  17039. case 0 /* X */:
  17040. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  17041. break;
  17042. case 1 /* Y */:
  17043. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  17044. break;
  17045. case 2 /* Z */:
  17046. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  17047. break;
  17048. }
  17049. var directionUpDown = this.reverseUpDown ? 1 : -1;
  17050. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  17051. switch (this._axisTargetedByUpAndDown) {
  17052. case 0 /* X */:
  17053. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  17054. break;
  17055. case 1 /* Y */:
  17056. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  17057. break;
  17058. case 2 /* Z */:
  17059. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  17060. break;
  17061. }
  17062. } else {
  17063. if (this._touches.item(e.pointerId.toString())) {
  17064. this._touches.item(e.pointerId.toString()).x = e.clientX;
  17065. this._touches.item(e.pointerId.toString()).y = e.clientY;
  17066. }
  17067. }
  17068. };
  17069. VirtualJoystick.prototype._onPointerUp = function (e) {
  17070. this._clearCanvas();
  17071. if (this._joystickPointerID == e.pointerId) {
  17072. this._joystickPointerID = -1;
  17073. this.pressed = false;
  17074. }
  17075. this._deltaJoystickVector.x = 0;
  17076. this._deltaJoystickVector.y = 0;
  17077. this._touches.remove(e.pointerId.toString());
  17078. };
  17079. /**
  17080. * Change the color of the virtual joystick
  17081. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  17082. */
  17083. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  17084. this._joystickColor = newColor;
  17085. };
  17086. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  17087. this._action = action;
  17088. };
  17089. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  17090. switch (axis) {
  17091. case 0 /* X */:
  17092. case 1 /* Y */:
  17093. case 2 /* Z */:
  17094. this._axisTargetedByLeftAndRight = axis;
  17095. break;
  17096. default:
  17097. this._axisTargetedByLeftAndRight = 0 /* X */;
  17098. break;
  17099. }
  17100. };
  17101. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  17102. switch (axis) {
  17103. case 0 /* X */:
  17104. case 1 /* Y */:
  17105. case 2 /* Z */:
  17106. this._axisTargetedByUpAndDown = axis;
  17107. break;
  17108. default:
  17109. this._axisTargetedByUpAndDown = 1 /* Y */;
  17110. break;
  17111. }
  17112. };
  17113. VirtualJoystick.prototype._clearCanvas = function () {
  17114. if (this._leftJoystick) {
  17115. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  17116. } else {
  17117. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  17118. }
  17119. };
  17120. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  17121. var _this = this;
  17122. if (this.pressed) {
  17123. this._clearCanvas();
  17124. this._touches.forEach(function (touch) {
  17125. if (touch.pointerId === _this._joystickPointerID) {
  17126. VirtualJoystick.vjCanvasContext.beginPath();
  17127. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17128. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17129. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  17130. VirtualJoystick.vjCanvasContext.stroke();
  17131. VirtualJoystick.vjCanvasContext.beginPath();
  17132. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17133. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17134. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  17135. VirtualJoystick.vjCanvasContext.stroke();
  17136. VirtualJoystick.vjCanvasContext.beginPath();
  17137. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17138. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  17139. VirtualJoystick.vjCanvasContext.stroke();
  17140. } else {
  17141. VirtualJoystick.vjCanvasContext.beginPath();
  17142. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  17143. VirtualJoystick.vjCanvasContext.beginPath();
  17144. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  17145. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17146. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  17147. VirtualJoystick.vjCanvasContext.stroke();
  17148. }
  17149. ;
  17150. });
  17151. }
  17152. requestAnimationFrame(function () {
  17153. _this._drawVirtualJoystick();
  17154. });
  17155. };
  17156. VirtualJoystick.prototype.releaseCanvas = function () {
  17157. if (VirtualJoystick.vjCanvas) {
  17158. document.body.removeChild(VirtualJoystick.vjCanvas);
  17159. VirtualJoystick.vjCanvas = null;
  17160. }
  17161. };
  17162. VirtualJoystick._globalJoystickIndex = 0;
  17163. return VirtualJoystick;
  17164. })();
  17165. BABYLON.VirtualJoystick = VirtualJoystick;
  17166. })(BABYLON || (BABYLON = {}));
  17167. var BABYLON;
  17168. (function (BABYLON) {
  17169. (function (VirtualJoystick) {
  17170. var Collection = (function () {
  17171. function Collection() {
  17172. this._count = 0;
  17173. this._collection = new Array();
  17174. }
  17175. Collection.prototype.Count = function () {
  17176. return this._count;
  17177. };
  17178. Collection.prototype.add = function (key, item) {
  17179. if (this._collection[key] != undefined) {
  17180. return undefined;
  17181. }
  17182. this._collection[key] = item;
  17183. return ++this._count;
  17184. };
  17185. Collection.prototype.remove = function (key) {
  17186. if (this._collection[key] == undefined) {
  17187. return undefined;
  17188. }
  17189. delete this._collection[key];
  17190. return --this._count;
  17191. };
  17192. Collection.prototype.item = function (key) {
  17193. return this._collection[key];
  17194. };
  17195. Collection.prototype.forEach = function (block) {
  17196. var key;
  17197. for (key in this._collection) {
  17198. if (this._collection.hasOwnProperty(key)) {
  17199. block(this._collection[key]);
  17200. }
  17201. }
  17202. };
  17203. return Collection;
  17204. })();
  17205. VirtualJoystick.Collection = Collection;
  17206. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  17207. var VirtualJoystick = BABYLON.VirtualJoystick;
  17208. })(BABYLON || (BABYLON = {}));
  17209. var __extends = this.__extends || function (d, b) {
  17210. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17211. function __() { this.constructor = d; }
  17212. __.prototype = b.prototype;
  17213. d.prototype = new __();
  17214. };
  17215. var BABYLON;
  17216. (function (BABYLON) {
  17217. var OculusRiftDevKit2013_Metric = {
  17218. HResolution: 1280,
  17219. VResolution: 800,
  17220. HScreenSize: 0.149759993,
  17221. VScreenSize: 0.0935999975,
  17222. VScreenCenter: 0.0467999987,
  17223. EyeToScreenDistance: 0.0410000011,
  17224. LensSeparationDistance: 0.0635000020,
  17225. InterpupillaryDistance: 0.0640000030,
  17226. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17227. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17228. PostProcessScaleFactor: 1.714605507808412,
  17229. LensCenterOffset: 0.151976421
  17230. };
  17231. var _OculusInnerCamera = (function (_super) {
  17232. __extends(_OculusInnerCamera, _super);
  17233. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  17234. _super.call(this, name, position, scene);
  17235. this._workMatrix = new BABYLON.Matrix();
  17236. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17237. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17238. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17239. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17240. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17241. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17242. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17243. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17244. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17245. }
  17246. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  17247. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17248. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17249. return this._projectionMatrix;
  17250. };
  17251. _OculusInnerCamera.prototype._getViewMatrix = function () {
  17252. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17253. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17254. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17255. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17256. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17257. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17258. return this._viewMatrix;
  17259. };
  17260. return _OculusInnerCamera;
  17261. })(BABYLON.FreeCamera);
  17262. var OculusCamera = (function (_super) {
  17263. __extends(OculusCamera, _super);
  17264. function OculusCamera(name, position, scene) {
  17265. _super.call(this, name, position, scene);
  17266. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  17267. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  17268. this.subCameras.push(this._leftCamera);
  17269. this.subCameras.push(this._rightCamera);
  17270. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17271. }
  17272. OculusCamera.prototype._update = function () {
  17273. this._leftCamera.position.copyFrom(this.position);
  17274. this._rightCamera.position.copyFrom(this.position);
  17275. this._updateCamera(this._leftCamera);
  17276. this._updateCamera(this._rightCamera);
  17277. _super.prototype._update.call(this);
  17278. };
  17279. OculusCamera.prototype._updateCamera = function (camera) {
  17280. camera.minZ = this.minZ;
  17281. camera.maxZ = this.maxZ;
  17282. camera.rotation.x = this.rotation.x;
  17283. camera.rotation.y = this.rotation.y;
  17284. camera.rotation.z = this.rotation.z;
  17285. };
  17286. OculusCamera.prototype._onOrientationEvent = function (evt) {
  17287. var yaw = evt.alpha / 180 * Math.PI;
  17288. var pitch = evt.beta / 180 * Math.PI;
  17289. var roll = evt.gamma / 180 * Math.PI;
  17290. if (!this._offsetOrientation) {
  17291. this._offsetOrientation = {
  17292. yaw: yaw,
  17293. pitch: pitch,
  17294. roll: roll
  17295. };
  17296. return;
  17297. } else {
  17298. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17299. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17300. this.rotation.z += this._offsetOrientation.roll - roll;
  17301. this._offsetOrientation.yaw = yaw;
  17302. this._offsetOrientation.pitch = pitch;
  17303. this._offsetOrientation.roll = roll;
  17304. }
  17305. };
  17306. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  17307. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17308. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17309. };
  17310. OculusCamera.prototype.detachControl = function (element) {
  17311. _super.prototype.detachControl.call(this, element);
  17312. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17313. };
  17314. return OculusCamera;
  17315. })(BABYLON.FreeCamera);
  17316. BABYLON.OculusCamera = OculusCamera;
  17317. })(BABYLON || (BABYLON = {}));
  17318. var __extends = this.__extends || function (d, b) {
  17319. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17320. function __() { this.constructor = d; }
  17321. __.prototype = b.prototype;
  17322. d.prototype = new __();
  17323. };
  17324. var BABYLON;
  17325. (function (BABYLON) {
  17326. var OculusRiftDevKit2013_Metric = {
  17327. HResolution: 1280,
  17328. VResolution: 800,
  17329. HScreenSize: 0.149759993,
  17330. VScreenSize: 0.0935999975,
  17331. VScreenCenter: 0.0467999987,
  17332. EyeToScreenDistance: 0.0410000011,
  17333. LensSeparationDistance: 0.0635000020,
  17334. InterpupillaryDistance: 0.0640000030,
  17335. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17336. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17337. PostProcessScaleFactor: 1.714605507808412,
  17338. LensCenterOffset: 0.151976421
  17339. };
  17340. var _OculusInnerGamepadCamera = (function (_super) {
  17341. __extends(_OculusInnerGamepadCamera, _super);
  17342. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  17343. _super.call(this, name, position, scene);
  17344. this._workMatrix = new BABYLON.Matrix();
  17345. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17346. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17347. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17348. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17349. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17350. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17351. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17352. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17353. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17354. }
  17355. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  17356. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17357. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17358. return this._projectionMatrix;
  17359. };
  17360. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  17361. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17362. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17363. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17364. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17365. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17366. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17367. return this._viewMatrix;
  17368. };
  17369. return _OculusInnerGamepadCamera;
  17370. })(BABYLON.FreeCamera);
  17371. var OculusGamepadCamera = (function (_super) {
  17372. __extends(OculusGamepadCamera, _super);
  17373. function OculusGamepadCamera(name, position, scene) {
  17374. var _this = this;
  17375. _super.call(this, name, position, scene);
  17376. this.angularSensibility = 200;
  17377. this.moveSensibility = 75;
  17378. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  17379. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  17380. this.subCameras.push(this._leftCamera);
  17381. this.subCameras.push(this._rightCamera);
  17382. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17383. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  17384. _this._onNewGameConnected(gamepad);
  17385. });
  17386. }
  17387. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  17388. if (gamepad.index === 0) {
  17389. this._gamepad = gamepad;
  17390. }
  17391. };
  17392. OculusGamepadCamera.prototype._update = function () {
  17393. this._leftCamera.position.copyFrom(this.position);
  17394. this._rightCamera.position.copyFrom(this.position);
  17395. this._updateCamera(this._leftCamera);
  17396. this._updateCamera(this._rightCamera);
  17397. _super.prototype._update.call(this);
  17398. };
  17399. OculusGamepadCamera.prototype._checkInputs = function () {
  17400. if (!this._gamepad) {
  17401. return;
  17402. }
  17403. var LSValues = this._gamepad.leftStick;
  17404. var normalizedLX = LSValues.x / this.moveSensibility;
  17405. var normalizedLY = LSValues.y / this.moveSensibility;
  17406. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17407. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17408. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17409. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  17410. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17411. };
  17412. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  17413. camera.minZ = this.minZ;
  17414. camera.maxZ = this.maxZ;
  17415. camera.rotation.x = this.rotation.x;
  17416. camera.rotation.y = this.rotation.y;
  17417. camera.rotation.z = this.rotation.z;
  17418. };
  17419. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  17420. var yaw = evt.alpha / 180 * Math.PI;
  17421. var pitch = evt.beta / 180 * Math.PI;
  17422. var roll = evt.gamma / 180 * Math.PI;
  17423. if (!this._offsetOrientation) {
  17424. this._offsetOrientation = {
  17425. yaw: yaw,
  17426. pitch: pitch,
  17427. roll: roll
  17428. };
  17429. return;
  17430. } else {
  17431. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17432. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17433. this.rotation.z += this._offsetOrientation.roll - roll;
  17434. this._offsetOrientation.yaw = yaw;
  17435. this._offsetOrientation.pitch = pitch;
  17436. this._offsetOrientation.roll = roll;
  17437. }
  17438. };
  17439. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  17440. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17441. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17442. };
  17443. OculusGamepadCamera.prototype.detachControl = function (element) {
  17444. _super.prototype.detachControl.call(this, element);
  17445. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17446. };
  17447. OculusGamepadCamera.prototype.dispose = function () {
  17448. this._gamepads.dispose();
  17449. _super.prototype.dispose.call(this);
  17450. };
  17451. return OculusGamepadCamera;
  17452. })(BABYLON.FreeCamera);
  17453. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  17454. })(BABYLON || (BABYLON = {}));
  17455. var __extends = this.__extends || function (d, b) {
  17456. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17457. function __() { this.constructor = d; }
  17458. __.prototype = b.prototype;
  17459. d.prototype = new __();
  17460. };
  17461. var BABYLON;
  17462. (function (BABYLON) {
  17463. var VirtualJoysticksCamera = (function (_super) {
  17464. __extends(VirtualJoysticksCamera, _super);
  17465. function VirtualJoysticksCamera(name, position, scene) {
  17466. _super.call(this, name, position, scene);
  17467. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  17468. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  17469. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  17470. this._leftjoystick.setJoystickSensibility(0.15);
  17471. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  17472. this._rightjoystick.setAxisForUpDown(0 /* X */);
  17473. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  17474. this._rightjoystick.reverseUpDown = true;
  17475. this._rightjoystick.setJoystickSensibility(0.05);
  17476. this._rightjoystick.setJoystickColor("yellow");
  17477. }
  17478. VirtualJoysticksCamera.prototype._checkInputs = function () {
  17479. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  17480. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  17481. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  17482. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  17483. if (!this._leftjoystick.pressed) {
  17484. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  17485. }
  17486. if (!this._rightjoystick.pressed) {
  17487. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  17488. }
  17489. };
  17490. VirtualJoysticksCamera.prototype.dispose = function () {
  17491. this._leftjoystick.releaseCanvas();
  17492. _super.prototype.dispose.call(this);
  17493. };
  17494. return VirtualJoysticksCamera;
  17495. })(BABYLON.FreeCamera);
  17496. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  17497. })(BABYLON || (BABYLON = {}));
  17498. var __extends = this.__extends || function (d, b) {
  17499. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17500. function __() { this.constructor = d; }
  17501. __.prototype = b.prototype;
  17502. d.prototype = new __();
  17503. };
  17504. var BABYLON;
  17505. (function (BABYLON) {
  17506. var ShaderMaterial = (function (_super) {
  17507. __extends(ShaderMaterial, _super);
  17508. function ShaderMaterial(name, scene, shaderPath, options) {
  17509. _super.call(this, name, scene);
  17510. this._textures = new Array();
  17511. this._floats = new Array();
  17512. this._floatsArrays = {};
  17513. this._colors3 = new Array();
  17514. this._colors4 = new Array();
  17515. this._vectors2 = new Array();
  17516. this._vectors3 = new Array();
  17517. this._matrices = new Array();
  17518. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  17519. this._shaderPath = shaderPath;
  17520. options.needAlphaBlending = options.needAlphaBlending || false;
  17521. options.needAlphaTesting = options.needAlphaTesting || false;
  17522. options.attributes = options.attributes || ["position", "normal", "uv"];
  17523. options.uniforms = options.uniforms || ["worldViewProjection"];
  17524. options.samplers = options.samplers || [];
  17525. this._options = options;
  17526. }
  17527. ShaderMaterial.prototype.needAlphaBlending = function () {
  17528. return this._options.needAlphaBlending;
  17529. };
  17530. ShaderMaterial.prototype.needAlphaTesting = function () {
  17531. return this._options.needAlphaTesting;
  17532. };
  17533. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  17534. if (this._options.uniforms.indexOf(uniformName) === -1) {
  17535. this._options.uniforms.push(uniformName);
  17536. }
  17537. };
  17538. ShaderMaterial.prototype.setTexture = function (name, texture) {
  17539. if (this._options.samplers.indexOf(name) === -1) {
  17540. this._options.samplers.push(name);
  17541. }
  17542. this._textures[name] = texture;
  17543. return this;
  17544. };
  17545. ShaderMaterial.prototype.setFloat = function (name, value) {
  17546. this._checkUniform(name);
  17547. this._floats[name] = value;
  17548. return this;
  17549. };
  17550. ShaderMaterial.prototype.setFloats = function (name, value) {
  17551. this._checkUniform(name);
  17552. this._floatsArrays[name] = value;
  17553. return this;
  17554. };
  17555. ShaderMaterial.prototype.setColor3 = function (name, value) {
  17556. this._checkUniform(name);
  17557. this._colors3[name] = value;
  17558. return this;
  17559. };
  17560. ShaderMaterial.prototype.setColor4 = function (name, value) {
  17561. this._checkUniform(name);
  17562. this._colors4[name] = value;
  17563. return this;
  17564. };
  17565. ShaderMaterial.prototype.setVector2 = function (name, value) {
  17566. this._checkUniform(name);
  17567. this._vectors2[name] = value;
  17568. return this;
  17569. };
  17570. ShaderMaterial.prototype.setVector3 = function (name, value) {
  17571. this._checkUniform(name);
  17572. this._vectors3[name] = value;
  17573. return this;
  17574. };
  17575. ShaderMaterial.prototype.setMatrix = function (name, value) {
  17576. this._checkUniform(name);
  17577. this._matrices[name] = value;
  17578. return this;
  17579. };
  17580. ShaderMaterial.prototype.isReady = function () {
  17581. var engine = this.getScene().getEngine();
  17582. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  17583. if (!this._effect.isReady()) {
  17584. return false;
  17585. }
  17586. return true;
  17587. };
  17588. ShaderMaterial.prototype.bind = function (world) {
  17589. if (this._options.uniforms.indexOf("world") !== -1) {
  17590. this._effect.setMatrix("world", world);
  17591. }
  17592. if (this._options.uniforms.indexOf("view") !== -1) {
  17593. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  17594. }
  17595. if (this._options.uniforms.indexOf("worldView") !== -1) {
  17596. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  17597. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  17598. }
  17599. if (this._options.uniforms.indexOf("projection") !== -1) {
  17600. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  17601. }
  17602. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  17603. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  17604. }
  17605. for (var name in this._textures) {
  17606. this._effect.setTexture(name, this._textures[name]);
  17607. }
  17608. for (name in this._floats) {
  17609. this._effect.setFloat(name, this._floats[name]);
  17610. }
  17611. for (name in this._floatsArrays) {
  17612. this._effect.setArray(name, this._floatsArrays[name]);
  17613. }
  17614. for (name in this._colors3) {
  17615. this._effect.setColor3(name, this._colors3[name]);
  17616. }
  17617. for (name in this._colors4) {
  17618. var color = this._colors4[name];
  17619. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17620. }
  17621. for (name in this._vectors2) {
  17622. this._effect.setVector2(name, this._vectors2[name]);
  17623. }
  17624. for (name in this._vectors3) {
  17625. this._effect.setVector3(name, this._vectors3[name]);
  17626. }
  17627. for (name in this._matrices) {
  17628. this._effect.setMatrix(name, this._matrices[name]);
  17629. }
  17630. };
  17631. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  17632. for (var name in this._textures) {
  17633. this._textures[name].dispose();
  17634. }
  17635. this._textures = [];
  17636. _super.prototype.dispose.call(this, forceDisposeEffect);
  17637. };
  17638. return ShaderMaterial;
  17639. })(BABYLON.Material);
  17640. BABYLON.ShaderMaterial = ShaderMaterial;
  17641. })(BABYLON || (BABYLON = {}));
  17642. var BABYLON;
  17643. (function (BABYLON) {
  17644. var VertexData = (function () {
  17645. function VertexData() {
  17646. }
  17647. VertexData.prototype.set = function (data, kind) {
  17648. switch (kind) {
  17649. case BABYLON.VertexBuffer.PositionKind:
  17650. this.positions = data;
  17651. break;
  17652. case BABYLON.VertexBuffer.NormalKind:
  17653. this.normals = data;
  17654. break;
  17655. case BABYLON.VertexBuffer.UVKind:
  17656. this.uvs = data;
  17657. break;
  17658. case BABYLON.VertexBuffer.UV2Kind:
  17659. this.uv2s = data;
  17660. break;
  17661. case BABYLON.VertexBuffer.ColorKind:
  17662. this.colors = data;
  17663. break;
  17664. case BABYLON.VertexBuffer.MatricesIndicesKind:
  17665. this.matricesIndices = data;
  17666. break;
  17667. case BABYLON.VertexBuffer.MatricesWeightsKind:
  17668. this.matricesWeights = data;
  17669. break;
  17670. }
  17671. };
  17672. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  17673. this._applyTo(mesh, updatable);
  17674. };
  17675. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  17676. this._applyTo(geometry, updatable);
  17677. };
  17678. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  17679. this._update(mesh);
  17680. };
  17681. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  17682. this._update(geometry);
  17683. };
  17684. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  17685. if (this.positions) {
  17686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  17687. }
  17688. if (this.normals) {
  17689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  17690. }
  17691. if (this.uvs) {
  17692. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  17693. }
  17694. if (this.uv2s) {
  17695. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  17696. }
  17697. if (this.colors) {
  17698. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  17699. }
  17700. if (this.matricesIndices) {
  17701. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  17702. }
  17703. if (this.matricesWeights) {
  17704. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  17705. }
  17706. if (this.indices) {
  17707. meshOrGeometry.setIndices(this.indices);
  17708. }
  17709. };
  17710. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  17711. if (this.positions) {
  17712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  17713. }
  17714. if (this.normals) {
  17715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  17716. }
  17717. if (this.uvs) {
  17718. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  17719. }
  17720. if (this.uv2s) {
  17721. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  17722. }
  17723. if (this.colors) {
  17724. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  17725. }
  17726. if (this.matricesIndices) {
  17727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  17728. }
  17729. if (this.matricesWeights) {
  17730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  17731. }
  17732. if (this.indices) {
  17733. meshOrGeometry.setIndices(this.indices);
  17734. }
  17735. };
  17736. VertexData.prototype.transform = function (matrix) {
  17737. var transformed = BABYLON.Vector3.Zero();
  17738. if (this.positions) {
  17739. var position = BABYLON.Vector3.Zero();
  17740. for (var index = 0; index < this.positions.length; index += 3) {
  17741. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  17742. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  17743. this.positions[index] = transformed.x;
  17744. this.positions[index + 1] = transformed.y;
  17745. this.positions[index + 2] = transformed.z;
  17746. }
  17747. }
  17748. if (this.normals) {
  17749. var normal = BABYLON.Vector3.Zero();
  17750. for (index = 0; index < this.normals.length; index += 3) {
  17751. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  17752. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  17753. this.normals[index] = transformed.x;
  17754. this.normals[index + 1] = transformed.y;
  17755. this.normals[index + 2] = transformed.z;
  17756. }
  17757. }
  17758. };
  17759. VertexData.prototype.merge = function (other) {
  17760. if (other.indices) {
  17761. if (!this.indices) {
  17762. this.indices = [];
  17763. }
  17764. var offset = this.positions ? this.positions.length / 3 : 0;
  17765. for (var index = 0; index < other.indices.length; index++) {
  17766. this.indices.push(other.indices[index] + offset);
  17767. }
  17768. }
  17769. if (other.positions) {
  17770. if (!this.positions) {
  17771. this.positions = [];
  17772. }
  17773. for (index = 0; index < other.positions.length; index++) {
  17774. this.positions.push(other.positions[index]);
  17775. }
  17776. }
  17777. if (other.normals) {
  17778. if (!this.normals) {
  17779. this.normals = [];
  17780. }
  17781. for (index = 0; index < other.normals.length; index++) {
  17782. this.normals.push(other.normals[index]);
  17783. }
  17784. }
  17785. if (other.uvs) {
  17786. if (!this.uvs) {
  17787. this.uvs = [];
  17788. }
  17789. for (index = 0; index < other.uvs.length; index++) {
  17790. this.uvs.push(other.uvs[index]);
  17791. }
  17792. }
  17793. if (other.uv2s) {
  17794. if (!this.uv2s) {
  17795. this.uv2s = [];
  17796. }
  17797. for (index = 0; index < other.uv2s.length; index++) {
  17798. this.uv2s.push(other.uv2s[index]);
  17799. }
  17800. }
  17801. if (other.matricesIndices) {
  17802. if (!this.matricesIndices) {
  17803. this.matricesIndices = [];
  17804. }
  17805. for (index = 0; index < other.matricesIndices.length; index++) {
  17806. this.matricesIndices.push(other.matricesIndices[index]);
  17807. }
  17808. }
  17809. if (other.matricesWeights) {
  17810. if (!this.matricesWeights) {
  17811. this.matricesWeights = [];
  17812. }
  17813. for (index = 0; index < other.matricesWeights.length; index++) {
  17814. this.matricesWeights.push(other.matricesWeights[index]);
  17815. }
  17816. }
  17817. if (other.colors) {
  17818. if (!this.colors) {
  17819. this.colors = [];
  17820. }
  17821. for (index = 0; index < other.colors.length; index++) {
  17822. this.colors.push(other.colors[index]);
  17823. }
  17824. }
  17825. };
  17826. VertexData.ExtractFromMesh = function (mesh) {
  17827. return VertexData._ExtractFrom(mesh);
  17828. };
  17829. VertexData.ExtractFromGeometry = function (geometry) {
  17830. return VertexData._ExtractFrom(geometry);
  17831. };
  17832. VertexData._ExtractFrom = function (meshOrGeometry) {
  17833. var result = new BABYLON.VertexData();
  17834. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17835. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17836. }
  17837. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17838. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17839. }
  17840. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17841. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17842. }
  17843. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17844. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17845. }
  17846. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17847. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17848. }
  17849. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17850. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17851. }
  17852. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17853. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17854. }
  17855. result.indices = meshOrGeometry.getIndices();
  17856. return result;
  17857. };
  17858. VertexData.CreateBox = function (size) {
  17859. var normalsSource = [
  17860. new BABYLON.Vector3(0, 0, 1),
  17861. new BABYLON.Vector3(0, 0, -1),
  17862. new BABYLON.Vector3(1, 0, 0),
  17863. new BABYLON.Vector3(-1, 0, 0),
  17864. new BABYLON.Vector3(0, 1, 0),
  17865. new BABYLON.Vector3(0, -1, 0)
  17866. ];
  17867. var indices = [];
  17868. var positions = [];
  17869. var normals = [];
  17870. var uvs = [];
  17871. size = size || 1;
  17872. for (var index = 0; index < normalsSource.length; index++) {
  17873. var normal = normalsSource[index];
  17874. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  17875. var side2 = BABYLON.Vector3.Cross(normal, side1);
  17876. var verticesLength = positions.length / 3;
  17877. indices.push(verticesLength);
  17878. indices.push(verticesLength + 1);
  17879. indices.push(verticesLength + 2);
  17880. indices.push(verticesLength);
  17881. indices.push(verticesLength + 2);
  17882. indices.push(verticesLength + 3);
  17883. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  17884. positions.push(vertex.x, vertex.y, vertex.z);
  17885. normals.push(normal.x, normal.y, normal.z);
  17886. uvs.push(1.0, 1.0);
  17887. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  17888. positions.push(vertex.x, vertex.y, vertex.z);
  17889. normals.push(normal.x, normal.y, normal.z);
  17890. uvs.push(0.0, 1.0);
  17891. vertex = normal.add(side1).add(side2).scale(size / 2);
  17892. positions.push(vertex.x, vertex.y, vertex.z);
  17893. normals.push(normal.x, normal.y, normal.z);
  17894. uvs.push(0.0, 0.0);
  17895. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  17896. positions.push(vertex.x, vertex.y, vertex.z);
  17897. normals.push(normal.x, normal.y, normal.z);
  17898. uvs.push(1.0, 0.0);
  17899. }
  17900. var vertexData = new BABYLON.VertexData();
  17901. vertexData.indices = indices;
  17902. vertexData.positions = positions;
  17903. vertexData.normals = normals;
  17904. vertexData.uvs = uvs;
  17905. return vertexData;
  17906. };
  17907. VertexData.CreateSphere = function (segments, diameter) {
  17908. segments = segments || 32;
  17909. diameter = diameter || 1;
  17910. var radius = diameter / 2;
  17911. var totalZRotationSteps = 2 + segments;
  17912. var totalYRotationSteps = 2 * totalZRotationSteps;
  17913. var indices = [];
  17914. var positions = [];
  17915. var normals = [];
  17916. var uvs = [];
  17917. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  17918. var normalizedZ = zRotationStep / totalZRotationSteps;
  17919. var angleZ = (normalizedZ * Math.PI);
  17920. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  17921. var normalizedY = yRotationStep / totalYRotationSteps;
  17922. var angleY = normalizedY * Math.PI * 2;
  17923. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  17924. var rotationY = BABYLON.Matrix.RotationY(angleY);
  17925. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  17926. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  17927. var vertex = complete.scale(radius);
  17928. var normal = BABYLON.Vector3.Normalize(vertex);
  17929. positions.push(vertex.x, vertex.y, vertex.z);
  17930. normals.push(normal.x, normal.y, normal.z);
  17931. uvs.push(normalizedZ, normalizedY);
  17932. }
  17933. if (zRotationStep > 0) {
  17934. var verticesCount = positions.length / 3;
  17935. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  17936. indices.push((firstIndex));
  17937. indices.push((firstIndex + 1));
  17938. indices.push(firstIndex + totalYRotationSteps + 1);
  17939. indices.push((firstIndex + totalYRotationSteps + 1));
  17940. indices.push((firstIndex + 1));
  17941. indices.push((firstIndex + totalYRotationSteps + 2));
  17942. }
  17943. }
  17944. }
  17945. var vertexData = new BABYLON.VertexData();
  17946. vertexData.indices = indices;
  17947. vertexData.positions = positions;
  17948. vertexData.normals = normals;
  17949. vertexData.uvs = uvs;
  17950. return vertexData;
  17951. };
  17952. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  17953. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  17954. var radiusTop = diameterTop / 2;
  17955. var radiusBottom = diameterBottom / 2;
  17956. var indices = [];
  17957. var positions = [];
  17958. var normals = [];
  17959. var uvs = [];
  17960. height = height || 1;
  17961. diameterTop = diameterTop || 0.5;
  17962. diameterBottom = diameterBottom || 1;
  17963. tessellation = tessellation || 16;
  17964. subdivisions = subdivisions || 1;
  17965. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  17966. var getCircleVector = function (i) {
  17967. var angle = (i * 2.0 * Math.PI / tessellation);
  17968. var dx = Math.cos(angle);
  17969. var dz = Math.sin(angle);
  17970. return new BABYLON.Vector3(dx, 0, dz);
  17971. };
  17972. var createCylinderCap = function (isTop) {
  17973. var radius = isTop ? radiusTop : radiusBottom;
  17974. if (radius == 0) {
  17975. return;
  17976. }
  17977. var vbase = positions.length / 3;
  17978. var offset = new BABYLON.Vector3(0, height / 2, 0);
  17979. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  17980. if (!isTop) {
  17981. offset.scaleInPlace(-1);
  17982. textureScale.x = -textureScale.x;
  17983. }
  17984. for (i = 0; i < tessellation; i++) {
  17985. var circleVector = getCircleVector(i);
  17986. var position = circleVector.scale(radius).add(offset);
  17987. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  17988. positions.push(position.x, position.y, position.z);
  17989. uvs.push(textureCoordinate.x, textureCoordinate.y);
  17990. }
  17991. for (var i = 0; i < tessellation - 2; i++) {
  17992. if (!isTop) {
  17993. indices.push(vbase);
  17994. indices.push(vbase + (i + 2) % tessellation);
  17995. indices.push(vbase + (i + 1) % tessellation);
  17996. } else {
  17997. indices.push(vbase);
  17998. indices.push(vbase + (i + 1) % tessellation);
  17999. indices.push(vbase + (i + 2) % tessellation);
  18000. }
  18001. }
  18002. };
  18003. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  18004. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  18005. var stride = tessellation + 1;
  18006. for (var i = 0; i <= tessellation; i++) {
  18007. var circleVector = getCircleVector(i);
  18008. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  18009. var position, radius = radiusBottom;
  18010. for (var s = 0; s <= subdivisions; s++) {
  18011. position = circleVector.scale(radius);
  18012. position.addInPlace(base.add(offset.scale(s)));
  18013. textureCoordinate.y += 1 / subdivisions;
  18014. radius += (radiusTop - radiusBottom) / subdivisions;
  18015. positions.push(position.x, position.y, position.z);
  18016. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18017. }
  18018. }
  18019. subdivisions += 1;
  18020. for (var s = 0; s < subdivisions - 1; s++) {
  18021. for (var i = 0; i <= tessellation; i++) {
  18022. indices.push(i * subdivisions + s);
  18023. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18024. indices.push(i * subdivisions + (s + 1));
  18025. indices.push(i * subdivisions + (s + 1));
  18026. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18027. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  18028. }
  18029. }
  18030. createCylinderCap(true);
  18031. createCylinderCap(false);
  18032. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18033. var vertexData = new BABYLON.VertexData();
  18034. vertexData.indices = indices;
  18035. vertexData.positions = positions;
  18036. vertexData.normals = normals;
  18037. vertexData.uvs = uvs;
  18038. return vertexData;
  18039. };
  18040. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  18041. var indices = [];
  18042. var positions = [];
  18043. var normals = [];
  18044. var uvs = [];
  18045. diameter = diameter || 1;
  18046. thickness = thickness || 0.5;
  18047. tessellation = tessellation || 16;
  18048. var stride = tessellation + 1;
  18049. for (var i = 0; i <= tessellation; i++) {
  18050. var u = i / tessellation;
  18051. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  18052. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  18053. for (var j = 0; j <= tessellation; j++) {
  18054. var v = 1 - j / tessellation;
  18055. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  18056. var dx = Math.cos(innerAngle);
  18057. var dy = Math.sin(innerAngle);
  18058. var normal = new BABYLON.Vector3(dx, dy, 0);
  18059. var position = normal.scale(thickness / 2);
  18060. var textureCoordinate = new BABYLON.Vector2(u, v);
  18061. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  18062. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  18063. positions.push(position.x, position.y, position.z);
  18064. normals.push(normal.x, normal.y, normal.z);
  18065. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18066. var nextI = (i + 1) % stride;
  18067. var nextJ = (j + 1) % stride;
  18068. indices.push(i * stride + j);
  18069. indices.push(i * stride + nextJ);
  18070. indices.push(nextI * stride + j);
  18071. indices.push(i * stride + nextJ);
  18072. indices.push(nextI * stride + nextJ);
  18073. indices.push(nextI * stride + j);
  18074. }
  18075. }
  18076. var vertexData = new BABYLON.VertexData();
  18077. vertexData.indices = indices;
  18078. vertexData.positions = positions;
  18079. vertexData.normals = normals;
  18080. vertexData.uvs = uvs;
  18081. return vertexData;
  18082. };
  18083. VertexData.CreateLines = function (points) {
  18084. var indices = [];
  18085. var positions = [];
  18086. for (var index = 0; index < points.length; index++) {
  18087. positions.push(points[index].x, points[index].y, points[index].z);
  18088. if (index > 0) {
  18089. indices.push(index - 1);
  18090. indices.push(index);
  18091. }
  18092. }
  18093. var vertexData = new BABYLON.VertexData();
  18094. vertexData.indices = indices;
  18095. vertexData.positions = positions;
  18096. return vertexData;
  18097. };
  18098. VertexData.CreateGround = function (width, height, subdivisions) {
  18099. var indices = [];
  18100. var positions = [];
  18101. var normals = [];
  18102. var uvs = [];
  18103. var row, col;
  18104. width = width || 1;
  18105. height = height || 1;
  18106. subdivisions = subdivisions || 1;
  18107. for (row = 0; row <= subdivisions; row++) {
  18108. for (col = 0; col <= subdivisions; col++) {
  18109. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18110. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18111. positions.push(position.x, position.y, position.z);
  18112. normals.push(normal.x, normal.y, normal.z);
  18113. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18114. }
  18115. }
  18116. for (row = 0; row < subdivisions; row++) {
  18117. for (col = 0; col < subdivisions; col++) {
  18118. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18119. indices.push(col + 1 + row * (subdivisions + 1));
  18120. indices.push(col + row * (subdivisions + 1));
  18121. indices.push(col + (row + 1) * (subdivisions + 1));
  18122. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18123. indices.push(col + row * (subdivisions + 1));
  18124. }
  18125. }
  18126. var vertexData = new BABYLON.VertexData();
  18127. vertexData.indices = indices;
  18128. vertexData.positions = positions;
  18129. vertexData.normals = normals;
  18130. vertexData.uvs = uvs;
  18131. return vertexData;
  18132. };
  18133. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  18134. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  18135. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  18136. var indices = [];
  18137. var positions = [];
  18138. var normals = [];
  18139. var uvs = [];
  18140. var row, col, tileRow, tileCol;
  18141. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  18142. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  18143. precision.w = (precision.w < 1) ? 1 : precision.w;
  18144. precision.h = (precision.h < 1) ? 1 : precision.h;
  18145. var tileSize = {
  18146. 'w': (xmax - xmin) / subdivisions.w,
  18147. 'h': (zmax - zmin) / subdivisions.h
  18148. };
  18149. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  18150. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  18151. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  18152. }
  18153. }
  18154. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  18155. var base = positions.length / 3;
  18156. var rowLength = precision.w + 1;
  18157. for (row = 0; row < precision.h; row++) {
  18158. for (col = 0; col < precision.w; col++) {
  18159. var square = [
  18160. base + col + row * rowLength,
  18161. base + (col + 1) + row * rowLength,
  18162. base + (col + 1) + (row + 1) * rowLength,
  18163. base + col + (row + 1) * rowLength
  18164. ];
  18165. indices.push(square[1]);
  18166. indices.push(square[2]);
  18167. indices.push(square[3]);
  18168. indices.push(square[0]);
  18169. indices.push(square[1]);
  18170. indices.push(square[3]);
  18171. }
  18172. }
  18173. var position = BABYLON.Vector3.Zero();
  18174. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18175. for (row = 0; row <= precision.h; row++) {
  18176. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  18177. for (col = 0; col <= precision.w; col++) {
  18178. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  18179. position.y = 0;
  18180. positions.push(position.x, position.y, position.z);
  18181. normals.push(normal.x, normal.y, normal.z);
  18182. uvs.push(col / precision.w, row / precision.h);
  18183. }
  18184. }
  18185. }
  18186. var vertexData = new BABYLON.VertexData();
  18187. vertexData.indices = indices;
  18188. vertexData.positions = positions;
  18189. vertexData.normals = normals;
  18190. vertexData.uvs = uvs;
  18191. return vertexData;
  18192. };
  18193. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  18194. var indices = [];
  18195. var positions = [];
  18196. var normals = [];
  18197. var uvs = [];
  18198. var row, col;
  18199. for (row = 0; row <= subdivisions; row++) {
  18200. for (col = 0; col <= subdivisions; col++) {
  18201. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18202. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  18203. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  18204. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  18205. var r = buffer[pos] / 255.0;
  18206. var g = buffer[pos + 1] / 255.0;
  18207. var b = buffer[pos + 2] / 255.0;
  18208. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18209. position.y = minHeight + (maxHeight - minHeight) * gradient;
  18210. positions.push(position.x, position.y, position.z);
  18211. normals.push(0, 0, 0);
  18212. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18213. }
  18214. }
  18215. for (row = 0; row < subdivisions; row++) {
  18216. for (col = 0; col < subdivisions; col++) {
  18217. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18218. indices.push(col + 1 + row * (subdivisions + 1));
  18219. indices.push(col + row * (subdivisions + 1));
  18220. indices.push(col + (row + 1) * (subdivisions + 1));
  18221. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18222. indices.push(col + row * (subdivisions + 1));
  18223. }
  18224. }
  18225. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18226. var vertexData = new BABYLON.VertexData();
  18227. vertexData.indices = indices;
  18228. vertexData.positions = positions;
  18229. vertexData.normals = normals;
  18230. vertexData.uvs = uvs;
  18231. return vertexData;
  18232. };
  18233. VertexData.CreatePlane = function (size) {
  18234. var indices = [];
  18235. var positions = [];
  18236. var normals = [];
  18237. var uvs = [];
  18238. size = size || 1;
  18239. var halfSize = size / 2.0;
  18240. positions.push(-halfSize, -halfSize, 0);
  18241. normals.push(0, 0, -1.0);
  18242. uvs.push(0.0, 0.0);
  18243. positions.push(halfSize, -halfSize, 0);
  18244. normals.push(0, 0, -1.0);
  18245. uvs.push(1.0, 0.0);
  18246. positions.push(halfSize, halfSize, 0);
  18247. normals.push(0, 0, -1.0);
  18248. uvs.push(1.0, 1.0);
  18249. positions.push(-halfSize, halfSize, 0);
  18250. normals.push(0, 0, -1.0);
  18251. uvs.push(0.0, 1.0);
  18252. indices.push(0);
  18253. indices.push(1);
  18254. indices.push(2);
  18255. indices.push(0);
  18256. indices.push(2);
  18257. indices.push(3);
  18258. var vertexData = new BABYLON.VertexData();
  18259. vertexData.indices = indices;
  18260. vertexData.positions = positions;
  18261. vertexData.normals = normals;
  18262. vertexData.uvs = uvs;
  18263. return vertexData;
  18264. };
  18265. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  18266. var indices = [];
  18267. var positions = [];
  18268. var normals = [];
  18269. var uvs = [];
  18270. radius = radius || 2;
  18271. tube = tube || 0.5;
  18272. radialSegments = radialSegments || 32;
  18273. tubularSegments = tubularSegments || 32;
  18274. p = p || 2;
  18275. q = q || 3;
  18276. var getPos = function (angle) {
  18277. var cu = Math.cos(angle);
  18278. var su = Math.sin(angle);
  18279. var quOverP = q / p * angle;
  18280. var cs = Math.cos(quOverP);
  18281. var tx = radius * (2 + cs) * 0.5 * cu;
  18282. var ty = radius * (2 + cs) * su * 0.5;
  18283. var tz = radius * Math.sin(quOverP) * 0.5;
  18284. return new BABYLON.Vector3(tx, ty, tz);
  18285. };
  18286. for (var i = 0; i <= radialSegments; i++) {
  18287. var modI = i % radialSegments;
  18288. var u = modI / radialSegments * 2 * p * Math.PI;
  18289. var p1 = getPos(u);
  18290. var p2 = getPos(u + 0.01);
  18291. var tang = p2.subtract(p1);
  18292. var n = p2.add(p1);
  18293. var bitan = BABYLON.Vector3.Cross(tang, n);
  18294. n = BABYLON.Vector3.Cross(bitan, tang);
  18295. bitan.normalize();
  18296. n.normalize();
  18297. for (var j = 0; j < tubularSegments; j++) {
  18298. var modJ = j % tubularSegments;
  18299. var v = modJ / tubularSegments * 2 * Math.PI;
  18300. var cx = -tube * Math.cos(v);
  18301. var cy = tube * Math.sin(v);
  18302. positions.push(p1.x + cx * n.x + cy * bitan.x);
  18303. positions.push(p1.y + cx * n.y + cy * bitan.y);
  18304. positions.push(p1.z + cx * n.z + cy * bitan.z);
  18305. uvs.push(i / radialSegments);
  18306. uvs.push(j / tubularSegments);
  18307. }
  18308. }
  18309. for (i = 0; i < radialSegments; i++) {
  18310. for (j = 0; j < tubularSegments; j++) {
  18311. var jNext = (j + 1) % tubularSegments;
  18312. var a = i * tubularSegments + j;
  18313. var b = (i + 1) * tubularSegments + j;
  18314. var c = (i + 1) * tubularSegments + jNext;
  18315. var d = i * tubularSegments + jNext;
  18316. indices.push(d);
  18317. indices.push(b);
  18318. indices.push(a);
  18319. indices.push(d);
  18320. indices.push(c);
  18321. indices.push(b);
  18322. }
  18323. }
  18324. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18325. var vertexData = new BABYLON.VertexData();
  18326. vertexData.indices = indices;
  18327. vertexData.positions = positions;
  18328. vertexData.normals = normals;
  18329. vertexData.uvs = uvs;
  18330. return vertexData;
  18331. };
  18332. VertexData.ComputeNormals = function (positions, indices, normals) {
  18333. var positionVectors = [];
  18334. var facesOfVertices = [];
  18335. var index;
  18336. for (index = 0; index < positions.length; index += 3) {
  18337. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  18338. positionVectors.push(vector3);
  18339. facesOfVertices.push([]);
  18340. }
  18341. var facesNormals = [];
  18342. for (index = 0; index < indices.length / 3; index++) {
  18343. var i1 = indices[index * 3];
  18344. var i2 = indices[index * 3 + 1];
  18345. var i3 = indices[index * 3 + 2];
  18346. var p1 = positionVectors[i1];
  18347. var p2 = positionVectors[i2];
  18348. var p3 = positionVectors[i3];
  18349. var p1p2 = p1.subtract(p2);
  18350. var p3p2 = p3.subtract(p2);
  18351. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18352. facesOfVertices[i1].push(index);
  18353. facesOfVertices[i2].push(index);
  18354. facesOfVertices[i3].push(index);
  18355. }
  18356. for (index = 0; index < positionVectors.length; index++) {
  18357. var faces = facesOfVertices[index];
  18358. var normal = BABYLON.Vector3.Zero();
  18359. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  18360. normal.addInPlace(facesNormals[faces[faceIndex]]);
  18361. }
  18362. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  18363. normals[index * 3] = normal.x;
  18364. normals[index * 3 + 1] = normal.y;
  18365. normals[index * 3 + 2] = normal.z;
  18366. }
  18367. };
  18368. return VertexData;
  18369. })();
  18370. BABYLON.VertexData = VertexData;
  18371. })(BABYLON || (BABYLON = {}));
  18372. var __extends = this.__extends || function (d, b) {
  18373. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18374. function __() { this.constructor = d; }
  18375. __.prototype = b.prototype;
  18376. d.prototype = new __();
  18377. };
  18378. var BABYLON;
  18379. (function (BABYLON) {
  18380. var buildCamera = function (that, name) {
  18381. that._leftCamera.isIntermediate = true;
  18382. that.subCameras.push(that._leftCamera);
  18383. that.subCameras.push(that._rightCamera);
  18384. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  18385. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  18386. that._anaglyphPostProcess.onApply = function (effect) {
  18387. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  18388. };
  18389. that._update();
  18390. };
  18391. var AnaglyphArcRotateCamera = (function (_super) {
  18392. __extends(AnaglyphArcRotateCamera, _super);
  18393. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  18394. _super.call(this, name, alpha, beta, radius, target, scene);
  18395. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18396. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  18397. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  18398. buildCamera(this, name);
  18399. }
  18400. AnaglyphArcRotateCamera.prototype._update = function () {
  18401. this._updateCamera(this._leftCamera);
  18402. this._updateCamera(this._rightCamera);
  18403. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  18404. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  18405. _super.prototype._update.call(this);
  18406. };
  18407. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  18408. camera.beta = this.beta;
  18409. camera.radius = this.radius;
  18410. camera.minZ = this.minZ;
  18411. camera.maxZ = this.maxZ;
  18412. camera.fov = this.fov;
  18413. camera.target = this.target;
  18414. };
  18415. return AnaglyphArcRotateCamera;
  18416. })(BABYLON.ArcRotateCamera);
  18417. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  18418. var AnaglyphFreeCamera = (function (_super) {
  18419. __extends(AnaglyphFreeCamera, _super);
  18420. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  18421. _super.call(this, name, position, scene);
  18422. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  18423. this._transformMatrix = new BABYLON.Matrix();
  18424. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  18425. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  18426. buildCamera(this, name);
  18427. }
  18428. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  18429. var target = this.getTarget();
  18430. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  18431. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18432. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  18433. };
  18434. AnaglyphFreeCamera.prototype._update = function () {
  18435. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  18436. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  18437. this._updateCamera(this._leftCamera);
  18438. this._updateCamera(this._rightCamera);
  18439. _super.prototype._update.call(this);
  18440. };
  18441. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  18442. camera.minZ = this.minZ;
  18443. camera.maxZ = this.maxZ;
  18444. camera.fov = this.fov;
  18445. camera.viewport = this.viewport;
  18446. camera.setTarget(this.getTarget());
  18447. };
  18448. return AnaglyphFreeCamera;
  18449. })(BABYLON.FreeCamera);
  18450. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  18451. })(BABYLON || (BABYLON = {}));
  18452. var __extends = this.__extends || function (d, b) {
  18453. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18454. function __() { this.constructor = d; }
  18455. __.prototype = b.prototype;
  18456. d.prototype = new __();
  18457. };
  18458. var BABYLON;
  18459. (function (BABYLON) {
  18460. var AnaglyphPostProcess = (function (_super) {
  18461. __extends(AnaglyphPostProcess, _super);
  18462. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18463. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  18464. }
  18465. return AnaglyphPostProcess;
  18466. })(BABYLON.PostProcess);
  18467. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  18468. })(BABYLON || (BABYLON = {}));
  18469. var BABYLON;
  18470. (function (BABYLON) {
  18471. var Tags = (function () {
  18472. function Tags() {
  18473. }
  18474. Tags.EnableFor = function (obj) {
  18475. obj._tags = obj._tags || {};
  18476. obj.hasTags = function () {
  18477. return Tags.HasTags(obj);
  18478. };
  18479. obj.addTags = function (tagsString) {
  18480. return Tags.AddTagsTo(obj, tagsString);
  18481. };
  18482. obj.removeTags = function (tagsString) {
  18483. return Tags.RemoveTagsFrom(obj, tagsString);
  18484. };
  18485. obj.matchesTagsQuery = function (tagsQuery) {
  18486. return Tags.MatchesQuery(obj, tagsQuery);
  18487. };
  18488. };
  18489. Tags.DisableFor = function (obj) {
  18490. delete obj._tags;
  18491. delete obj.hasTags;
  18492. delete obj.addTags;
  18493. delete obj.removeTags;
  18494. delete obj.matchesTagsQuery;
  18495. };
  18496. Tags.HasTags = function (obj) {
  18497. if (!obj._tags) {
  18498. return false;
  18499. }
  18500. return !BABYLON.Tools.IsEmpty(obj._tags);
  18501. };
  18502. Tags.GetTags = function (obj) {
  18503. if (!obj._tags) {
  18504. return null;
  18505. }
  18506. return obj._tags;
  18507. };
  18508. Tags.AddTagsTo = function (obj, tagsString) {
  18509. if (!tagsString) {
  18510. return;
  18511. }
  18512. var tags = tagsString.split(" ");
  18513. for (var t in tags) {
  18514. Tags._AddTagTo(obj, tags[t]);
  18515. }
  18516. };
  18517. Tags._AddTagTo = function (obj, tag) {
  18518. tag = tag.trim();
  18519. if (tag === "" || tag === "true" || tag === "false") {
  18520. return;
  18521. }
  18522. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  18523. return;
  18524. }
  18525. Tags.EnableFor(obj);
  18526. obj._tags[tag] = true;
  18527. };
  18528. Tags.RemoveTagsFrom = function (obj, tagsString) {
  18529. if (!Tags.HasTags(obj)) {
  18530. return;
  18531. }
  18532. var tags = tagsString.split(" ");
  18533. for (var t in tags) {
  18534. Tags._RemoveTagFrom(obj, tags[t]);
  18535. }
  18536. };
  18537. Tags._RemoveTagFrom = function (obj, tag) {
  18538. delete obj._tags[tag];
  18539. };
  18540. Tags.MatchesQuery = function (obj, tagsQuery) {
  18541. if (tagsQuery === undefined) {
  18542. return true;
  18543. }
  18544. if (tagsQuery === "") {
  18545. return Tags.HasTags(obj);
  18546. }
  18547. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  18548. return Tags.HasTags(obj) && obj._tags[r];
  18549. });
  18550. };
  18551. return Tags;
  18552. })();
  18553. BABYLON.Tags = Tags;
  18554. })(BABYLON || (BABYLON = {}));
  18555. var BABYLON;
  18556. (function (BABYLON) {
  18557. (function (Internals) {
  18558. var AndOrNotEvaluator = (function () {
  18559. function AndOrNotEvaluator() {
  18560. }
  18561. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  18562. if (!query.match(/\([^\(\)]*\)/g)) {
  18563. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  18564. } else {
  18565. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  18566. r = r.slice(1, r.length - 1);
  18567. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  18568. });
  18569. }
  18570. if (query === "true") {
  18571. return true;
  18572. }
  18573. if (query === "false") {
  18574. return false;
  18575. }
  18576. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  18577. };
  18578. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  18579. evaluateCallback = evaluateCallback || (function (r) {
  18580. return r === "true" ? true : false;
  18581. });
  18582. var result;
  18583. var or = parenthesisContent.split("||");
  18584. for (var i in or) {
  18585. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  18586. var and = ori.split("&&");
  18587. if (and.length > 1) {
  18588. for (var j = 0; j < and.length; ++j) {
  18589. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  18590. if (andj !== "true" && andj !== "false") {
  18591. if (andj[0] === "!") {
  18592. result = !evaluateCallback(andj.substring(1));
  18593. } else {
  18594. result = evaluateCallback(andj);
  18595. }
  18596. } else {
  18597. result = andj === "true" ? true : false;
  18598. }
  18599. if (!result) {
  18600. ori = "false";
  18601. break;
  18602. }
  18603. }
  18604. }
  18605. if (result || ori === "true") {
  18606. result = true;
  18607. break;
  18608. }
  18609. if (ori !== "true" && ori !== "false") {
  18610. if (ori[0] === "!") {
  18611. result = !evaluateCallback(ori.substring(1));
  18612. } else {
  18613. result = evaluateCallback(ori);
  18614. }
  18615. } else {
  18616. result = ori === "true" ? true : false;
  18617. }
  18618. }
  18619. return result ? "true" : "false";
  18620. };
  18621. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  18622. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  18623. r = r.replace(/[\s]/g, function () {
  18624. return "";
  18625. });
  18626. return r.length % 2 ? "!" : "";
  18627. });
  18628. booleanString = booleanString.trim();
  18629. if (booleanString === "!true") {
  18630. booleanString = "false";
  18631. } else if (booleanString === "!false") {
  18632. booleanString = "true";
  18633. }
  18634. return booleanString;
  18635. };
  18636. return AndOrNotEvaluator;
  18637. })();
  18638. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  18639. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18640. var Internals = BABYLON.Internals;
  18641. })(BABYLON || (BABYLON = {}));
  18642. var BABYLON;
  18643. (function (BABYLON) {
  18644. var PostProcessRenderPass = (function () {
  18645. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  18646. this._enabled = true;
  18647. this._refCount = 0;
  18648. this._name = name;
  18649. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  18650. this.setRenderList(renderList);
  18651. this._renderTexture.onBeforeRender = beforeRender;
  18652. this._renderTexture.onAfterRender = afterRender;
  18653. this._scene = scene;
  18654. this._renderList = renderList;
  18655. }
  18656. PostProcessRenderPass.prototype._incRefCount = function () {
  18657. if (this._refCount === 0) {
  18658. this._scene.customRenderTargets.push(this._renderTexture);
  18659. }
  18660. return ++this._refCount;
  18661. };
  18662. PostProcessRenderPass.prototype._decRefCount = function () {
  18663. this._refCount--;
  18664. if (this._refCount <= 0) {
  18665. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  18666. }
  18667. return this._refCount;
  18668. };
  18669. PostProcessRenderPass.prototype._update = function () {
  18670. this.setRenderList(this._renderList);
  18671. };
  18672. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  18673. this._renderTexture.renderList = renderList;
  18674. };
  18675. PostProcessRenderPass.prototype.getRenderTexture = function () {
  18676. return this._renderTexture;
  18677. };
  18678. return PostProcessRenderPass;
  18679. })();
  18680. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  18681. })(BABYLON || (BABYLON = {}));
  18682. var BABYLON;
  18683. (function (BABYLON) {
  18684. var PostProcessRenderEffect = (function () {
  18685. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  18686. this._engine = engine;
  18687. this._name = name;
  18688. this._singleInstance = singleInstance || true;
  18689. this._getPostProcess = getPostProcess;
  18690. this._cameras = [];
  18691. this._postProcesses = [];
  18692. this._indicesForCamera = [];
  18693. this._renderPasses = [];
  18694. this._renderEffectAsPasses = [];
  18695. }
  18696. PostProcessRenderEffect.prototype._update = function () {
  18697. for (var renderPassName in this._renderPasses) {
  18698. this._renderPasses[renderPassName]._update();
  18699. }
  18700. };
  18701. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  18702. this._renderPasses[renderPass._name] = renderPass;
  18703. this._linkParameters();
  18704. };
  18705. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  18706. delete this._renderPasses[renderPass._name];
  18707. this._linkParameters();
  18708. };
  18709. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  18710. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  18711. this._linkParameters();
  18712. };
  18713. PostProcessRenderEffect.prototype.getPass = function (passName) {
  18714. for (var renderPassName in this._renderPasses) {
  18715. if (renderPassName === passName) {
  18716. return this._renderPasses[passName];
  18717. }
  18718. }
  18719. };
  18720. PostProcessRenderEffect.prototype.emptyPasses = function () {
  18721. this._renderPasses.length = 0;
  18722. this._linkParameters();
  18723. };
  18724. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  18725. var cameraKey;
  18726. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18727. for (var i = 0; i < _cam.length; i++) {
  18728. var camera = _cam[i];
  18729. var cameraName = camera.name;
  18730. if (this._singleInstance) {
  18731. cameraKey = 0;
  18732. } else {
  18733. cameraKey = cameraName;
  18734. }
  18735. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  18736. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  18737. if (!this._indicesForCamera[cameraName]) {
  18738. this._indicesForCamera[cameraName] = [];
  18739. }
  18740. this._indicesForCamera[cameraName].push(index);
  18741. if (this._cameras.indexOf(camera) === -1) {
  18742. this._cameras[cameraName] = camera;
  18743. }
  18744. for (var passName in this._renderPasses) {
  18745. this._renderPasses[passName]._incRefCount();
  18746. }
  18747. }
  18748. this._linkParameters();
  18749. };
  18750. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  18751. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18752. for (var i = 0; i < _cam.length; i++) {
  18753. var camera = _cam[i];
  18754. var cameraName = camera.name;
  18755. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18756. var index = this._cameras.indexOf(cameraName);
  18757. this._indicesForCamera.splice(index, 1);
  18758. this._cameras.splice(index, 1);
  18759. for (var passName in this._renderPasses) {
  18760. this._renderPasses[passName]._decRefCount();
  18761. }
  18762. }
  18763. };
  18764. PostProcessRenderEffect.prototype._enable = function (cameras) {
  18765. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18766. for (var i = 0; i < _cam.length; i++) {
  18767. var camera = _cam[i];
  18768. var cameraName = camera.name;
  18769. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  18770. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  18771. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  18772. }
  18773. }
  18774. for (var passName in this._renderPasses) {
  18775. this._renderPasses[passName]._incRefCount();
  18776. }
  18777. }
  18778. };
  18779. PostProcessRenderEffect.prototype._disable = function (cameras) {
  18780. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18781. for (var i = 0; i < _cam.length; i++) {
  18782. var camera = _cam[i];
  18783. var cameraName = camera.Name;
  18784. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  18785. for (var passName in this._renderPasses) {
  18786. this._renderPasses[passName]._decRefCount();
  18787. }
  18788. }
  18789. };
  18790. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  18791. if (this._singleInstance) {
  18792. return this._postProcesses[0];
  18793. } else {
  18794. return this._postProcesses[camera.name];
  18795. }
  18796. };
  18797. PostProcessRenderEffect.prototype._linkParameters = function () {
  18798. var _this = this;
  18799. for (var index in this._postProcesses) {
  18800. if (this.applyParameters) {
  18801. this.applyParameters(this._postProcesses[index]);
  18802. }
  18803. this._postProcesses[index].onBeforeRender = function (effect) {
  18804. _this._linkTextures(effect);
  18805. };
  18806. }
  18807. };
  18808. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  18809. for (var renderPassName in this._renderPasses) {
  18810. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  18811. }
  18812. for (var renderEffectName in this._renderEffectAsPasses) {
  18813. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  18814. }
  18815. };
  18816. return PostProcessRenderEffect;
  18817. })();
  18818. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  18819. })(BABYLON || (BABYLON = {}));
  18820. var BABYLON;
  18821. (function (BABYLON) {
  18822. var PostProcessRenderPipeline = (function () {
  18823. function PostProcessRenderPipeline(engine, name) {
  18824. this._engine = engine;
  18825. this._name = name;
  18826. this._renderEffects = [];
  18827. this._renderEffectsForIsolatedPass = [];
  18828. this._cameras = [];
  18829. }
  18830. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  18831. this._renderEffects[renderEffect._name] = renderEffect;
  18832. };
  18833. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  18834. var renderEffects = this._renderEffects[renderEffectName];
  18835. if (!renderEffects) {
  18836. return;
  18837. }
  18838. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18839. };
  18840. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  18841. var renderEffects = this._renderEffects[renderEffectName];
  18842. if (!renderEffects) {
  18843. return;
  18844. }
  18845. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  18846. };
  18847. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  18848. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18849. var indicesToDelete = [];
  18850. for (var i = 0; i < _cam.length; i++) {
  18851. var camera = _cam[i];
  18852. var cameraName = camera.name;
  18853. if (this._cameras.indexOf(camera) === -1) {
  18854. this._cameras[cameraName] = camera;
  18855. } else if (unique) {
  18856. indicesToDelete.push(i);
  18857. }
  18858. }
  18859. for (var i = 0; i < indicesToDelete.length; i++) {
  18860. cameras.splice(indicesToDelete[i], 1);
  18861. }
  18862. for (var renderEffectName in this._renderEffects) {
  18863. this._renderEffects[renderEffectName]._attachCameras(_cam);
  18864. }
  18865. };
  18866. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  18867. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18868. for (var renderEffectName in this._renderEffects) {
  18869. this._renderEffects[renderEffectName]._detachCameras(_cam);
  18870. }
  18871. for (var i = 0; i < _cam.length; i++) {
  18872. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  18873. }
  18874. };
  18875. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  18876. var _this = this;
  18877. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18878. var pass = null;
  18879. for (var renderEffectName in this._renderEffects) {
  18880. pass = this._renderEffects[renderEffectName].getPass(passName);
  18881. if (pass != null) {
  18882. break;
  18883. }
  18884. }
  18885. if (pass === null) {
  18886. return;
  18887. }
  18888. for (var renderEffectName in this._renderEffects) {
  18889. this._renderEffects[renderEffectName]._disable(_cam);
  18890. }
  18891. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  18892. for (var i = 0; i < _cam.length; i++) {
  18893. var camera = _cam[i];
  18894. var cameraName = camera.name;
  18895. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18896. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18897. });
  18898. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  18899. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  18900. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  18901. }
  18902. };
  18903. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  18904. var _this = this;
  18905. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  18906. for (var i = 0; i < _cam.length; i++) {
  18907. var camera = _cam[i];
  18908. var cameraName = camera.name;
  18909. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  18910. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  18911. });
  18912. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  18913. }
  18914. for (var renderEffectName in this._renderEffects) {
  18915. this._renderEffects[renderEffectName]._enable(_cam);
  18916. }
  18917. };
  18918. PostProcessRenderPipeline.prototype._update = function () {
  18919. for (var renderEffectName in this._renderEffects) {
  18920. this._renderEffects[renderEffectName]._update();
  18921. }
  18922. for (var i = 0; i < this._cameras.length; i++) {
  18923. var cameraName = this._cameras[i].name;
  18924. if (this._renderEffectsForIsolatedPass[cameraName]) {
  18925. this._renderEffectsForIsolatedPass[cameraName]._update();
  18926. }
  18927. }
  18928. };
  18929. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  18930. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  18931. return PostProcessRenderPipeline;
  18932. })();
  18933. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  18934. })(BABYLON || (BABYLON = {}));
  18935. var BABYLON;
  18936. (function (BABYLON) {
  18937. var PostProcessRenderPipelineManager = (function () {
  18938. function PostProcessRenderPipelineManager() {
  18939. this._renderPipelines = new Array();
  18940. }
  18941. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  18942. this._renderPipelines[renderPipeline._name] = renderPipeline;
  18943. };
  18944. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  18945. var renderPipeline = this._renderPipelines[renderPipelineName];
  18946. if (!renderPipeline) {
  18947. return;
  18948. }
  18949. renderPipeline._attachCameras(cameras, unique);
  18950. };
  18951. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  18952. var renderPipeline = this._renderPipelines[renderPipelineName];
  18953. if (!renderPipeline) {
  18954. return;
  18955. }
  18956. renderPipeline._detachCameras(cameras);
  18957. };
  18958. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18959. var renderPipeline = this._renderPipelines[renderPipelineName];
  18960. if (!renderPipeline) {
  18961. return;
  18962. }
  18963. renderPipeline._enableEffect(renderEffectName, cameras);
  18964. };
  18965. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  18966. var renderPipeline = this._renderPipelines[renderPipelineName];
  18967. if (!renderPipeline) {
  18968. return;
  18969. }
  18970. renderPipeline._disableEffect(renderEffectName, cameras);
  18971. };
  18972. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  18973. var renderPipeline = this._renderPipelines[renderPipelineName];
  18974. if (!renderPipeline) {
  18975. return;
  18976. }
  18977. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  18978. };
  18979. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  18980. var renderPipeline = this._renderPipelines[renderPipelineName];
  18981. if (!renderPipeline) {
  18982. return;
  18983. }
  18984. renderPipeline._disableDisplayOnlyPass(cameras);
  18985. };
  18986. PostProcessRenderPipelineManager.prototype.update = function () {
  18987. for (var renderPipelineName in this._renderPipelines) {
  18988. this._renderPipelines[renderPipelineName]._update();
  18989. }
  18990. };
  18991. return PostProcessRenderPipelineManager;
  18992. })();
  18993. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  18994. })(BABYLON || (BABYLON = {}));
  18995. var __extends = this.__extends || function (d, b) {
  18996. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18997. function __() { this.constructor = d; }
  18998. __.prototype = b.prototype;
  18999. d.prototype = new __();
  19000. };
  19001. var BABYLON;
  19002. (function (BABYLON) {
  19003. var DisplayPassPostProcess = (function (_super) {
  19004. __extends(DisplayPassPostProcess, _super);
  19005. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19006. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  19007. }
  19008. return DisplayPassPostProcess;
  19009. })(BABYLON.PostProcess);
  19010. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  19011. })(BABYLON || (BABYLON = {}));
  19012. var BABYLON;
  19013. (function (BABYLON) {
  19014. var BoundingBoxRenderer = (function () {
  19015. function BoundingBoxRenderer(scene) {
  19016. this.frontColor = new BABYLON.Color3(1, 1, 1);
  19017. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  19018. this.showBackLines = true;
  19019. this.renderList = new BABYLON.SmartArray(32);
  19020. this._scene = scene;
  19021. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19022. attributes: ["position"],
  19023. uniforms: ["worldViewProjection", "color"]
  19024. });
  19025. var engine = this._scene.getEngine();
  19026. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  19027. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  19028. 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]);
  19029. }
  19030. BoundingBoxRenderer.prototype.reset = function () {
  19031. this.renderList.reset();
  19032. };
  19033. BoundingBoxRenderer.prototype.render = function () {
  19034. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  19035. return;
  19036. }
  19037. var engine = this._scene.getEngine();
  19038. engine.setDepthWrite(false);
  19039. this._colorShader._preBind();
  19040. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  19041. var boundingBox = this.renderList.data[boundingBoxIndex];
  19042. var min = boundingBox.minimum;
  19043. var max = boundingBox.maximum;
  19044. var diff = max.subtract(min);
  19045. var median = min.add(diff.scale(0.5));
  19046. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  19047. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  19048. if (this.showBackLines) {
  19049. engine.setDepthFunctionToGreaterOrEqual();
  19050. this._colorShader.setColor4("color", this.backColor.toColor4());
  19051. this._colorShader.bind(worldMatrix);
  19052. engine.draw(false, 0, 24);
  19053. }
  19054. engine.setDepthFunctionToLess();
  19055. this._colorShader.setColor4("color", this.frontColor.toColor4());
  19056. this._colorShader.bind(worldMatrix);
  19057. engine.draw(false, 0, 24);
  19058. }
  19059. this._colorShader.unbind();
  19060. engine.setDepthFunctionToLessOrEqual();
  19061. engine.setDepthWrite(true);
  19062. };
  19063. BoundingBoxRenderer.prototype.dispose = function () {
  19064. this._colorShader.dispose();
  19065. this._vb.dispose();
  19066. this._scene.getEngine()._releaseBuffer(this._ib);
  19067. };
  19068. return BoundingBoxRenderer;
  19069. })();
  19070. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  19071. })(BABYLON || (BABYLON = {}));
  19072. /**
  19073. * Based on jsTGALoader - Javascript loader for TGA file
  19074. * By Vincent Thibault
  19075. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  19076. */
  19077. var BABYLON;
  19078. (function (BABYLON) {
  19079. (function (Internals) {
  19080. var TGATools = (function () {
  19081. function TGATools() {
  19082. }
  19083. TGATools.GetTGAHeader = function (data) {
  19084. var offset = 0;
  19085. var header = {
  19086. id_length: data[offset++],
  19087. colormap_type: data[offset++],
  19088. image_type: data[offset++],
  19089. colormap_index: data[offset++] | data[offset++] << 8,
  19090. colormap_length: data[offset++] | data[offset++] << 8,
  19091. colormap_size: data[offset++],
  19092. origin: [
  19093. data[offset++] | data[offset++] << 8,
  19094. data[offset++] | data[offset++] << 8
  19095. ],
  19096. width: data[offset++] | data[offset++] << 8,
  19097. height: data[offset++] | data[offset++] << 8,
  19098. pixel_size: data[offset++],
  19099. flags: data[offset++]
  19100. };
  19101. return header;
  19102. };
  19103. TGATools.UploadContent = function (gl, data) {
  19104. if (data.length < 19) {
  19105. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  19106. return;
  19107. }
  19108. var offset = 18;
  19109. var header = TGATools.GetTGAHeader(data);
  19110. if (header.id_length + offset > data.length) {
  19111. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  19112. return;
  19113. }
  19114. offset += header.id_length;
  19115. var use_rle = false;
  19116. var use_pal = false;
  19117. var use_rgb = false;
  19118. var use_grey = false;
  19119. switch (header.image_type) {
  19120. case TGATools._TYPE_RLE_INDEXED:
  19121. use_rle = true;
  19122. case TGATools._TYPE_INDEXED:
  19123. use_pal = true;
  19124. break;
  19125. case TGATools._TYPE_RLE_RGB:
  19126. use_rle = true;
  19127. case TGATools._TYPE_RGB:
  19128. use_rgb = true;
  19129. break;
  19130. case TGATools._TYPE_RLE_GREY:
  19131. use_rle = true;
  19132. case TGATools._TYPE_GREY:
  19133. use_grey = true;
  19134. break;
  19135. }
  19136. var pixel_data;
  19137. var numAlphaBits = header.flags & 0xf;
  19138. var pixel_size = header.pixel_size >> 3;
  19139. var pixel_total = header.width * header.height * pixel_size;
  19140. var palettes;
  19141. if (use_pal) {
  19142. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  19143. }
  19144. if (use_rle) {
  19145. pixel_data = new Uint8Array(pixel_total);
  19146. var c, count, i;
  19147. var localOffset = 0;
  19148. var pixels = new Uint8Array(pixel_size);
  19149. while (offset < pixel_total && localOffset < pixel_total) {
  19150. c = data[offset++];
  19151. count = (c & 0x7f) + 1;
  19152. if (c & 0x80) {
  19153. for (i = 0; i < pixel_size; ++i) {
  19154. pixels[i] = data[offset++];
  19155. }
  19156. for (i = 0; i < count; ++i) {
  19157. pixel_data.set(pixels, localOffset + i * pixel_size);
  19158. }
  19159. localOffset += pixel_size * count;
  19160. } else {
  19161. count *= pixel_size;
  19162. for (i = 0; i < count; ++i) {
  19163. pixel_data[localOffset + i] = data[offset++];
  19164. }
  19165. localOffset += count;
  19166. }
  19167. }
  19168. } else {
  19169. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  19170. }
  19171. var x_start, y_start, x_step, y_step, y_end, x_end;
  19172. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  19173. default:
  19174. case TGATools._ORIGIN_UL:
  19175. x_start = 0;
  19176. x_step = 1;
  19177. x_end = header.width;
  19178. y_start = 0;
  19179. y_step = 1;
  19180. y_end = header.height;
  19181. break;
  19182. case TGATools._ORIGIN_BL:
  19183. x_start = 0;
  19184. x_step = 1;
  19185. x_end = header.width;
  19186. y_start = header.height - 1;
  19187. y_step = -1;
  19188. y_end = -1;
  19189. break;
  19190. case TGATools._ORIGIN_UR:
  19191. x_start = header.width - 1;
  19192. x_step = -1;
  19193. x_end = -1;
  19194. y_start = 0;
  19195. y_step = 1;
  19196. y_end = header.height;
  19197. break;
  19198. case TGATools._ORIGIN_BR:
  19199. x_start = header.width - 1;
  19200. x_step = -1;
  19201. x_end = -1;
  19202. y_start = header.height - 1;
  19203. y_step = -1;
  19204. y_end = -1;
  19205. break;
  19206. }
  19207. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  19208. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  19209. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  19210. };
  19211. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19212. var image = pixel_data, colormap = palettes;
  19213. var width = header.width, height = header.height;
  19214. var color, i = 0, x, y;
  19215. var imageData = new Uint8Array(width * height * 4);
  19216. for (y = y_start; y !== y_end; y += y_step) {
  19217. for (x = x_start; x !== x_end; x += x_step, i++) {
  19218. color = image[i];
  19219. imageData[(x + width * y) * 4 + 3] = 255;
  19220. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  19221. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  19222. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  19223. }
  19224. }
  19225. return imageData;
  19226. };
  19227. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19228. var image = pixel_data;
  19229. var width = header.width, height = header.height;
  19230. var color, i = 0, x, y;
  19231. var imageData = new Uint8Array(width * height * 4);
  19232. for (y = y_start; y !== y_end; y += y_step) {
  19233. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19234. color = image[i + 0] + (image[i + 1] << 8);
  19235. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  19236. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  19237. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  19238. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  19239. }
  19240. }
  19241. return imageData;
  19242. };
  19243. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19244. var image = pixel_data;
  19245. var width = header.width, height = header.height;
  19246. var i = 0, x, y;
  19247. var imageData = new Uint8Array(width * height * 4);
  19248. for (y = y_start; y !== y_end; y += y_step) {
  19249. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  19250. imageData[(x + width * y) * 4 + 3] = 255;
  19251. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19252. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19253. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19254. }
  19255. }
  19256. return imageData;
  19257. };
  19258. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19259. var image = pixel_data;
  19260. var width = header.width, height = header.height;
  19261. var i = 0, x, y;
  19262. var imageData = new Uint8Array(width * height * 4);
  19263. for (y = y_start; y !== y_end; y += y_step) {
  19264. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  19265. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19266. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19267. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19268. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  19269. }
  19270. }
  19271. return imageData;
  19272. };
  19273. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19274. var image = pixel_data;
  19275. var width = header.width, height = header.height;
  19276. var color, i = 0, x, y;
  19277. var imageData = new Uint8Array(width * height * 4);
  19278. for (y = y_start; y !== y_end; y += y_step) {
  19279. for (x = x_start; x !== x_end; x += x_step, i++) {
  19280. color = image[i];
  19281. imageData[(x + width * y) * 4 + 0] = color;
  19282. imageData[(x + width * y) * 4 + 1] = color;
  19283. imageData[(x + width * y) * 4 + 2] = color;
  19284. imageData[(x + width * y) * 4 + 3] = 255;
  19285. }
  19286. }
  19287. return imageData;
  19288. };
  19289. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19290. var image = pixel_data;
  19291. var width = header.width, height = header.height;
  19292. var i = 0, x, y;
  19293. var imageData = new Uint8Array(width * height * 4);
  19294. for (y = y_start; y !== y_end; y += y_step) {
  19295. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19296. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  19297. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  19298. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19299. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  19300. }
  19301. }
  19302. return imageData;
  19303. };
  19304. TGATools._TYPE_NO_DATA = 0;
  19305. TGATools._TYPE_INDEXED = 1;
  19306. TGATools._TYPE_RGB = 2;
  19307. TGATools._TYPE_GREY = 3;
  19308. TGATools._TYPE_RLE_INDEXED = 9;
  19309. TGATools._TYPE_RLE_RGB = 10;
  19310. TGATools._TYPE_RLE_GREY = 11;
  19311. TGATools._ORIGIN_MASK = 0x30;
  19312. TGATools._ORIGIN_SHIFT = 0x04;
  19313. TGATools._ORIGIN_BL = 0x00;
  19314. TGATools._ORIGIN_BR = 0x01;
  19315. TGATools._ORIGIN_UL = 0x02;
  19316. TGATools._ORIGIN_UR = 0x03;
  19317. return TGATools;
  19318. })();
  19319. Internals.TGATools = TGATools;
  19320. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19321. var Internals = BABYLON.Internals;
  19322. })(BABYLON || (BABYLON = {}));
  19323. var BABYLON;
  19324. (function (BABYLON) {
  19325. (function (Internals) {
  19326. var DDS_MAGIC = 0x20534444;
  19327. 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;
  19328. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  19329. 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;
  19330. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  19331. function FourCCToInt32(value) {
  19332. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  19333. }
  19334. function Int32ToFourCC(value) {
  19335. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  19336. }
  19337. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  19338. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  19339. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  19340. var headerLengthInt = 31;
  19341. var off_magic = 0;
  19342. var off_size = 1;
  19343. var off_flags = 2;
  19344. var off_height = 3;
  19345. var off_width = 4;
  19346. var off_mipmapCount = 7;
  19347. var off_pfFlags = 20;
  19348. var off_pfFourCC = 21;
  19349. var off_RGBbpp = 22;
  19350. var off_RMask = 23;
  19351. var off_GMask = 24;
  19352. var off_BMask = 25;
  19353. var off_AMask = 26;
  19354. var off_caps1 = 27;
  19355. var off_caps2 = 28;
  19356. ;
  19357. var DDSTools = (function () {
  19358. function DDSTools() {
  19359. }
  19360. DDSTools.GetDDSInfo = function (arrayBuffer) {
  19361. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  19362. var mipmapCount = 1;
  19363. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  19364. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19365. }
  19366. return {
  19367. width: header[off_width],
  19368. height: header[off_height],
  19369. mipmapCount: mipmapCount,
  19370. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  19371. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  19372. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  19373. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  19374. };
  19375. };
  19376. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19377. var byteArray = new Uint8Array(dataLength);
  19378. var srcData = new Uint8Array(arrayBuffer);
  19379. var index = 0;
  19380. for (var y = height - 1; y >= 0; y--) {
  19381. for (var x = 0; x < width; x++) {
  19382. var srcPos = dataOffset + (x + y * width) * 4;
  19383. byteArray[index + 2] = srcData[srcPos];
  19384. byteArray[index + 1] = srcData[srcPos + 1];
  19385. byteArray[index] = srcData[srcPos + 2];
  19386. byteArray[index + 3] = srcData[srcPos + 3];
  19387. index += 4;
  19388. }
  19389. }
  19390. return byteArray;
  19391. };
  19392. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19393. var byteArray = new Uint8Array(dataLength);
  19394. var srcData = new Uint8Array(arrayBuffer);
  19395. var index = 0;
  19396. for (var y = height - 1; y >= 0; y--) {
  19397. for (var x = 0; x < width; x++) {
  19398. var srcPos = dataOffset + (x + y * width) * 3;
  19399. byteArray[index + 2] = srcData[srcPos];
  19400. byteArray[index + 1] = srcData[srcPos + 1];
  19401. byteArray[index] = srcData[srcPos + 2];
  19402. index += 3;
  19403. }
  19404. }
  19405. return byteArray;
  19406. };
  19407. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19408. var byteArray = new Uint8Array(dataLength);
  19409. var srcData = new Uint8Array(arrayBuffer);
  19410. var index = 0;
  19411. for (var y = height - 1; y >= 0; y--) {
  19412. for (var x = 0; x < width; x++) {
  19413. var srcPos = dataOffset + (x + y * width);
  19414. byteArray[index] = srcData[srcPos];
  19415. index++;
  19416. }
  19417. }
  19418. return byteArray;
  19419. };
  19420. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  19421. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  19422. if (header[off_magic] != DDS_MAGIC) {
  19423. BABYLON.Tools.Error("Invalid magic number in DDS header");
  19424. return;
  19425. }
  19426. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  19427. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  19428. return;
  19429. }
  19430. if (info.isFourCC) {
  19431. fourCC = header[off_pfFourCC];
  19432. switch (fourCC) {
  19433. case FOURCC_DXT1:
  19434. blockBytes = 8;
  19435. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  19436. break;
  19437. case FOURCC_DXT3:
  19438. blockBytes = 16;
  19439. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  19440. break;
  19441. case FOURCC_DXT5:
  19442. blockBytes = 16;
  19443. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  19444. break;
  19445. default:
  19446. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  19447. return;
  19448. }
  19449. }
  19450. mipmapCount = 1;
  19451. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  19452. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19453. }
  19454. var bpp = header[off_RGBbpp];
  19455. for (var face = 0; face < faces; face++) {
  19456. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  19457. width = header[off_width];
  19458. height = header[off_height];
  19459. dataOffset = header[off_size] + 4;
  19460. for (i = 0; i < mipmapCount; ++i) {
  19461. if (info.isRGB) {
  19462. if (bpp == 24) {
  19463. dataLength = width * height * 3;
  19464. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19465. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  19466. } else {
  19467. dataLength = width * height * 4;
  19468. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19469. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  19470. }
  19471. } else if (info.isLuminance) {
  19472. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  19473. var unpaddedRowSize = width;
  19474. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  19475. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  19476. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  19477. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  19478. } else {
  19479. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  19480. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  19481. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  19482. }
  19483. dataOffset += dataLength;
  19484. width *= 0.5;
  19485. height *= 0.5;
  19486. width = Math.max(1.0, width);
  19487. height = Math.max(1.0, height);
  19488. }
  19489. }
  19490. };
  19491. return DDSTools;
  19492. })();
  19493. Internals.DDSTools = DDSTools;
  19494. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19495. var Internals = BABYLON.Internals;
  19496. })(BABYLON || (BABYLON = {}));
  19497. var BABYLON;
  19498. (function (BABYLON) {
  19499. var SmartArray = (function () {
  19500. function SmartArray(capacity) {
  19501. this.length = 0;
  19502. this._duplicateId = 0;
  19503. this.data = new Array(capacity);
  19504. this._id = SmartArray._GlobalId++;
  19505. }
  19506. SmartArray.prototype.push = function (value) {
  19507. this.data[this.length++] = value;
  19508. if (this.length > this.data.length) {
  19509. this.data.length *= 2;
  19510. }
  19511. if (!value.__smartArrayFlags) {
  19512. value.__smartArrayFlags = {};
  19513. }
  19514. value.__smartArrayFlags[this._id] = this._duplicateId;
  19515. };
  19516. SmartArray.prototype.pushNoDuplicate = function (value) {
  19517. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  19518. return;
  19519. }
  19520. this.push(value);
  19521. };
  19522. SmartArray.prototype.sort = function (compareFn) {
  19523. this.data.sort(compareFn);
  19524. };
  19525. SmartArray.prototype.reset = function () {
  19526. this.length = 0;
  19527. this._duplicateId++;
  19528. };
  19529. SmartArray.prototype.concat = function (array) {
  19530. if (array.length === 0) {
  19531. return;
  19532. }
  19533. if (this.length + array.length > this.data.length) {
  19534. this.data.length = (this.length + array.length) * 2;
  19535. }
  19536. for (var index = 0; index < array.length; index++) {
  19537. this.data[this.length++] = (array.data || array)[index];
  19538. }
  19539. };
  19540. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  19541. if (array.length === 0) {
  19542. return;
  19543. }
  19544. if (this.length + array.length > this.data.length) {
  19545. this.data.length = (this.length + array.length) * 2;
  19546. }
  19547. for (var index = 0; index < array.length; index++) {
  19548. var item = (array.data || array)[index];
  19549. this.pushNoDuplicate(item);
  19550. }
  19551. };
  19552. SmartArray.prototype.indexOf = function (value) {
  19553. var position = this.data.indexOf(value);
  19554. if (position >= this.length) {
  19555. return -1;
  19556. }
  19557. return position;
  19558. };
  19559. SmartArray._GlobalId = 0;
  19560. return SmartArray;
  19561. })();
  19562. BABYLON.SmartArray = SmartArray;
  19563. })(BABYLON || (BABYLON = {}));
  19564. var BABYLON;
  19565. (function (BABYLON) {
  19566. var CannonJSPlugin = (function () {
  19567. function CannonJSPlugin() {
  19568. this._registeredMeshes = [];
  19569. this._physicsMaterials = [];
  19570. this.updateBodyPosition = function (mesh) {
  19571. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19572. var registeredMesh = this._registeredMeshes[index];
  19573. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  19574. var body = registeredMesh.body;
  19575. var center = mesh.getBoundingInfo().boundingBox.center;
  19576. body.position.set(center.x, center.z, center.y);
  19577. body.quaternion.x = mesh.rotationQuaternion.x;
  19578. body.quaternion.z = mesh.rotationQuaternion.y;
  19579. body.quaternion.y = mesh.rotationQuaternion.z;
  19580. body.quaternion.w = -mesh.rotationQuaternion.w;
  19581. return;
  19582. }
  19583. }
  19584. };
  19585. }
  19586. CannonJSPlugin.prototype.initialize = function (iterations) {
  19587. if (typeof iterations === "undefined") { iterations = 10; }
  19588. this._world = new CANNON.World();
  19589. this._world.broadphase = new CANNON.NaiveBroadphase();
  19590. this._world.solver.iterations = iterations;
  19591. };
  19592. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  19593. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  19594. };
  19595. CannonJSPlugin.prototype.runOneStep = function (delta) {
  19596. this._world.step(delta);
  19597. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19598. var registeredMesh = this._registeredMeshes[index];
  19599. if (registeredMesh.isChild) {
  19600. continue;
  19601. }
  19602. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  19603. var deltaPos = registeredMesh.delta;
  19604. if (deltaPos) {
  19605. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  19606. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  19607. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  19608. } else {
  19609. registeredMesh.mesh.position.x = bodyX;
  19610. registeredMesh.mesh.position.y = bodyZ;
  19611. registeredMesh.mesh.position.z = bodyY;
  19612. }
  19613. if (!registeredMesh.mesh.rotationQuaternion) {
  19614. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19615. }
  19616. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  19617. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  19618. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  19619. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  19620. }
  19621. };
  19622. CannonJSPlugin.prototype.setGravity = function (gravity) {
  19623. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  19624. };
  19625. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  19626. this.unregisterMesh(mesh);
  19627. mesh.computeWorldMatrix(true);
  19628. switch (impostor) {
  19629. case BABYLON.PhysicsEngine.SphereImpostor:
  19630. var bbox = mesh.getBoundingInfo().boundingBox;
  19631. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  19632. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  19633. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  19634. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  19635. case BABYLON.PhysicsEngine.BoxImpostor:
  19636. bbox = mesh.getBoundingInfo().boundingBox;
  19637. var min = bbox.minimumWorld;
  19638. var max = bbox.maximumWorld;
  19639. var box = max.subtract(min).scale(0.5);
  19640. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  19641. case BABYLON.PhysicsEngine.PlaneImpostor:
  19642. return this._createPlane(mesh, options);
  19643. case BABYLON.PhysicsEngine.MeshImpostor:
  19644. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19645. var rawFaces = mesh.getIndices();
  19646. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  19647. }
  19648. return null;
  19649. };
  19650. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  19651. var shape = new CANNON.Sphere(radius);
  19652. if (!options) {
  19653. return shape;
  19654. }
  19655. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19656. };
  19657. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  19658. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  19659. if (!options) {
  19660. return shape;
  19661. }
  19662. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19663. };
  19664. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  19665. var shape = new CANNON.Plane();
  19666. if (!options) {
  19667. return shape;
  19668. }
  19669. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19670. };
  19671. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  19672. var verts = [], faces = [];
  19673. mesh.computeWorldMatrix(true);
  19674. for (var i = 0; i < rawVerts.length; i += 3) {
  19675. var transformed = BABYLON.Vector3.Zero();
  19676. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  19677. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  19678. }
  19679. for (var j = 0; j < rawFaces.length; j += 3) {
  19680. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  19681. }
  19682. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  19683. if (!options) {
  19684. return shape;
  19685. }
  19686. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  19687. };
  19688. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  19689. var index;
  19690. var mat;
  19691. for (index = 0; index < this._physicsMaterials.length; index++) {
  19692. mat = this._physicsMaterials[index];
  19693. if (mat.friction === friction && mat.restitution === restitution) {
  19694. return mat;
  19695. }
  19696. }
  19697. var currentMat = new CANNON.Material();
  19698. currentMat.friction = friction;
  19699. currentMat.restitution = restitution;
  19700. this._physicsMaterials.push(currentMat);
  19701. for (index = 0; index < this._physicsMaterials.length; index++) {
  19702. mat = this._physicsMaterials[index];
  19703. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  19704. contactMaterial.contactEquationStiffness = 1e10;
  19705. contactMaterial.contactEquationRegularizationTime = 10;
  19706. this._world.addContactMaterial(contactMaterial);
  19707. }
  19708. return currentMat;
  19709. };
  19710. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  19711. var initialRotation = null;
  19712. if (mesh.rotationQuaternion) {
  19713. initialRotation = mesh.rotationQuaternion.clone();
  19714. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  19715. }
  19716. var bbox = mesh.getBoundingInfo().boundingBox;
  19717. var deltaPosition = mesh.position.subtract(bbox.center);
  19718. var material = this._addMaterial(friction, restitution);
  19719. var body = new CANNON.RigidBody(mass, shape, material);
  19720. if (initialRotation) {
  19721. body.quaternion.x = initialRotation.x;
  19722. body.quaternion.z = initialRotation.y;
  19723. body.quaternion.y = initialRotation.z;
  19724. body.quaternion.w = -initialRotation.w;
  19725. }
  19726. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  19727. this._world.add(body);
  19728. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  19729. return body;
  19730. };
  19731. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  19732. var compoundShape = new CANNON.Compound();
  19733. for (var index = 0; index < parts.length; index++) {
  19734. var mesh = parts[index].mesh;
  19735. var shape = this.registerMesh(mesh, parts[index].impostor);
  19736. if (index == 0) {
  19737. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  19738. } else {
  19739. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  19740. }
  19741. }
  19742. var initialMesh = parts[0].mesh;
  19743. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  19744. body.parts = parts;
  19745. return body;
  19746. };
  19747. CannonJSPlugin.prototype._unbindBody = function (body) {
  19748. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19749. var registeredMesh = this._registeredMeshes[index];
  19750. if (registeredMesh.body === body) {
  19751. registeredMesh.body = null;
  19752. registeredMesh.delta = 0;
  19753. }
  19754. }
  19755. };
  19756. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  19757. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19758. var registeredMesh = this._registeredMeshes[index];
  19759. if (registeredMesh.mesh === mesh) {
  19760. if (registeredMesh.body) {
  19761. this._world.remove(registeredMesh.body);
  19762. this._unbindBody(registeredMesh.body);
  19763. }
  19764. this._registeredMeshes.splice(index, 1);
  19765. return;
  19766. }
  19767. }
  19768. };
  19769. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  19770. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  19771. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  19772. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19773. var registeredMesh = this._registeredMeshes[index];
  19774. if (registeredMesh.mesh === mesh) {
  19775. registeredMesh.body.applyImpulse(impulse, worldPoint);
  19776. return;
  19777. }
  19778. }
  19779. };
  19780. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  19781. var body1 = null, body2 = null;
  19782. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19783. var registeredMesh = this._registeredMeshes[index];
  19784. if (registeredMesh.mesh === mesh1) {
  19785. body1 = registeredMesh.body;
  19786. } else if (registeredMesh.mesh === mesh2) {
  19787. body2 = registeredMesh.body;
  19788. }
  19789. }
  19790. if (!body1 || !body2) {
  19791. return false;
  19792. }
  19793. 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));
  19794. this._world.addConstraint(constraint);
  19795. return true;
  19796. };
  19797. CannonJSPlugin.prototype.dispose = function () {
  19798. while (this._registeredMeshes.length) {
  19799. this.unregisterMesh(this._registeredMeshes[0].mesh);
  19800. }
  19801. };
  19802. CannonJSPlugin.prototype.isSupported = function () {
  19803. return window.CANNON !== undefined;
  19804. };
  19805. return CannonJSPlugin;
  19806. })();
  19807. BABYLON.CannonJSPlugin = CannonJSPlugin;
  19808. })(BABYLON || (BABYLON = {}));
  19809. var __extends = this.__extends || function (d, b) {
  19810. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19811. function __() { this.constructor = d; }
  19812. __.prototype = b.prototype;
  19813. d.prototype = new __();
  19814. };
  19815. var BABYLON;
  19816. (function (BABYLON) {
  19817. var Condition = (function () {
  19818. function Condition(actionManager) {
  19819. this._actionManager = actionManager;
  19820. }
  19821. Condition.prototype.isValid = function () {
  19822. return true;
  19823. };
  19824. Condition.prototype._getProperty = function (propertyPath) {
  19825. return this._actionManager._getProperty(propertyPath);
  19826. };
  19827. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  19828. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19829. };
  19830. return Condition;
  19831. })();
  19832. BABYLON.Condition = Condition;
  19833. var ValueCondition = (function (_super) {
  19834. __extends(ValueCondition, _super);
  19835. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  19836. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  19837. _super.call(this, actionManager);
  19838. this.propertyPath = propertyPath;
  19839. this.value = value;
  19840. this.operator = operator;
  19841. this._target = this._getEffectiveTarget(target, this.propertyPath);
  19842. this._property = this._getProperty(this.propertyPath);
  19843. }
  19844. Object.defineProperty(ValueCondition, "IsEqual", {
  19845. get: function () {
  19846. return ValueCondition._IsEqual;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(ValueCondition, "IsDifferent", {
  19852. get: function () {
  19853. return ValueCondition._IsDifferent;
  19854. },
  19855. enumerable: true,
  19856. configurable: true
  19857. });
  19858. Object.defineProperty(ValueCondition, "IsGreater", {
  19859. get: function () {
  19860. return ValueCondition._IsGreater;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(ValueCondition, "IsLesser", {
  19866. get: function () {
  19867. return ValueCondition._IsLesser;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. ValueCondition.prototype.isValid = function () {
  19873. switch (this.operator) {
  19874. case ValueCondition.IsGreater:
  19875. return this._target[this._property] > this.value;
  19876. case ValueCondition.IsLesser:
  19877. return this._target[this._property] < this.value;
  19878. case ValueCondition.IsEqual:
  19879. case ValueCondition.IsDifferent:
  19880. var check;
  19881. if (this.value.equals) {
  19882. check = this.value.equals(this._target[this._property]);
  19883. } else {
  19884. check = this.value === this._target[this._property];
  19885. }
  19886. return this.operator === ValueCondition.IsEqual ? check : !check;
  19887. }
  19888. return false;
  19889. };
  19890. ValueCondition._IsEqual = 0;
  19891. ValueCondition._IsDifferent = 1;
  19892. ValueCondition._IsGreater = 2;
  19893. ValueCondition._IsLesser = 3;
  19894. return ValueCondition;
  19895. })(Condition);
  19896. BABYLON.ValueCondition = ValueCondition;
  19897. var PredicateCondition = (function (_super) {
  19898. __extends(PredicateCondition, _super);
  19899. function PredicateCondition(actionManager, predicate) {
  19900. _super.call(this, actionManager);
  19901. this.predicate = predicate;
  19902. }
  19903. PredicateCondition.prototype.isValid = function () {
  19904. return this.predicate();
  19905. };
  19906. return PredicateCondition;
  19907. })(Condition);
  19908. BABYLON.PredicateCondition = PredicateCondition;
  19909. var StateCondition = (function (_super) {
  19910. __extends(StateCondition, _super);
  19911. function StateCondition(actionManager, target, value) {
  19912. _super.call(this, actionManager);
  19913. this.value = value;
  19914. this._target = target;
  19915. }
  19916. StateCondition.prototype.isValid = function () {
  19917. return this._target.state === this.value;
  19918. };
  19919. return StateCondition;
  19920. })(Condition);
  19921. BABYLON.StateCondition = StateCondition;
  19922. })(BABYLON || (BABYLON = {}));
  19923. var BABYLON;
  19924. (function (BABYLON) {
  19925. var Action = (function () {
  19926. function Action(triggerOptions, condition) {
  19927. this.triggerOptions = triggerOptions;
  19928. if (triggerOptions.parameter) {
  19929. this.trigger = triggerOptions.trigger;
  19930. this._triggerParameter = triggerOptions.parameter;
  19931. } else {
  19932. this.trigger = triggerOptions;
  19933. }
  19934. this._nextActiveAction = this;
  19935. this._condition = condition;
  19936. }
  19937. Action.prototype._prepare = function () {
  19938. };
  19939. Action.prototype.getTriggerParameter = function () {
  19940. return this._triggerParameter;
  19941. };
  19942. Action.prototype._executeCurrent = function (evt) {
  19943. if (this._condition) {
  19944. var currentRenderId = this._actionManager.getScene().getRenderId();
  19945. if (this._condition._evaluationId === currentRenderId) {
  19946. if (!this._condition._currentResult) {
  19947. return;
  19948. }
  19949. } else {
  19950. this._condition._evaluationId = currentRenderId;
  19951. if (!this._condition.isValid()) {
  19952. this._condition._currentResult = false;
  19953. return;
  19954. }
  19955. this._condition._currentResult = true;
  19956. }
  19957. }
  19958. this._nextActiveAction.execute(evt);
  19959. if (this._nextActiveAction._child) {
  19960. if (!this._nextActiveAction._child._actionManager) {
  19961. this._nextActiveAction._child._actionManager = this._actionManager;
  19962. }
  19963. this._nextActiveAction = this._nextActiveAction._child;
  19964. } else {
  19965. this._nextActiveAction = this;
  19966. }
  19967. };
  19968. Action.prototype.execute = function (evt) {
  19969. };
  19970. Action.prototype.then = function (action) {
  19971. this._child = action;
  19972. action._actionManager = this._actionManager;
  19973. action._prepare();
  19974. return action;
  19975. };
  19976. Action.prototype._getProperty = function (propertyPath) {
  19977. return this._actionManager._getProperty(propertyPath);
  19978. };
  19979. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  19980. return this._actionManager._getEffectiveTarget(target, propertyPath);
  19981. };
  19982. return Action;
  19983. })();
  19984. BABYLON.Action = Action;
  19985. })(BABYLON || (BABYLON = {}));
  19986. var BABYLON;
  19987. (function (BABYLON) {
  19988. var ActionEvent = (function () {
  19989. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  19990. this.source = source;
  19991. this.pointerX = pointerX;
  19992. this.pointerY = pointerY;
  19993. this.meshUnderPointer = meshUnderPointer;
  19994. this.sourceEvent = sourceEvent;
  19995. }
  19996. ActionEvent.CreateNew = function (source) {
  19997. var scene = source.getScene();
  19998. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  19999. };
  20000. ActionEvent.CreateNewFromScene = function (scene, evt) {
  20001. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  20002. };
  20003. return ActionEvent;
  20004. })();
  20005. BABYLON.ActionEvent = ActionEvent;
  20006. var ActionManager = (function () {
  20007. function ActionManager(scene) {
  20008. this.actions = new Array();
  20009. this._scene = scene;
  20010. scene._actionManagers.push(this);
  20011. }
  20012. Object.defineProperty(ActionManager, "NothingTrigger", {
  20013. get: function () {
  20014. return ActionManager._NothingTrigger;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(ActionManager, "OnPickTrigger", {
  20020. get: function () {
  20021. return ActionManager._OnPickTrigger;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  20027. get: function () {
  20028. return ActionManager._OnLeftPickTrigger;
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  20034. get: function () {
  20035. return ActionManager._OnRightPickTrigger;
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  20041. get: function () {
  20042. return ActionManager._OnCenterPickTrigger;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  20048. get: function () {
  20049. return ActionManager._OnPointerOverTrigger;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  20055. get: function () {
  20056. return ActionManager._OnPointerOutTrigger;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  20062. get: function () {
  20063. return ActionManager._OnEveryFrameTrigger;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  20069. get: function () {
  20070. return ActionManager._OnIntersectionEnterTrigger;
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  20076. get: function () {
  20077. return ActionManager._OnIntersectionExitTrigger;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  20083. get: function () {
  20084. return ActionManager._OnKeyDownTrigger;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  20090. get: function () {
  20091. return ActionManager._OnKeyUpTrigger;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. ActionManager.prototype.dispose = function () {
  20097. var index = this._scene._actionManagers.indexOf(this);
  20098. if (index > -1) {
  20099. this._scene._actionManagers.splice(index, 1);
  20100. }
  20101. };
  20102. ActionManager.prototype.getScene = function () {
  20103. return this._scene;
  20104. };
  20105. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  20106. for (var index = 0; index < this.actions.length; index++) {
  20107. var action = this.actions[index];
  20108. if (triggers.indexOf(action.trigger) > -1) {
  20109. return true;
  20110. }
  20111. }
  20112. return false;
  20113. };
  20114. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  20115. get: function () {
  20116. for (var index = 0; index < this.actions.length; index++) {
  20117. var action = this.actions[index];
  20118. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  20119. return true;
  20120. }
  20121. }
  20122. return false;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  20128. get: function () {
  20129. for (var index = 0; index < this.actions.length; index++) {
  20130. var action = this.actions[index];
  20131. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  20132. return true;
  20133. }
  20134. }
  20135. return false;
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. ActionManager.prototype.registerAction = function (action) {
  20141. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  20142. if (this.getScene().actionManager !== this) {
  20143. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  20144. return null;
  20145. }
  20146. }
  20147. this.actions.push(action);
  20148. action._actionManager = this;
  20149. action._prepare();
  20150. return action;
  20151. };
  20152. ActionManager.prototype.processTrigger = function (trigger, evt) {
  20153. for (var index = 0; index < this.actions.length; index++) {
  20154. var action = this.actions[index];
  20155. if (action.trigger === trigger) {
  20156. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  20157. var parameter = action.getTriggerParameter();
  20158. if (parameter) {
  20159. if (evt.sourceEvent.key !== parameter) {
  20160. continue;
  20161. }
  20162. }
  20163. }
  20164. action._executeCurrent(evt);
  20165. }
  20166. }
  20167. };
  20168. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  20169. var properties = propertyPath.split(".");
  20170. for (var index = 0; index < properties.length - 1; index++) {
  20171. target = target[properties[index]];
  20172. }
  20173. return target;
  20174. };
  20175. ActionManager.prototype._getProperty = function (propertyPath) {
  20176. var properties = propertyPath.split(".");
  20177. return properties[properties.length - 1];
  20178. };
  20179. ActionManager._NothingTrigger = 0;
  20180. ActionManager._OnPickTrigger = 1;
  20181. ActionManager._OnLeftPickTrigger = 2;
  20182. ActionManager._OnRightPickTrigger = 3;
  20183. ActionManager._OnCenterPickTrigger = 4;
  20184. ActionManager._OnPointerOverTrigger = 5;
  20185. ActionManager._OnPointerOutTrigger = 6;
  20186. ActionManager._OnEveryFrameTrigger = 7;
  20187. ActionManager._OnIntersectionEnterTrigger = 8;
  20188. ActionManager._OnIntersectionExitTrigger = 9;
  20189. ActionManager._OnKeyDownTrigger = 10;
  20190. ActionManager._OnKeyUpTrigger = 11;
  20191. return ActionManager;
  20192. })();
  20193. BABYLON.ActionManager = ActionManager;
  20194. })(BABYLON || (BABYLON = {}));
  20195. var __extends = this.__extends || function (d, b) {
  20196. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20197. function __() { this.constructor = d; }
  20198. __.prototype = b.prototype;
  20199. d.prototype = new __();
  20200. };
  20201. var BABYLON;
  20202. (function (BABYLON) {
  20203. var InterpolateValueAction = (function (_super) {
  20204. __extends(InterpolateValueAction, _super);
  20205. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  20206. if (typeof duration === "undefined") { duration = 1000; }
  20207. _super.call(this, triggerOptions, condition);
  20208. this.propertyPath = propertyPath;
  20209. this.value = value;
  20210. this.duration = duration;
  20211. this.stopOtherAnimations = stopOtherAnimations;
  20212. this._target = target;
  20213. }
  20214. InterpolateValueAction.prototype._prepare = function () {
  20215. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20216. this._property = this._getProperty(this.propertyPath);
  20217. };
  20218. InterpolateValueAction.prototype.execute = function () {
  20219. var scene = this._actionManager.getScene();
  20220. var keys = [
  20221. {
  20222. frame: 0,
  20223. value: this._target[this._property]
  20224. }, {
  20225. frame: 100,
  20226. value: this.value
  20227. }
  20228. ];
  20229. var dataType;
  20230. if (typeof this.value === "number") {
  20231. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  20232. } else if (this.value instanceof BABYLON.Color3) {
  20233. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  20234. } else if (this.value instanceof BABYLON.Vector3) {
  20235. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  20236. } else if (this.value instanceof BABYLON.Matrix) {
  20237. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  20238. } else if (this.value instanceof BABYLON.Quaternion) {
  20239. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  20240. } else {
  20241. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  20242. return;
  20243. }
  20244. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  20245. animation.setKeys(keys);
  20246. if (this.stopOtherAnimations) {
  20247. scene.stopAnimation(this._target);
  20248. }
  20249. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  20250. };
  20251. return InterpolateValueAction;
  20252. })(BABYLON.Action);
  20253. BABYLON.InterpolateValueAction = InterpolateValueAction;
  20254. })(BABYLON || (BABYLON = {}));
  20255. var __extends = this.__extends || function (d, b) {
  20256. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20257. function __() { this.constructor = d; }
  20258. __.prototype = b.prototype;
  20259. d.prototype = new __();
  20260. };
  20261. var BABYLON;
  20262. (function (BABYLON) {
  20263. var SwitchBooleanAction = (function (_super) {
  20264. __extends(SwitchBooleanAction, _super);
  20265. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  20266. _super.call(this, triggerOptions, condition);
  20267. this.propertyPath = propertyPath;
  20268. this._target = target;
  20269. }
  20270. SwitchBooleanAction.prototype._prepare = function () {
  20271. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20272. this._property = this._getProperty(this.propertyPath);
  20273. };
  20274. SwitchBooleanAction.prototype.execute = function () {
  20275. this._target[this._property] = !this._target[this._property];
  20276. };
  20277. return SwitchBooleanAction;
  20278. })(BABYLON.Action);
  20279. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  20280. var SetStateAction = (function (_super) {
  20281. __extends(SetStateAction, _super);
  20282. function SetStateAction(triggerOptions, target, value, condition) {
  20283. _super.call(this, triggerOptions, condition);
  20284. this.value = value;
  20285. this._target = target;
  20286. }
  20287. SetStateAction.prototype.execute = function () {
  20288. this._target.state = this.value;
  20289. };
  20290. return SetStateAction;
  20291. })(BABYLON.Action);
  20292. BABYLON.SetStateAction = SetStateAction;
  20293. var SetValueAction = (function (_super) {
  20294. __extends(SetValueAction, _super);
  20295. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  20296. _super.call(this, triggerOptions, condition);
  20297. this.propertyPath = propertyPath;
  20298. this.value = value;
  20299. this._target = target;
  20300. }
  20301. SetValueAction.prototype._prepare = function () {
  20302. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20303. this._property = this._getProperty(this.propertyPath);
  20304. };
  20305. SetValueAction.prototype.execute = function () {
  20306. this._target[this._property] = this.value;
  20307. };
  20308. return SetValueAction;
  20309. })(BABYLON.Action);
  20310. BABYLON.SetValueAction = SetValueAction;
  20311. var IncrementValueAction = (function (_super) {
  20312. __extends(IncrementValueAction, _super);
  20313. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  20314. _super.call(this, triggerOptions, condition);
  20315. this.propertyPath = propertyPath;
  20316. this.value = value;
  20317. this._target = target;
  20318. }
  20319. IncrementValueAction.prototype._prepare = function () {
  20320. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20321. this._property = this._getProperty(this.propertyPath);
  20322. if (typeof this._target[this._property] !== "number") {
  20323. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  20324. }
  20325. };
  20326. IncrementValueAction.prototype.execute = function () {
  20327. this._target[this._property] += this.value;
  20328. };
  20329. return IncrementValueAction;
  20330. })(BABYLON.Action);
  20331. BABYLON.IncrementValueAction = IncrementValueAction;
  20332. var PlayAnimationAction = (function (_super) {
  20333. __extends(PlayAnimationAction, _super);
  20334. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  20335. _super.call(this, triggerOptions, condition);
  20336. this.from = from;
  20337. this.to = to;
  20338. this.loop = loop;
  20339. this._target = target;
  20340. }
  20341. PlayAnimationAction.prototype._prepare = function () {
  20342. };
  20343. PlayAnimationAction.prototype.execute = function () {
  20344. var scene = this._actionManager.getScene();
  20345. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  20346. };
  20347. return PlayAnimationAction;
  20348. })(BABYLON.Action);
  20349. BABYLON.PlayAnimationAction = PlayAnimationAction;
  20350. var StopAnimationAction = (function (_super) {
  20351. __extends(StopAnimationAction, _super);
  20352. function StopAnimationAction(triggerOptions, target, condition) {
  20353. _super.call(this, triggerOptions, condition);
  20354. this._target = target;
  20355. }
  20356. StopAnimationAction.prototype._prepare = function () {
  20357. };
  20358. StopAnimationAction.prototype.execute = function () {
  20359. var scene = this._actionManager.getScene();
  20360. scene.stopAnimation(this._target);
  20361. };
  20362. return StopAnimationAction;
  20363. })(BABYLON.Action);
  20364. BABYLON.StopAnimationAction = StopAnimationAction;
  20365. var DoNothingAction = (function (_super) {
  20366. __extends(DoNothingAction, _super);
  20367. function DoNothingAction(triggerOptions, condition) {
  20368. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  20369. _super.call(this, triggerOptions, condition);
  20370. }
  20371. DoNothingAction.prototype.execute = function () {
  20372. };
  20373. return DoNothingAction;
  20374. })(BABYLON.Action);
  20375. BABYLON.DoNothingAction = DoNothingAction;
  20376. var CombineAction = (function (_super) {
  20377. __extends(CombineAction, _super);
  20378. function CombineAction(triggerOptions, children, condition) {
  20379. _super.call(this, triggerOptions, condition);
  20380. this.children = children;
  20381. }
  20382. CombineAction.prototype._prepare = function () {
  20383. for (var index = 0; index < this.children.length; index++) {
  20384. this.children[index]._actionManager = this._actionManager;
  20385. this.children[index]._prepare();
  20386. }
  20387. };
  20388. CombineAction.prototype.execute = function (evt) {
  20389. for (var index = 0; index < this.children.length; index++) {
  20390. this.children[index].execute(evt);
  20391. }
  20392. };
  20393. return CombineAction;
  20394. })(BABYLON.Action);
  20395. BABYLON.CombineAction = CombineAction;
  20396. var ExecuteCodeAction = (function (_super) {
  20397. __extends(ExecuteCodeAction, _super);
  20398. function ExecuteCodeAction(triggerOptions, func, condition) {
  20399. _super.call(this, triggerOptions, condition);
  20400. this.func = func;
  20401. }
  20402. ExecuteCodeAction.prototype.execute = function (evt) {
  20403. this.func(evt);
  20404. };
  20405. return ExecuteCodeAction;
  20406. })(BABYLON.Action);
  20407. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  20408. var SetParentAction = (function (_super) {
  20409. __extends(SetParentAction, _super);
  20410. function SetParentAction(triggerOptions, target, parent, condition) {
  20411. _super.call(this, triggerOptions, condition);
  20412. this._target = target;
  20413. this._parent = parent;
  20414. }
  20415. SetParentAction.prototype._prepare = function () {
  20416. };
  20417. SetParentAction.prototype.execute = function () {
  20418. if (this._target.parent === this._parent) {
  20419. return;
  20420. }
  20421. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  20422. invertParentWorldMatrix.invert();
  20423. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  20424. this._target.parent = this._parent;
  20425. };
  20426. return SetParentAction;
  20427. })(BABYLON.Action);
  20428. BABYLON.SetParentAction = SetParentAction;
  20429. })(BABYLON || (BABYLON = {}));
  20430. var __extends = this.__extends || function (d, b) {
  20431. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20432. function __() { this.constructor = d; }
  20433. __.prototype = b.prototype;
  20434. d.prototype = new __();
  20435. };
  20436. var BABYLON;
  20437. (function (BABYLON) {
  20438. var Geometry = (function () {
  20439. function Geometry(id, scene, vertexData, updatable, mesh) {
  20440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20441. this._totalVertices = 0;
  20442. this._indices = [];
  20443. this.id = id;
  20444. this._engine = scene.getEngine();
  20445. this._meshes = [];
  20446. this._scene = scene;
  20447. if (vertexData) {
  20448. this.setAllVerticesData(vertexData, updatable);
  20449. } else {
  20450. this._totalVertices = 0;
  20451. this._indices = [];
  20452. }
  20453. if (mesh) {
  20454. this.applyToMesh(mesh);
  20455. }
  20456. }
  20457. Geometry.prototype.getScene = function () {
  20458. return this._scene;
  20459. };
  20460. Geometry.prototype.getEngine = function () {
  20461. return this._engine;
  20462. };
  20463. Geometry.prototype.isReady = function () {
  20464. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  20465. };
  20466. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  20467. vertexData.applyToGeometry(this, updatable);
  20468. };
  20469. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20470. this._vertexBuffers = this._vertexBuffers || {};
  20471. if (this._vertexBuffers[kind]) {
  20472. this._vertexBuffers[kind].dispose();
  20473. }
  20474. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  20475. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20476. stride = this._vertexBuffers[kind].getStrideSize();
  20477. this._totalVertices = data.length / stride;
  20478. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20479. var meshes = this._meshes;
  20480. var numOfMeshes = meshes.length;
  20481. for (var index = 0; index < numOfMeshes; index++) {
  20482. var mesh = meshes[index];
  20483. mesh._resetPointsArrayCache();
  20484. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20485. mesh._createGlobalSubMesh();
  20486. mesh.computeWorldMatrix(true);
  20487. }
  20488. }
  20489. };
  20490. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  20491. var vertexBuffer = this.getVertexBuffer(kind);
  20492. if (!vertexBuffer) {
  20493. return;
  20494. }
  20495. vertexBuffer.updateDirectly(data);
  20496. };
  20497. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  20498. var vertexBuffer = this.getVertexBuffer(kind);
  20499. if (!vertexBuffer) {
  20500. return;
  20501. }
  20502. vertexBuffer.update(data);
  20503. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20504. var extend;
  20505. if (updateExtends) {
  20506. var stride = vertexBuffer.getStrideSize();
  20507. this._totalVertices = data.length / stride;
  20508. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  20509. }
  20510. var meshes = this._meshes;
  20511. var numOfMeshes = meshes.length;
  20512. for (var index = 0; index < numOfMeshes; index++) {
  20513. var mesh = meshes[index];
  20514. mesh._resetPointsArrayCache();
  20515. if (updateExtends) {
  20516. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20517. }
  20518. }
  20519. }
  20520. };
  20521. Geometry.prototype.getTotalVertices = function () {
  20522. if (!this.isReady()) {
  20523. return 0;
  20524. }
  20525. return this._totalVertices;
  20526. };
  20527. Geometry.prototype.getVerticesData = function (kind) {
  20528. var vertexBuffer = this.getVertexBuffer(kind);
  20529. if (!vertexBuffer) {
  20530. return null;
  20531. }
  20532. return vertexBuffer.getData();
  20533. };
  20534. Geometry.prototype.getVertexBuffer = function (kind) {
  20535. if (!this.isReady()) {
  20536. return null;
  20537. }
  20538. return this._vertexBuffers[kind];
  20539. };
  20540. Geometry.prototype.getVertexBuffers = function () {
  20541. if (!this.isReady()) {
  20542. return null;
  20543. }
  20544. return this._vertexBuffers;
  20545. };
  20546. Geometry.prototype.isVerticesDataPresent = function (kind) {
  20547. if (!this._vertexBuffers) {
  20548. if (this._delayInfo) {
  20549. return this._delayInfo.indexOf(kind) !== -1;
  20550. }
  20551. return false;
  20552. }
  20553. return this._vertexBuffers[kind] !== undefined;
  20554. };
  20555. Geometry.prototype.getVerticesDataKinds = function () {
  20556. var result = [];
  20557. if (!this._vertexBuffers && this._delayInfo) {
  20558. for (var kind in this._delayInfo) {
  20559. result.push(kind);
  20560. }
  20561. } else {
  20562. for (kind in this._vertexBuffers) {
  20563. result.push(kind);
  20564. }
  20565. }
  20566. return result;
  20567. };
  20568. Geometry.prototype.setIndices = function (indices) {
  20569. if (this._indexBuffer) {
  20570. this._engine._releaseBuffer(this._indexBuffer);
  20571. }
  20572. this._indices = indices;
  20573. if (this._meshes.length !== 0 && this._indices) {
  20574. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20575. }
  20576. var meshes = this._meshes;
  20577. var numOfMeshes = meshes.length;
  20578. for (var index = 0; index < numOfMeshes; index++) {
  20579. meshes[index]._createGlobalSubMesh();
  20580. }
  20581. };
  20582. Geometry.prototype.getTotalIndices = function () {
  20583. if (!this.isReady()) {
  20584. return 0;
  20585. }
  20586. return this._indices.length;
  20587. };
  20588. Geometry.prototype.getIndices = function () {
  20589. if (!this.isReady()) {
  20590. return null;
  20591. }
  20592. return this._indices;
  20593. };
  20594. Geometry.prototype.getIndexBuffer = function () {
  20595. if (!this.isReady()) {
  20596. return null;
  20597. }
  20598. return this._indexBuffer;
  20599. };
  20600. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  20601. var meshes = this._meshes;
  20602. var index = meshes.indexOf(mesh);
  20603. if (index === -1) {
  20604. return;
  20605. }
  20606. for (var kind in this._vertexBuffers) {
  20607. this._vertexBuffers[kind].dispose();
  20608. }
  20609. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  20610. this._indexBuffer = null;
  20611. }
  20612. meshes.splice(index, 1);
  20613. mesh._geometry = null;
  20614. if (meshes.length == 0 && shouldDispose) {
  20615. this.dispose();
  20616. }
  20617. };
  20618. Geometry.prototype.applyToMesh = function (mesh) {
  20619. if (mesh._geometry === this) {
  20620. return;
  20621. }
  20622. var previousGeometry = mesh._geometry;
  20623. if (previousGeometry) {
  20624. previousGeometry.releaseForMesh(mesh);
  20625. }
  20626. var meshes = this._meshes;
  20627. mesh._geometry = this;
  20628. this._scene.pushGeometry(this);
  20629. meshes.push(mesh);
  20630. if (this.isReady()) {
  20631. this._applyToMesh(mesh);
  20632. } else {
  20633. mesh._boundingInfo = this._boundingInfo;
  20634. }
  20635. };
  20636. Geometry.prototype._applyToMesh = function (mesh) {
  20637. var numOfMeshes = this._meshes.length;
  20638. for (var kind in this._vertexBuffers) {
  20639. if (numOfMeshes === 1) {
  20640. this._vertexBuffers[kind].create();
  20641. }
  20642. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  20643. if (kind === BABYLON.VertexBuffer.PositionKind) {
  20644. mesh._resetPointsArrayCache();
  20645. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  20646. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20647. mesh._createGlobalSubMesh();
  20648. }
  20649. }
  20650. if (numOfMeshes === 1 && this._indices) {
  20651. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  20652. }
  20653. if (this._indexBuffer) {
  20654. this._indexBuffer.references = numOfMeshes;
  20655. }
  20656. };
  20657. Geometry.prototype.load = function (scene, onLoaded) {
  20658. var _this = this;
  20659. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20660. return;
  20661. }
  20662. if (this.isReady()) {
  20663. if (onLoaded) {
  20664. onLoaded();
  20665. }
  20666. return;
  20667. }
  20668. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20669. scene._addPendingData(this);
  20670. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20671. _this._delayLoadingFunction(JSON.parse(data), _this);
  20672. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20673. _this._delayInfo = [];
  20674. scene._removePendingData(_this);
  20675. var meshes = _this._meshes;
  20676. var numOfMeshes = meshes.length;
  20677. for (var index = 0; index < numOfMeshes; index++) {
  20678. _this._applyToMesh(meshes[index]);
  20679. }
  20680. if (onLoaded) {
  20681. onLoaded();
  20682. }
  20683. }, function () {
  20684. }, scene.database);
  20685. };
  20686. Geometry.prototype.dispose = function () {
  20687. var meshes = this._meshes;
  20688. var numOfMeshes = meshes.length;
  20689. for (var index = 0; index < numOfMeshes; index++) {
  20690. this.releaseForMesh(meshes[index]);
  20691. }
  20692. this._meshes = [];
  20693. for (var kind in this._vertexBuffers) {
  20694. this._vertexBuffers[kind].dispose();
  20695. }
  20696. this._vertexBuffers = [];
  20697. this._totalVertices = 0;
  20698. if (this._indexBuffer) {
  20699. this._engine._releaseBuffer(this._indexBuffer);
  20700. }
  20701. this._indexBuffer = null;
  20702. this._indices = [];
  20703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20704. this.delayLoadingFile = null;
  20705. this._delayLoadingFunction = null;
  20706. this._delayInfo = [];
  20707. this._boundingInfo = null;
  20708. var geometries = this._scene.getGeometries();
  20709. index = geometries.indexOf(this);
  20710. if (index > -1) {
  20711. geometries.splice(index, 1);
  20712. }
  20713. };
  20714. Geometry.prototype.copy = function (id) {
  20715. var vertexData = new BABYLON.VertexData();
  20716. vertexData.indices = [];
  20717. var indices = this.getIndices();
  20718. for (var index = 0; index < indices.length; index++) {
  20719. vertexData.indices.push(indices[index]);
  20720. }
  20721. var updatable = false;
  20722. var stopChecking = false;
  20723. for (var kind in this._vertexBuffers) {
  20724. vertexData.set(this.getVerticesData(kind), kind);
  20725. if (!stopChecking) {
  20726. updatable = this.getVertexBuffer(kind).isUpdatable();
  20727. stopChecking = !updatable;
  20728. }
  20729. }
  20730. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  20731. geometry.delayLoadState = this.delayLoadState;
  20732. geometry.delayLoadingFile = this.delayLoadingFile;
  20733. geometry._delayLoadingFunction = this._delayLoadingFunction;
  20734. for (kind in this._delayInfo) {
  20735. geometry._delayInfo = geometry._delayInfo || [];
  20736. geometry._delayInfo.push(kind);
  20737. }
  20738. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  20739. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20740. return geometry;
  20741. };
  20742. Geometry.ExtractFromMesh = function (mesh, id) {
  20743. var geometry = mesh._geometry;
  20744. if (!geometry) {
  20745. return null;
  20746. }
  20747. return geometry.copy(id);
  20748. };
  20749. Geometry.RandomId = function () {
  20750. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  20751. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  20752. return v.toString(16);
  20753. });
  20754. };
  20755. return Geometry;
  20756. })();
  20757. BABYLON.Geometry = Geometry;
  20758. (function (Geometry) {
  20759. (function (Primitives) {
  20760. var _Primitive = (function (_super) {
  20761. __extends(_Primitive, _super);
  20762. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  20763. this._beingRegenerated = true;
  20764. this._canBeRegenerated = canBeRegenerated;
  20765. _super.call(this, id, scene, vertexData, false, mesh);
  20766. this._beingRegenerated = false;
  20767. }
  20768. _Primitive.prototype.canBeRegenerated = function () {
  20769. return this._canBeRegenerated;
  20770. };
  20771. _Primitive.prototype.regenerate = function () {
  20772. if (!this._canBeRegenerated) {
  20773. return;
  20774. }
  20775. this._beingRegenerated = true;
  20776. this.setAllVerticesData(this._regenerateVertexData(), false);
  20777. this._beingRegenerated = false;
  20778. };
  20779. _Primitive.prototype.asNewGeometry = function (id) {
  20780. return _super.prototype.copy.call(this, id);
  20781. };
  20782. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  20783. if (!this._beingRegenerated) {
  20784. return;
  20785. }
  20786. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  20787. };
  20788. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  20789. if (!this._beingRegenerated) {
  20790. return;
  20791. }
  20792. _super.prototype.setVerticesData.call(this, kind, data, false);
  20793. };
  20794. _Primitive.prototype._regenerateVertexData = function () {
  20795. throw new Error("Abstract method");
  20796. };
  20797. _Primitive.prototype.copy = function (id) {
  20798. throw new Error("Must be overriden in sub-classes.");
  20799. };
  20800. return _Primitive;
  20801. })(Geometry);
  20802. Primitives._Primitive = _Primitive;
  20803. var Box = (function (_super) {
  20804. __extends(Box, _super);
  20805. function Box(id, scene, size, canBeRegenerated, mesh) {
  20806. this.size = size;
  20807. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20808. }
  20809. Box.prototype._regenerateVertexData = function () {
  20810. return BABYLON.VertexData.CreateBox(this.size);
  20811. };
  20812. Box.prototype.copy = function (id) {
  20813. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20814. };
  20815. return Box;
  20816. })(_Primitive);
  20817. Primitives.Box = Box;
  20818. var Sphere = (function (_super) {
  20819. __extends(Sphere, _super);
  20820. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  20821. this.segments = segments;
  20822. this.diameter = diameter;
  20823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20824. }
  20825. Sphere.prototype._regenerateVertexData = function () {
  20826. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  20827. };
  20828. Sphere.prototype.copy = function (id) {
  20829. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  20830. };
  20831. return Sphere;
  20832. })(_Primitive);
  20833. Primitives.Sphere = Sphere;
  20834. var Cylinder = (function (_super) {
  20835. __extends(Cylinder, _super);
  20836. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  20837. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20838. this.height = height;
  20839. this.diameterTop = diameterTop;
  20840. this.diameterBottom = diameterBottom;
  20841. this.tessellation = tessellation;
  20842. this.subdivisions = subdivisions;
  20843. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20844. }
  20845. Cylinder.prototype._regenerateVertexData = function () {
  20846. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  20847. };
  20848. Cylinder.prototype.copy = function (id) {
  20849. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  20850. };
  20851. return Cylinder;
  20852. })(_Primitive);
  20853. Primitives.Cylinder = Cylinder;
  20854. var Torus = (function (_super) {
  20855. __extends(Torus, _super);
  20856. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  20857. this.diameter = diameter;
  20858. this.thickness = thickness;
  20859. this.tessellation = tessellation;
  20860. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20861. }
  20862. Torus.prototype._regenerateVertexData = function () {
  20863. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  20864. };
  20865. Torus.prototype.copy = function (id) {
  20866. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  20867. };
  20868. return Torus;
  20869. })(_Primitive);
  20870. Primitives.Torus = Torus;
  20871. var Ground = (function (_super) {
  20872. __extends(Ground, _super);
  20873. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  20874. this.width = width;
  20875. this.height = height;
  20876. this.subdivisions = subdivisions;
  20877. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20878. }
  20879. Ground.prototype._regenerateVertexData = function () {
  20880. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  20881. };
  20882. Ground.prototype.copy = function (id) {
  20883. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  20884. };
  20885. return Ground;
  20886. })(_Primitive);
  20887. Primitives.Ground = Ground;
  20888. var TiledGround = (function (_super) {
  20889. __extends(TiledGround, _super);
  20890. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  20891. this.xmin = xmin;
  20892. this.zmin = zmin;
  20893. this.xmax = xmax;
  20894. this.zmax = zmax;
  20895. this.subdivisions = subdivisions;
  20896. this.precision = precision;
  20897. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20898. }
  20899. TiledGround.prototype._regenerateVertexData = function () {
  20900. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  20901. };
  20902. TiledGround.prototype.copy = function (id) {
  20903. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  20904. };
  20905. return TiledGround;
  20906. })(_Primitive);
  20907. Primitives.TiledGround = TiledGround;
  20908. var Plane = (function (_super) {
  20909. __extends(Plane, _super);
  20910. function Plane(id, scene, size, canBeRegenerated, mesh) {
  20911. this.size = size;
  20912. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20913. }
  20914. Plane.prototype._regenerateVertexData = function () {
  20915. return BABYLON.VertexData.CreatePlane(this.size);
  20916. };
  20917. Plane.prototype.copy = function (id) {
  20918. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  20919. };
  20920. return Plane;
  20921. })(_Primitive);
  20922. Primitives.Plane = Plane;
  20923. var TorusKnot = (function (_super) {
  20924. __extends(TorusKnot, _super);
  20925. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  20926. this.radius = radius;
  20927. this.tube = tube;
  20928. this.radialSegments = radialSegments;
  20929. this.tubularSegments = tubularSegments;
  20930. this.p = p;
  20931. this.q = q;
  20932. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  20933. }
  20934. TorusKnot.prototype._regenerateVertexData = function () {
  20935. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  20936. };
  20937. TorusKnot.prototype.copy = function (id) {
  20938. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  20939. };
  20940. return TorusKnot;
  20941. })(_Primitive);
  20942. Primitives.TorusKnot = TorusKnot;
  20943. })(Geometry.Primitives || (Geometry.Primitives = {}));
  20944. var Primitives = Geometry.Primitives;
  20945. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  20946. var Geometry = BABYLON.Geometry;
  20947. })(BABYLON || (BABYLON = {}));
  20948. var __extends = this.__extends || function (d, b) {
  20949. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20950. function __() { this.constructor = d; }
  20951. __.prototype = b.prototype;
  20952. d.prototype = new __();
  20953. };
  20954. var BABYLON;
  20955. (function (BABYLON) {
  20956. var Gamepads = (function () {
  20957. function Gamepads(ongamedpadconnected) {
  20958. var _this = this;
  20959. this.babylonGamepads = [];
  20960. this.oneGamepadConnected = false;
  20961. this.isMonitoring = false;
  20962. this.gamepadEventSupported = 'GamepadEvent' in window;
  20963. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  20964. 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=";
  20965. this._callbackGamepadConnected = ongamedpadconnected;
  20966. if (this.gamepadSupportAvailable) {
  20967. if (this.gamepadEventSupported) {
  20968. window.addEventListener('gamepadconnected', function (evt) {
  20969. _this._onGamepadConnected(evt);
  20970. }, false);
  20971. window.addEventListener('gamepaddisconnected', function (evt) {
  20972. _this._onGamepadDisconnected(evt);
  20973. }, false);
  20974. } else {
  20975. this._startMonitoringGamepads();
  20976. }
  20977. if (!this.oneGamepadConnected) {
  20978. this._insertGamepadDOMInstructions();
  20979. }
  20980. } else {
  20981. this._insertGamepadDOMNotSupported();
  20982. }
  20983. }
  20984. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  20985. Gamepads.gamepadDOMInfo = document.createElement("div");
  20986. var buttonAImage = document.createElement("img");
  20987. buttonAImage.src = this.buttonADataURL;
  20988. var spanMessage = document.createElement("span");
  20989. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  20990. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  20991. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  20992. Gamepads.gamepadDOMInfo.style.position = "absolute";
  20993. Gamepads.gamepadDOMInfo.style.width = "100%";
  20994. Gamepads.gamepadDOMInfo.style.height = "48px";
  20995. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  20996. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  20997. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  20998. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  20999. buttonAImage.style.position = "relative";
  21000. buttonAImage.style.bottom = "8px";
  21001. spanMessage.style.position = "relative";
  21002. spanMessage.style.fontSize = "32px";
  21003. spanMessage.style.bottom = "32px";
  21004. spanMessage.style.color = "green";
  21005. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21006. };
  21007. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  21008. Gamepads.gamepadDOMInfo = document.createElement("div");
  21009. var spanMessage = document.createElement("span");
  21010. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  21011. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21012. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21013. Gamepads.gamepadDOMInfo.style.width = "100%";
  21014. Gamepads.gamepadDOMInfo.style.height = "40px";
  21015. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21016. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21017. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21018. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21019. spanMessage.style.position = "relative";
  21020. spanMessage.style.fontSize = "32px";
  21021. spanMessage.style.color = "red";
  21022. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21023. };
  21024. Gamepads.prototype.dispose = function () {
  21025. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21026. };
  21027. Gamepads.prototype._onGamepadConnected = function (evt) {
  21028. var newGamepad = this._addNewGamepad(evt.gamepad);
  21029. if (this._callbackGamepadConnected)
  21030. this._callbackGamepadConnected(newGamepad);
  21031. this._startMonitoringGamepads();
  21032. };
  21033. Gamepads.prototype._addNewGamepad = function (gamepad) {
  21034. if (!this.oneGamepadConnected) {
  21035. this.oneGamepadConnected = true;
  21036. if (Gamepads.gamepadDOMInfo) {
  21037. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21038. Gamepads.gamepadDOMInfo = null;
  21039. }
  21040. }
  21041. var newGamepad;
  21042. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  21043. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  21044. } else {
  21045. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  21046. }
  21047. this.babylonGamepads.push(newGamepad);
  21048. return newGamepad;
  21049. };
  21050. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  21051. for (var i in this.babylonGamepads) {
  21052. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  21053. this.babylonGamepads.splice(i, 1);
  21054. break;
  21055. }
  21056. }
  21057. if (this.babylonGamepads.length == 0) {
  21058. this._stopMonitoringGamepads();
  21059. }
  21060. };
  21061. Gamepads.prototype._startMonitoringGamepads = function () {
  21062. if (!this.isMonitoring) {
  21063. this.isMonitoring = true;
  21064. this._checkGamepadsStatus();
  21065. }
  21066. };
  21067. Gamepads.prototype._stopMonitoringGamepads = function () {
  21068. this.isMonitoring = false;
  21069. };
  21070. Gamepads.prototype._checkGamepadsStatus = function () {
  21071. var _this = this;
  21072. this._updateGamepadObjects();
  21073. for (var i in this.babylonGamepads) {
  21074. this.babylonGamepads[i].update();
  21075. }
  21076. if (this.isMonitoring) {
  21077. if (window.requestAnimationFrame) {
  21078. window.requestAnimationFrame(function () {
  21079. _this._checkGamepadsStatus();
  21080. });
  21081. } else if (window.mozRequestAnimationFrame) {
  21082. window.mozRequestAnimationFrame(function () {
  21083. _this._checkGamepadsStatus();
  21084. });
  21085. } else if (window.webkitRequestAnimationFrame) {
  21086. window.webkitRequestAnimationFrame(function () {
  21087. _this._checkGamepadsStatus();
  21088. });
  21089. }
  21090. }
  21091. };
  21092. Gamepads.prototype._updateGamepadObjects = function () {
  21093. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  21094. for (var i = 0; i < gamepads.length; i++) {
  21095. if (gamepads[i]) {
  21096. if (!(gamepads[i].index in this.babylonGamepads)) {
  21097. var newGamepad = this._addNewGamepad(gamepads[i]);
  21098. if (this._callbackGamepadConnected) {
  21099. this._callbackGamepadConnected(newGamepad);
  21100. }
  21101. } else {
  21102. this.babylonGamepads[i].browserGamepad = gamepads[i];
  21103. }
  21104. }
  21105. }
  21106. };
  21107. return Gamepads;
  21108. })();
  21109. BABYLON.Gamepads = Gamepads;
  21110. var StickValues = (function () {
  21111. function StickValues(x, y) {
  21112. this.x = x;
  21113. this.y = y;
  21114. }
  21115. return StickValues;
  21116. })();
  21117. BABYLON.StickValues = StickValues;
  21118. var Gamepad = (function () {
  21119. function Gamepad(id, index, browserGamepad) {
  21120. this.id = id;
  21121. this.index = index;
  21122. this.browserGamepad = browserGamepad;
  21123. if (this.browserGamepad.axes.length >= 2) {
  21124. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21125. }
  21126. if (this.browserGamepad.axes.length >= 4) {
  21127. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21128. }
  21129. }
  21130. Gamepad.prototype.onleftstickchanged = function (callback) {
  21131. this._onleftstickchanged = callback;
  21132. };
  21133. Gamepad.prototype.onrightstickchanged = function (callback) {
  21134. this._onrightstickchanged = callback;
  21135. };
  21136. Object.defineProperty(Gamepad.prototype, "leftStick", {
  21137. get: function () {
  21138. return this._leftStick;
  21139. },
  21140. set: function (newValues) {
  21141. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  21142. this._onleftstickchanged(newValues);
  21143. }
  21144. this._leftStick = newValues;
  21145. },
  21146. enumerable: true,
  21147. configurable: true
  21148. });
  21149. Object.defineProperty(Gamepad.prototype, "rightStick", {
  21150. get: function () {
  21151. return this._rightStick;
  21152. },
  21153. set: function (newValues) {
  21154. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  21155. this._onrightstickchanged(newValues);
  21156. }
  21157. this._rightStick = newValues;
  21158. },
  21159. enumerable: true,
  21160. configurable: true
  21161. });
  21162. Gamepad.prototype.update = function () {
  21163. if (this._leftStick) {
  21164. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21165. }
  21166. if (this._rightStick) {
  21167. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21168. }
  21169. };
  21170. return Gamepad;
  21171. })();
  21172. BABYLON.Gamepad = Gamepad;
  21173. var GenericPad = (function (_super) {
  21174. __extends(GenericPad, _super);
  21175. function GenericPad(id, index, gamepad) {
  21176. _super.call(this, id, index, gamepad);
  21177. this.id = id;
  21178. this.index = index;
  21179. this.gamepad = gamepad;
  21180. this._buttons = new Array(gamepad.buttons.length);
  21181. }
  21182. GenericPad.prototype.onbuttondown = function (callback) {
  21183. this._onbuttondown = callback;
  21184. };
  21185. GenericPad.prototype.onbuttonup = function (callback) {
  21186. this._onbuttonup = callback;
  21187. };
  21188. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  21189. if (newValue !== currentValue) {
  21190. if (this._onbuttondown && newValue === 1) {
  21191. this._onbuttondown(buttonIndex);
  21192. }
  21193. if (this._onbuttonup && newValue === 0) {
  21194. this._onbuttonup(buttonIndex);
  21195. }
  21196. }
  21197. return newValue;
  21198. };
  21199. GenericPad.prototype.update = function () {
  21200. _super.prototype.update.call(this);
  21201. for (var index = 0; index < this._buttons.length; index++) {
  21202. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  21203. }
  21204. };
  21205. return GenericPad;
  21206. })(Gamepad);
  21207. BABYLON.GenericPad = GenericPad;
  21208. (function (Xbox360Button) {
  21209. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  21210. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  21211. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  21212. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  21213. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  21214. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  21215. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  21216. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  21217. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  21218. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  21219. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  21220. var Xbox360Button = BABYLON.Xbox360Button;
  21221. (function (Xbox360Dpad) {
  21222. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  21223. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  21224. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  21225. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  21226. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  21227. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  21228. var Xbox360Pad = (function (_super) {
  21229. __extends(Xbox360Pad, _super);
  21230. function Xbox360Pad() {
  21231. _super.apply(this, arguments);
  21232. this._leftTrigger = 0;
  21233. this._rightTrigger = 0;
  21234. this._buttonA = 0;
  21235. this._buttonB = 0;
  21236. this._buttonX = 0;
  21237. this._buttonY = 0;
  21238. this._buttonBack = 0;
  21239. this._buttonStart = 0;
  21240. this._buttonLB = 0;
  21241. this._buttonRB = 0;
  21242. this._buttonLeftStick = 0;
  21243. this._buttonRightStick = 0;
  21244. this._dPadUp = 0;
  21245. this._dPadDown = 0;
  21246. this._dPadLeft = 0;
  21247. this._dPadRight = 0;
  21248. }
  21249. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  21250. this._onlefttriggerchanged = callback;
  21251. };
  21252. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  21253. this._onrighttriggerchanged = callback;
  21254. };
  21255. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  21256. get: function () {
  21257. return this._leftTrigger;
  21258. },
  21259. set: function (newValue) {
  21260. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  21261. this._onlefttriggerchanged(newValue);
  21262. }
  21263. this._leftTrigger = newValue;
  21264. },
  21265. enumerable: true,
  21266. configurable: true
  21267. });
  21268. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  21269. get: function () {
  21270. return this._rightTrigger;
  21271. },
  21272. set: function (newValue) {
  21273. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  21274. this._onrighttriggerchanged(newValue);
  21275. }
  21276. this._rightTrigger = newValue;
  21277. },
  21278. enumerable: true,
  21279. configurable: true
  21280. });
  21281. Xbox360Pad.prototype.onbuttondown = function (callback) {
  21282. this._onbuttondown = callback;
  21283. };
  21284. Xbox360Pad.prototype.onbuttonup = function (callback) {
  21285. this._onbuttonup = callback;
  21286. };
  21287. Xbox360Pad.prototype.ondpaddown = function (callback) {
  21288. this._ondpaddown = callback;
  21289. };
  21290. Xbox360Pad.prototype.ondpadup = function (callback) {
  21291. this._ondpadup = callback;
  21292. };
  21293. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  21294. if (newValue !== currentValue) {
  21295. if (this._onbuttondown && newValue === 1) {
  21296. this._onbuttondown(buttonType);
  21297. }
  21298. if (this._onbuttonup && newValue === 0) {
  21299. this._onbuttonup(buttonType);
  21300. }
  21301. }
  21302. return newValue;
  21303. };
  21304. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  21305. if (newValue !== currentValue) {
  21306. if (this._ondpaddown && newValue === 1) {
  21307. this._ondpaddown(buttonType);
  21308. }
  21309. if (this._ondpadup && newValue === 0) {
  21310. this._ondpadup(buttonType);
  21311. }
  21312. }
  21313. return newValue;
  21314. };
  21315. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  21316. get: function () {
  21317. return this._buttonA;
  21318. },
  21319. set: function (value) {
  21320. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  21321. },
  21322. enumerable: true,
  21323. configurable: true
  21324. });
  21325. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  21326. get: function () {
  21327. return this._buttonB;
  21328. },
  21329. set: function (value) {
  21330. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  21336. get: function () {
  21337. return this._buttonX;
  21338. },
  21339. set: function (value) {
  21340. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  21341. },
  21342. enumerable: true,
  21343. configurable: true
  21344. });
  21345. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  21346. get: function () {
  21347. return this._buttonY;
  21348. },
  21349. set: function (value) {
  21350. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  21356. get: function () {
  21357. return this._buttonStart;
  21358. },
  21359. set: function (value) {
  21360. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  21361. },
  21362. enumerable: true,
  21363. configurable: true
  21364. });
  21365. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  21366. get: function () {
  21367. return this._buttonBack;
  21368. },
  21369. set: function (value) {
  21370. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  21371. },
  21372. enumerable: true,
  21373. configurable: true
  21374. });
  21375. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  21376. get: function () {
  21377. return this._buttonLB;
  21378. },
  21379. set: function (value) {
  21380. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  21381. },
  21382. enumerable: true,
  21383. configurable: true
  21384. });
  21385. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  21386. get: function () {
  21387. return this._buttonRB;
  21388. },
  21389. set: function (value) {
  21390. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  21391. },
  21392. enumerable: true,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  21396. get: function () {
  21397. return this._buttonLeftStick;
  21398. },
  21399. set: function (value) {
  21400. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  21401. },
  21402. enumerable: true,
  21403. configurable: true
  21404. });
  21405. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  21406. get: function () {
  21407. return this._buttonRightStick;
  21408. },
  21409. set: function (value) {
  21410. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  21416. get: function () {
  21417. return this._dPadUp;
  21418. },
  21419. set: function (value) {
  21420. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  21426. get: function () {
  21427. return this._dPadDown;
  21428. },
  21429. set: function (value) {
  21430. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  21431. },
  21432. enumerable: true,
  21433. configurable: true
  21434. });
  21435. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  21436. get: function () {
  21437. return this._dPadLeft;
  21438. },
  21439. set: function (value) {
  21440. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  21441. },
  21442. enumerable: true,
  21443. configurable: true
  21444. });
  21445. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  21446. get: function () {
  21447. return this._dPadRight;
  21448. },
  21449. set: function (value) {
  21450. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  21451. },
  21452. enumerable: true,
  21453. configurable: true
  21454. });
  21455. Xbox360Pad.prototype.update = function () {
  21456. _super.prototype.update.call(this);
  21457. this.buttonA = this.browserGamepad.buttons[0].value;
  21458. this.buttonB = this.browserGamepad.buttons[1].value;
  21459. this.buttonX = this.browserGamepad.buttons[2].value;
  21460. this.buttonY = this.browserGamepad.buttons[3].value;
  21461. this.buttonLB = this.browserGamepad.buttons[4].value;
  21462. this.buttonRB = this.browserGamepad.buttons[5].value;
  21463. this.leftTrigger = this.browserGamepad.buttons[6].value;
  21464. this.rightTrigger = this.browserGamepad.buttons[7].value;
  21465. this.buttonBack = this.browserGamepad.buttons[8].value;
  21466. this.buttonStart = this.browserGamepad.buttons[9].value;
  21467. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  21468. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  21469. this.dPadUp = this.browserGamepad.buttons[12].value;
  21470. this.dPadDown = this.browserGamepad.buttons[13].value;
  21471. this.dPadLeft = this.browserGamepad.buttons[14].value;
  21472. this.dPadRight = this.browserGamepad.buttons[15].value;
  21473. };
  21474. return Xbox360Pad;
  21475. })(Gamepad);
  21476. BABYLON.Xbox360Pad = Xbox360Pad;
  21477. })(BABYLON || (BABYLON = {}));
  21478. var __extends = this.__extends || function (d, b) {
  21479. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21480. function __() { this.constructor = d; }
  21481. __.prototype = b.prototype;
  21482. d.prototype = new __();
  21483. };
  21484. var BABYLON;
  21485. (function (BABYLON) {
  21486. var GamepadCamera = (function (_super) {
  21487. __extends(GamepadCamera, _super);
  21488. function GamepadCamera(name, position, scene) {
  21489. var _this = this;
  21490. _super.call(this, name, position, scene);
  21491. this.angularSensibility = 200;
  21492. this.moveSensibility = 75;
  21493. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21494. _this._onNewGameConnected(gamepad);
  21495. });
  21496. }
  21497. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21498. if (gamepad.index === 0) {
  21499. this._gamepad = gamepad;
  21500. }
  21501. };
  21502. GamepadCamera.prototype._checkInputs = function () {
  21503. if (!this._gamepad) {
  21504. return;
  21505. }
  21506. var LSValues = this._gamepad.leftStick;
  21507. var normalizedLX = LSValues.x / this.moveSensibility;
  21508. var normalizedLY = LSValues.y / this.moveSensibility;
  21509. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21510. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21511. var RSValues = this._gamepad.rightStick;
  21512. var normalizedRX = RSValues.x / this.angularSensibility;
  21513. var normalizedRY = RSValues.y / this.angularSensibility;
  21514. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  21515. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  21516. ;
  21517. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21518. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21519. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21520. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  21521. };
  21522. GamepadCamera.prototype.dispose = function () {
  21523. this._gamepads.dispose();
  21524. _super.prototype.dispose.call(this);
  21525. };
  21526. return GamepadCamera;
  21527. })(BABYLON.FreeCamera);
  21528. BABYLON.GamepadCamera = GamepadCamera;
  21529. })(BABYLON || (BABYLON = {}));
  21530. var __extends = this.__extends || function (d, b) {
  21531. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21532. function __() { this.constructor = d; }
  21533. __.prototype = b.prototype;
  21534. d.prototype = new __();
  21535. };
  21536. var BABYLON;
  21537. (function (BABYLON) {
  21538. var LinesMesh = (function (_super) {
  21539. __extends(LinesMesh, _super);
  21540. function LinesMesh(name, scene, updatable) {
  21541. if (typeof updatable === "undefined") { updatable = false; }
  21542. _super.call(this, name, scene);
  21543. this.color = new BABYLON.Color3(1, 1, 1);
  21544. this.alpha = 1;
  21545. this._indices = new Array();
  21546. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21547. attributes: ["position"],
  21548. uniforms: ["worldViewProjection", "color"],
  21549. needAlphaBlending: true
  21550. });
  21551. }
  21552. Object.defineProperty(LinesMesh.prototype, "material", {
  21553. get: function () {
  21554. return this._colorShader;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  21560. get: function () {
  21561. return false;
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  21567. get: function () {
  21568. return false;
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  21574. var engine = this.getScene().getEngine();
  21575. var indexToBind = this._geometry.getIndexBuffer();
  21576. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  21577. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  21578. };
  21579. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21580. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21581. return;
  21582. }
  21583. var engine = this.getScene().getEngine();
  21584. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  21585. };
  21586. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  21587. return null;
  21588. };
  21589. LinesMesh.prototype.dispose = function (doNotRecurse) {
  21590. this._colorShader.dispose();
  21591. _super.prototype.dispose.call(this, doNotRecurse);
  21592. };
  21593. return LinesMesh;
  21594. })(BABYLON.Mesh);
  21595. BABYLON.LinesMesh = LinesMesh;
  21596. })(BABYLON || (BABYLON = {}));
  21597. var BABYLON;
  21598. (function (BABYLON) {
  21599. var OutlineRenderer = (function () {
  21600. function OutlineRenderer(scene) {
  21601. this._scene = scene;
  21602. }
  21603. OutlineRenderer.prototype.render = function (subMesh, batch) {
  21604. var scene = this._scene;
  21605. var engine = this._scene.getEngine();
  21606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances !== null);
  21607. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  21608. return;
  21609. }
  21610. var mesh = subMesh.getRenderingMesh();
  21611. var material = subMesh.getMaterial();
  21612. engine.enableEffect(this._effect);
  21613. this._effect.setFloat("offset", mesh.outlineWidth);
  21614. this._effect.setColor3("color", mesh.outlineColor);
  21615. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  21616. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  21617. if (useBones) {
  21618. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  21619. }
  21620. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  21621. if (material && material.needAlphaTesting()) {
  21622. var alphaTexture = material.getAlphaTestTexture();
  21623. this._effect.setTexture("diffuseSampler", alphaTexture);
  21624. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  21625. }
  21626. if (hardwareInstancedRendering) {
  21627. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  21628. } else {
  21629. if (batch.renderSelf[subMesh._id]) {
  21630. this._effect.setMatrix("world", mesh.getWorldMatrix());
  21631. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21632. }
  21633. if (batch.visibleInstances[subMesh._id]) {
  21634. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21635. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21636. this._effect.setMatrix("world", instance.getWorldMatrix());
  21637. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  21638. }
  21639. }
  21640. }
  21641. };
  21642. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  21643. var defines = [];
  21644. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  21645. var mesh = subMesh.getMesh();
  21646. var material = subMesh.getMaterial();
  21647. if (material && material.needAlphaTesting()) {
  21648. defines.push("#define ALPHATEST");
  21649. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21650. attribs.push(BABYLON.VertexBuffer.UVKind);
  21651. defines.push("#define UV1");
  21652. }
  21653. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21654. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  21655. defines.push("#define UV2");
  21656. }
  21657. }
  21658. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21661. defines.push("#define BONES");
  21662. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  21663. }
  21664. if (useInstances) {
  21665. defines.push("#define INSTANCES");
  21666. attribs.push("world0");
  21667. attribs.push("world1");
  21668. attribs.push("world2");
  21669. attribs.push("world3");
  21670. }
  21671. var join = defines.join("\n");
  21672. if (this._cachedDefines != join) {
  21673. this._cachedDefines = join;
  21674. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  21675. }
  21676. return this._effect.isReady();
  21677. };
  21678. return OutlineRenderer;
  21679. })();
  21680. BABYLON.OutlineRenderer = OutlineRenderer;
  21681. })(BABYLON || (BABYLON = {}));
  21682. var BABYLON;
  21683. (function (BABYLON) {
  21684. var MeshAssetTask = (function () {
  21685. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  21686. this.name = name;
  21687. this.meshesNames = meshesNames;
  21688. this.rootUrl = rootUrl;
  21689. this.sceneFilename = sceneFilename;
  21690. this.isCompleted = false;
  21691. }
  21692. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21693. var _this = this;
  21694. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  21695. _this.loadedMeshes = meshes;
  21696. _this.loadedParticleSystems = particleSystems;
  21697. _this.loadedSkeletons = skeletons;
  21698. _this.isCompleted = true;
  21699. if (_this.onSuccess) {
  21700. _this.onSuccess(_this);
  21701. }
  21702. onSuccess();
  21703. }, null, function () {
  21704. if (_this.onError) {
  21705. _this.onError(_this);
  21706. }
  21707. onError();
  21708. });
  21709. };
  21710. return MeshAssetTask;
  21711. })();
  21712. BABYLON.MeshAssetTask = MeshAssetTask;
  21713. var TextFileAssetTask = (function () {
  21714. function TextFileAssetTask(name, url) {
  21715. this.name = name;
  21716. this.url = url;
  21717. this.isCompleted = false;
  21718. }
  21719. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21720. var _this = this;
  21721. BABYLON.Tools.LoadFile(this.url, function (data) {
  21722. _this.text = data;
  21723. _this.isCompleted = true;
  21724. if (_this.onSuccess) {
  21725. _this.onSuccess(_this);
  21726. }
  21727. onSuccess();
  21728. }, null, scene.database, false, function () {
  21729. if (_this.onError) {
  21730. _this.onError(_this);
  21731. }
  21732. onError();
  21733. });
  21734. };
  21735. return TextFileAssetTask;
  21736. })();
  21737. BABYLON.TextFileAssetTask = TextFileAssetTask;
  21738. var BinaryFileAssetTask = (function () {
  21739. function BinaryFileAssetTask(name, url) {
  21740. this.name = name;
  21741. this.url = url;
  21742. this.isCompleted = false;
  21743. }
  21744. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21745. var _this = this;
  21746. BABYLON.Tools.LoadFile(this.url, function (data) {
  21747. _this.data = data;
  21748. _this.isCompleted = true;
  21749. if (_this.onSuccess) {
  21750. _this.onSuccess(_this);
  21751. }
  21752. onSuccess();
  21753. }, null, scene.database, true, function () {
  21754. if (_this.onError) {
  21755. _this.onError(_this);
  21756. }
  21757. onError();
  21758. });
  21759. };
  21760. return BinaryFileAssetTask;
  21761. })();
  21762. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  21763. var ImageAssetTask = (function () {
  21764. function ImageAssetTask(name, url) {
  21765. this.name = name;
  21766. this.url = url;
  21767. this.isCompleted = false;
  21768. }
  21769. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21770. var _this = this;
  21771. var img = new Image();
  21772. img.onload = function () {
  21773. _this.image = img;
  21774. _this.isCompleted = true;
  21775. if (_this.onSuccess) {
  21776. _this.onSuccess(_this);
  21777. }
  21778. onSuccess();
  21779. };
  21780. img.onerror = function () {
  21781. if (_this.onError) {
  21782. _this.onError(_this);
  21783. }
  21784. onError();
  21785. };
  21786. img.src = this.url;
  21787. };
  21788. return ImageAssetTask;
  21789. })();
  21790. BABYLON.ImageAssetTask = ImageAssetTask;
  21791. var TextureAssetTask = (function () {
  21792. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  21793. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21794. this.name = name;
  21795. this.url = url;
  21796. this.noMipmap = noMipmap;
  21797. this.invertY = invertY;
  21798. this.samplingMode = samplingMode;
  21799. this.isCompleted = false;
  21800. }
  21801. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  21802. var _this = this;
  21803. var onload = function () {
  21804. _this.isCompleted = true;
  21805. if (_this.onSuccess) {
  21806. _this.onSuccess(_this);
  21807. }
  21808. onSuccess();
  21809. };
  21810. var onerror = function () {
  21811. if (_this.onError) {
  21812. _this.onError(_this);
  21813. }
  21814. onError();
  21815. };
  21816. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  21817. };
  21818. return TextureAssetTask;
  21819. })();
  21820. BABYLON.TextureAssetTask = TextureAssetTask;
  21821. var AssetsManager = (function () {
  21822. function AssetsManager(scene) {
  21823. this._tasks = new Array();
  21824. this._waitingTasksCount = 0;
  21825. this.useDefaultLoadingScreen = true;
  21826. this._scene = scene;
  21827. }
  21828. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  21829. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  21830. this._tasks.push(task);
  21831. return task;
  21832. };
  21833. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  21834. var task = new TextFileAssetTask(taskName, url);
  21835. this._tasks.push(task);
  21836. return task;
  21837. };
  21838. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  21839. var task = new BinaryFileAssetTask(taskName, url);
  21840. this._tasks.push(task);
  21841. return task;
  21842. };
  21843. AssetsManager.prototype.addImageTask = function (taskName, url) {
  21844. var task = new ImageAssetTask(taskName, url);
  21845. this._tasks.push(task);
  21846. return task;
  21847. };
  21848. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  21849. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21850. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  21851. this._tasks.push(task);
  21852. return task;
  21853. };
  21854. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  21855. this._waitingTasksCount--;
  21856. if (this._waitingTasksCount === 0) {
  21857. if (this.onFinish) {
  21858. this.onFinish(this._tasks);
  21859. }
  21860. this._scene.getEngine().hideLoadingUI();
  21861. }
  21862. };
  21863. AssetsManager.prototype._runTask = function (task) {
  21864. var _this = this;
  21865. task.run(this._scene, function () {
  21866. if (_this.onTaskSuccess) {
  21867. _this.onTaskSuccess(task);
  21868. }
  21869. _this._decreaseWaitingTasksCount();
  21870. }, function () {
  21871. if (_this.onTaskError) {
  21872. _this.onTaskError(task);
  21873. }
  21874. _this._decreaseWaitingTasksCount();
  21875. });
  21876. };
  21877. AssetsManager.prototype.reset = function () {
  21878. this._tasks = new Array();
  21879. return this;
  21880. };
  21881. AssetsManager.prototype.load = function () {
  21882. this._waitingTasksCount = this._tasks.length;
  21883. if (this._waitingTasksCount === 0) {
  21884. if (this.onFinish) {
  21885. this.onFinish(this._tasks);
  21886. }
  21887. return this;
  21888. }
  21889. if (this.useDefaultLoadingScreen) {
  21890. this._scene.getEngine().displayLoadingUI();
  21891. }
  21892. for (var index = 0; index < this._tasks.length; index++) {
  21893. var task = this._tasks[index];
  21894. this._runTask(task);
  21895. }
  21896. return this;
  21897. };
  21898. return AssetsManager;
  21899. })();
  21900. BABYLON.AssetsManager = AssetsManager;
  21901. })(BABYLON || (BABYLON = {}));
  21902. var __extends = this.__extends || function (d, b) {
  21903. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21904. function __() { this.constructor = d; }
  21905. __.prototype = b.prototype;
  21906. d.prototype = new __();
  21907. };
  21908. var BABYLON;
  21909. (function (BABYLON) {
  21910. var VRDeviceOrientationCamera = (function (_super) {
  21911. __extends(VRDeviceOrientationCamera, _super);
  21912. function VRDeviceOrientationCamera(name, position, scene) {
  21913. _super.call(this, name, position, scene);
  21914. this._alpha = 0;
  21915. this._beta = 0;
  21916. this._gamma = 0;
  21917. }
  21918. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  21919. this._alpha = +evt.alpha | 0;
  21920. this._beta = +evt.beta | 0;
  21921. this._gamma = +evt.gamma | 0;
  21922. if (this._gamma < 0) {
  21923. this._gamma = 90 + this._gamma;
  21924. } else {
  21925. this._gamma = 270 - this._gamma;
  21926. }
  21927. this.rotation.x = this._gamma / 180.0 * Math.PI;
  21928. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  21929. this.rotation.z = this._beta / 180.0 * Math.PI;
  21930. };
  21931. return VRDeviceOrientationCamera;
  21932. })(BABYLON.OculusCamera);
  21933. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  21934. })(BABYLON || (BABYLON = {}));
  21935. var __extends = this.__extends || function (d, b) {
  21936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21937. function __() { this.constructor = d; }
  21938. __.prototype = b.prototype;
  21939. d.prototype = new __();
  21940. };
  21941. var BABYLON;
  21942. (function (BABYLON) {
  21943. var WebVRCamera = (function (_super) {
  21944. __extends(WebVRCamera, _super);
  21945. function WebVRCamera(name, position, scene) {
  21946. _super.call(this, name, position, scene);
  21947. this._hmdDevice = null;
  21948. this._sensorDevice = null;
  21949. this._cacheState = null;
  21950. this._cacheQuaternion = new BABYLON.Quaternion();
  21951. this._cacheRotation = BABYLON.Vector3.Zero();
  21952. this._vrEnabled = false;
  21953. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  21954. }
  21955. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  21956. var size = devices.length;
  21957. var i = 0;
  21958. this._sensorDevice = null;
  21959. this._hmdDevice = null;
  21960. while (i < size && this._hmdDevice === null) {
  21961. if (devices[i] instanceof HMDVRDevice) {
  21962. this._hmdDevice = devices[i];
  21963. }
  21964. i++;
  21965. }
  21966. i = 0;
  21967. while (i < size && this._sensorDevice === null) {
  21968. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  21969. this._sensorDevice = devices[i];
  21970. }
  21971. i++;
  21972. }
  21973. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  21974. };
  21975. WebVRCamera.prototype._update = function () {
  21976. if (this._vrEnabled) {
  21977. this._cacheState = this._sensorDevice.getState();
  21978. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  21979. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  21980. this.rotation.x = -this._cacheRotation.z;
  21981. this.rotation.y = -this._cacheRotation.y;
  21982. this.rotation.z = this._cacheRotation.x;
  21983. }
  21984. _super.prototype._update.call(this);
  21985. };
  21986. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  21987. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21988. if (navigator.getVRDevices) {
  21989. navigator.getVRDevices().then(this._getWebVRDevices);
  21990. } else if (navigator.mozGetVRDevices) {
  21991. navigator.mozGetVRDevices(this._getWebVRDevices);
  21992. }
  21993. };
  21994. WebVRCamera.prototype.detachControl = function (element) {
  21995. _super.prototype.detachControl.call(this, element);
  21996. this._vrEnabled = false;
  21997. };
  21998. return WebVRCamera;
  21999. })(BABYLON.OculusCamera);
  22000. BABYLON.WebVRCamera = WebVRCamera;
  22001. })(BABYLON || (BABYLON = {}));
  22002. var __extends = this.__extends || function (d, b) {
  22003. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22004. function __() { this.constructor = d; }
  22005. __.prototype = b.prototype;
  22006. d.prototype = new __();
  22007. };
  22008. var BABYLON;
  22009. (function (BABYLON) {
  22010. var SceneOptimization = (function () {
  22011. function SceneOptimization(priority) {
  22012. if (typeof priority === "undefined") { priority = 0; }
  22013. this.priority = priority;
  22014. this.apply = function (scene) {
  22015. return true;
  22016. };
  22017. }
  22018. return SceneOptimization;
  22019. })();
  22020. BABYLON.SceneOptimization = SceneOptimization;
  22021. var TextureOptimization = (function (_super) {
  22022. __extends(TextureOptimization, _super);
  22023. function TextureOptimization(priority, maximumSize) {
  22024. if (typeof priority === "undefined") { priority = 0; }
  22025. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  22026. var _this = this;
  22027. _super.call(this, priority);
  22028. this.priority = priority;
  22029. this.maximumSize = maximumSize;
  22030. this.apply = function (scene) {
  22031. var allDone = true;
  22032. for (var index = 0; index < scene.textures.length; index++) {
  22033. var texture = scene.textures[index];
  22034. if (!texture.canRescale) {
  22035. continue;
  22036. }
  22037. var currentSize = texture.getSize();
  22038. var maxDimension = Math.max(currentSize.width, currentSize.height);
  22039. if (maxDimension > _this.maximumSize) {
  22040. texture.scale(0.5);
  22041. allDone = false;
  22042. }
  22043. }
  22044. return allDone;
  22045. };
  22046. }
  22047. return TextureOptimization;
  22048. })(SceneOptimization);
  22049. BABYLON.TextureOptimization = TextureOptimization;
  22050. var HardwareScalingOptimization = (function (_super) {
  22051. __extends(HardwareScalingOptimization, _super);
  22052. function HardwareScalingOptimization(priority, maximumScale) {
  22053. if (typeof priority === "undefined") { priority = 0; }
  22054. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  22055. var _this = this;
  22056. _super.call(this, priority);
  22057. this.priority = priority;
  22058. this.maximumScale = maximumScale;
  22059. this._currentScale = 1;
  22060. this.apply = function (scene) {
  22061. _this._currentScale++;
  22062. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  22063. return _this._currentScale >= _this.maximumScale;
  22064. };
  22065. }
  22066. return HardwareScalingOptimization;
  22067. })(SceneOptimization);
  22068. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  22069. var ShadowsOptimization = (function (_super) {
  22070. __extends(ShadowsOptimization, _super);
  22071. function ShadowsOptimization() {
  22072. _super.apply(this, arguments);
  22073. this.apply = function (scene) {
  22074. scene.shadowsEnabled = false;
  22075. return true;
  22076. };
  22077. }
  22078. return ShadowsOptimization;
  22079. })(SceneOptimization);
  22080. BABYLON.ShadowsOptimization = ShadowsOptimization;
  22081. var PostProcessesOptimization = (function (_super) {
  22082. __extends(PostProcessesOptimization, _super);
  22083. function PostProcessesOptimization() {
  22084. _super.apply(this, arguments);
  22085. this.apply = function (scene) {
  22086. scene.postProcessesEnabled = false;
  22087. return true;
  22088. };
  22089. }
  22090. return PostProcessesOptimization;
  22091. })(SceneOptimization);
  22092. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  22093. var LensFlaresOptimization = (function (_super) {
  22094. __extends(LensFlaresOptimization, _super);
  22095. function LensFlaresOptimization() {
  22096. _super.apply(this, arguments);
  22097. this.apply = function (scene) {
  22098. scene.lensFlaresEnabled = false;
  22099. return true;
  22100. };
  22101. }
  22102. return LensFlaresOptimization;
  22103. })(SceneOptimization);
  22104. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  22105. var ParticlesOptimization = (function (_super) {
  22106. __extends(ParticlesOptimization, _super);
  22107. function ParticlesOptimization() {
  22108. _super.apply(this, arguments);
  22109. this.apply = function (scene) {
  22110. scene.particlesEnabled = false;
  22111. return true;
  22112. };
  22113. }
  22114. return ParticlesOptimization;
  22115. })(SceneOptimization);
  22116. BABYLON.ParticlesOptimization = ParticlesOptimization;
  22117. var RenderTargetsOptimization = (function (_super) {
  22118. __extends(RenderTargetsOptimization, _super);
  22119. function RenderTargetsOptimization() {
  22120. _super.apply(this, arguments);
  22121. this.apply = function (scene) {
  22122. scene.renderTargetsEnabled = false;
  22123. return true;
  22124. };
  22125. }
  22126. return RenderTargetsOptimization;
  22127. })(SceneOptimization);
  22128. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  22129. var SceneOptimizerOptions = (function () {
  22130. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  22131. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  22132. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  22133. this.targetFrameRate = targetFrameRate;
  22134. this.trackerDuration = trackerDuration;
  22135. this.optimizations = new Array();
  22136. }
  22137. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  22138. var result = new SceneOptimizerOptions(targetFrameRate);
  22139. var priority = 0;
  22140. result.optimizations.push(new ShadowsOptimization(priority));
  22141. result.optimizations.push(new LensFlaresOptimization(priority));
  22142. priority++;
  22143. result.optimizations.push(new PostProcessesOptimization(priority));
  22144. result.optimizations.push(new ParticlesOptimization(priority));
  22145. priority++;
  22146. result.optimizations.push(new TextureOptimization(priority, 1024));
  22147. return result;
  22148. };
  22149. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  22150. var result = new SceneOptimizerOptions(targetFrameRate);
  22151. var priority = 0;
  22152. result.optimizations.push(new ShadowsOptimization(priority));
  22153. result.optimizations.push(new LensFlaresOptimization(priority));
  22154. priority++;
  22155. result.optimizations.push(new PostProcessesOptimization(priority));
  22156. result.optimizations.push(new ParticlesOptimization(priority));
  22157. priority++;
  22158. result.optimizations.push(new TextureOptimization(priority, 512));
  22159. priority++;
  22160. result.optimizations.push(new RenderTargetsOptimization(priority));
  22161. priority++;
  22162. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  22163. return result;
  22164. };
  22165. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  22166. var result = new SceneOptimizerOptions(targetFrameRate);
  22167. var priority = 0;
  22168. result.optimizations.push(new ShadowsOptimization(priority));
  22169. result.optimizations.push(new LensFlaresOptimization(priority));
  22170. priority++;
  22171. result.optimizations.push(new PostProcessesOptimization(priority));
  22172. result.optimizations.push(new ParticlesOptimization(priority));
  22173. priority++;
  22174. result.optimizations.push(new TextureOptimization(priority, 256));
  22175. priority++;
  22176. result.optimizations.push(new RenderTargetsOptimization(priority));
  22177. priority++;
  22178. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  22179. return result;
  22180. };
  22181. return SceneOptimizerOptions;
  22182. })();
  22183. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  22184. var SceneOptimizer = (function () {
  22185. function SceneOptimizer() {
  22186. }
  22187. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  22188. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  22189. if (onSuccess) {
  22190. onSuccess();
  22191. }
  22192. return;
  22193. }
  22194. var allDone = true;
  22195. var noOptimizationApplied = true;
  22196. for (var index = 0; index < options.optimizations.length; index++) {
  22197. var optimization = options.optimizations[index];
  22198. if (optimization.priority === currentPriorityLevel) {
  22199. noOptimizationApplied = false;
  22200. allDone = allDone && optimization.apply(scene);
  22201. }
  22202. }
  22203. if (noOptimizationApplied) {
  22204. if (onFailure) {
  22205. onFailure();
  22206. }
  22207. return;
  22208. }
  22209. if (allDone) {
  22210. currentPriorityLevel++;
  22211. }
  22212. scene.executeWhenReady(function () {
  22213. setTimeout(function () {
  22214. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  22215. }, options.trackerDuration);
  22216. });
  22217. };
  22218. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  22219. if (!options) {
  22220. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  22221. }
  22222. scene.executeWhenReady(function () {
  22223. setTimeout(function () {
  22224. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  22225. }, options.trackerDuration);
  22226. });
  22227. };
  22228. return SceneOptimizer;
  22229. })();
  22230. BABYLON.SceneOptimizer = SceneOptimizer;
  22231. })(BABYLON || (BABYLON = {}));
  22232. var BABYLON;
  22233. (function (BABYLON) {
  22234. (function (Internals) {
  22235. var MeshLODLevel = (function () {
  22236. function MeshLODLevel(distance, mesh) {
  22237. this.distance = distance;
  22238. this.mesh = mesh;
  22239. }
  22240. return MeshLODLevel;
  22241. })();
  22242. Internals.MeshLODLevel = MeshLODLevel;
  22243. })(BABYLON.Internals || (BABYLON.Internals = {}));
  22244. var Internals = BABYLON.Internals;
  22245. })(BABYLON || (BABYLON = {}));