babylon.2.0-alpha.debug.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (typeof r === "undefined") { r = 0; }
  6. if (typeof g === "undefined") { g = 0; }
  7. if (typeof b === "undefined") { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. Color3.prototype.toArray = function (array, index) {
  16. if (index === undefined) {
  17. index = 0;
  18. }
  19. array[index] = this.r;
  20. array[index + 1] = this.g;
  21. array[index + 2] = this.b;
  22. };
  23. Color3.prototype.toColor4 = function (alpha) {
  24. if (typeof alpha === "undefined") { alpha = 1; }
  25. return new Color4(this.r, this.g, this.b, alpha);
  26. };
  27. Color3.prototype.asArray = function () {
  28. var result = [];
  29. this.toArray(result, 0);
  30. return result;
  31. };
  32. Color3.prototype.toLuminance = function () {
  33. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  34. };
  35. Color3.prototype.multiply = function (otherColor) {
  36. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  37. };
  38. Color3.prototype.multiplyToRef = function (otherColor, result) {
  39. result.r = this.r * otherColor.r;
  40. result.g = this.g * otherColor.g;
  41. result.b = this.b * otherColor.b;
  42. };
  43. Color3.prototype.equals = function (otherColor) {
  44. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  45. };
  46. Color3.prototype.scale = function (scale) {
  47. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  48. };
  49. Color3.prototype.scaleToRef = function (scale, result) {
  50. result.r = this.r * scale;
  51. result.g = this.g * scale;
  52. result.b = this.b * scale;
  53. };
  54. Color3.prototype.add = function (otherColor) {
  55. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  56. };
  57. Color3.prototype.addToRef = function (otherColor, result) {
  58. result.r = this.r + otherColor.r;
  59. result.g = this.g + otherColor.g;
  60. result.b = this.b + otherColor.b;
  61. };
  62. Color3.prototype.subtract = function (otherColor) {
  63. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  64. };
  65. Color3.prototype.subtractToRef = function (otherColor, result) {
  66. result.r = this.r - otherColor.r;
  67. result.g = this.g - otherColor.g;
  68. result.b = this.b - otherColor.b;
  69. };
  70. Color3.prototype.clone = function () {
  71. return new Color3(this.r, this.g, this.b);
  72. };
  73. Color3.prototype.copyFrom = function (source) {
  74. this.r = source.r;
  75. this.g = source.g;
  76. this.b = source.b;
  77. };
  78. Color3.prototype.copyFromFloats = function (r, g, b) {
  79. this.r = r;
  80. this.g = g;
  81. this.b = b;
  82. };
  83. Color3.FromArray = function (array) {
  84. return new Color3(array[0], array[1], array[2]);
  85. };
  86. Color3.FromInts = function (r, g, b) {
  87. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  88. };
  89. Color3.Lerp = function (start, end, amount) {
  90. var r = start.r + ((end.r - start.r) * amount);
  91. var g = start.g + ((end.g - start.g) * amount);
  92. var b = start.b + ((end.b - start.b) * amount);
  93. return new Color3(r, g, b);
  94. };
  95. Color3.Red = function () {
  96. return new Color3(1, 0, 0);
  97. };
  98. Color3.Green = function () {
  99. return new Color3(0, 1, 0);
  100. };
  101. Color3.Blue = function () {
  102. return new Color3(0, 0, 1);
  103. };
  104. Color3.Black = function () {
  105. return new Color3(0, 0, 0);
  106. };
  107. Color3.White = function () {
  108. return new Color3(1, 1, 1);
  109. };
  110. Color3.Purple = function () {
  111. return new Color3(0.5, 0, 0.5);
  112. };
  113. Color3.Magenta = function () {
  114. return new Color3(1, 0, 1);
  115. };
  116. Color3.Yellow = function () {
  117. return new Color3(1, 1, 0);
  118. };
  119. Color3.Gray = function () {
  120. return new Color3(0.5, 0.5, 0.5);
  121. };
  122. return Color3;
  123. })();
  124. BABYLON.Color3 = Color3;
  125. var Color4 = (function () {
  126. function Color4(r, g, b, a) {
  127. this.r = r;
  128. this.g = g;
  129. this.b = b;
  130. this.a = a;
  131. }
  132. Color4.prototype.addInPlace = function (right) {
  133. this.r += right.r;
  134. this.g += right.g;
  135. this.b += right.b;
  136. this.a += right.a;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. };
  152. Color4.prototype.add = function (right) {
  153. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  154. };
  155. Color4.prototype.subtract = function (right) {
  156. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  157. };
  158. Color4.prototype.subtractToRef = function (right, result) {
  159. result.r = this.r - right.r;
  160. result.g = this.g - right.g;
  161. result.b = this.b - right.b;
  162. result.a = this.a - right.a;
  163. };
  164. Color4.prototype.scale = function (scale) {
  165. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  166. };
  167. Color4.prototype.scaleToRef = function (scale, result) {
  168. result.r = this.r * scale;
  169. result.g = this.g * scale;
  170. result.b = this.b * scale;
  171. result.a = this.a * scale;
  172. };
  173. Color4.prototype.toString = function () {
  174. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  175. };
  176. Color4.prototype.clone = function () {
  177. return new Color4(this.r, this.g, this.b, this.a);
  178. };
  179. Color4.Lerp = function (left, right, amount) {
  180. var result = new Color4(0, 0, 0, 0);
  181. BABYLON.Color4.LerpToRef(left, right, amount, result);
  182. return result;
  183. };
  184. Color4.LerpToRef = function (left, right, amount, result) {
  185. result.r = left.r + (right.r - left.r) * amount;
  186. result.g = left.g + (right.g - left.g) * amount;
  187. result.b = left.b + (right.b - left.b) * amount;
  188. result.a = left.a + (right.a - left.a) * amount;
  189. };
  190. Color4.FromArray = function (array, offset) {
  191. if (typeof offset === "undefined") { offset = 0; }
  192. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  193. };
  194. Color4.FromInts = function (r, g, b, a) {
  195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  196. };
  197. return Color4;
  198. })();
  199. BABYLON.Color4 = Color4;
  200. var Vector2 = (function () {
  201. function Vector2(x, y) {
  202. this.x = x;
  203. this.y = y;
  204. }
  205. Vector2.prototype.toString = function () {
  206. return "{X: " + this.x + " Y:" + this.y + "}";
  207. };
  208. Vector2.prototype.toArray = function (array, index) {
  209. if (index === undefined) {
  210. index = 0;
  211. }
  212. array[index] = this.x;
  213. array[index + 1] = this.y;
  214. };
  215. Vector2.prototype.asArray = function () {
  216. var result = [];
  217. this.toArray(result, 0);
  218. return result;
  219. };
  220. Vector2.prototype.copyFrom = function (source) {
  221. this.x = source.x;
  222. this.y = source.y;
  223. };
  224. Vector2.prototype.copyFromFloats = function (x, y) {
  225. this.x = x;
  226. this.y = y;
  227. };
  228. Vector2.prototype.add = function (otherVector) {
  229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  230. };
  231. Vector2.prototype.addVector3 = function (otherVector) {
  232. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  233. };
  234. Vector2.prototype.subtract = function (otherVector) {
  235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  236. };
  237. Vector2.prototype.subtractInPlace = function (otherVector) {
  238. this.x -= otherVector.x;
  239. this.y -= otherVector.y;
  240. };
  241. Vector2.prototype.multiplyInPlace = function (otherVector) {
  242. this.x *= otherVector.x;
  243. this.y *= otherVector.y;
  244. };
  245. Vector2.prototype.multiply = function (otherVector) {
  246. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  247. };
  248. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  249. result.x = this.x * otherVector.x;
  250. result.y = this.y * otherVector.y;
  251. };
  252. Vector2.prototype.multiplyByFloats = function (x, y) {
  253. return new Vector2(this.x * x, this.y * y);
  254. };
  255. Vector2.prototype.divide = function (otherVector) {
  256. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  257. };
  258. Vector2.prototype.divideToRef = function (otherVector, result) {
  259. result.x = this.x / otherVector.x;
  260. result.y = this.y / otherVector.y;
  261. };
  262. Vector2.prototype.negate = function () {
  263. return new Vector2(-this.x, -this.y);
  264. };
  265. Vector2.prototype.scaleInPlace = function (scale) {
  266. this.x *= scale;
  267. this.y *= scale;
  268. return this;
  269. };
  270. Vector2.prototype.scale = function (scale) {
  271. return new Vector2(this.x * scale, this.y * scale);
  272. };
  273. Vector2.prototype.equals = function (otherVector) {
  274. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  275. };
  276. Vector2.prototype.length = function () {
  277. return Math.sqrt(this.x * this.x + this.y * this.y);
  278. };
  279. Vector2.prototype.lengthSquared = function () {
  280. return (this.x * this.x + this.y * this.y);
  281. };
  282. Vector2.prototype.normalize = function () {
  283. var len = this.length();
  284. if (len === 0)
  285. return this;
  286. var num = 1.0 / len;
  287. this.x *= num;
  288. this.y *= num;
  289. return this;
  290. };
  291. Vector2.prototype.clone = function () {
  292. return new Vector2(this.x, this.y);
  293. };
  294. Vector2.Zero = function () {
  295. return new Vector2(0, 0);
  296. };
  297. Vector2.FromArray = function (array, offset) {
  298. if (!offset) {
  299. offset = 0;
  300. }
  301. return new Vector2(array[offset], array[offset + 1]);
  302. };
  303. Vector2.FromArrayToRef = function (array, offset, result) {
  304. result.x = array[offset];
  305. result.y = array[offset + 1];
  306. };
  307. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  308. var squared = amount * amount;
  309. var cubed = amount * squared;
  310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  311. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  312. return new Vector2(x, y);
  313. };
  314. Vector2.Clamp = function (value, min, max) {
  315. var x = value.x;
  316. x = (x > max.x) ? max.x : x;
  317. x = (x < min.x) ? min.x : x;
  318. var y = value.y;
  319. y = (y > max.y) ? max.y : y;
  320. y = (y < min.y) ? min.y : y;
  321. return new Vector2(x, y);
  322. };
  323. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  324. var squared = amount * amount;
  325. var cubed = amount * squared;
  326. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  327. var part2 = (-2.0 * cubed) + (3.0 * squared);
  328. var part3 = (cubed - (2.0 * squared)) + amount;
  329. var part4 = cubed - squared;
  330. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  331. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  332. return new Vector2(x, y);
  333. };
  334. Vector2.Lerp = function (start, end, amount) {
  335. var x = start.x + ((end.x - start.x) * amount);
  336. var y = start.y + ((end.y - start.y) * amount);
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Dot = function (left, right) {
  340. return left.x * right.x + left.y * right.y;
  341. };
  342. Vector2.Normalize = function (vector) {
  343. var newVector = vector.clone();
  344. newVector.normalize();
  345. return newVector;
  346. };
  347. Vector2.Minimize = function (left, right) {
  348. var x = (left.x < right.x) ? left.x : right.x;
  349. var y = (left.y < right.y) ? left.y : right.y;
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Maximize = function (left, right) {
  353. var x = (left.x > right.x) ? left.x : right.x;
  354. var y = (left.y > right.y) ? left.y : right.y;
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Transform = function (vector, transformation) {
  358. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  359. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  360. return new Vector2(x, y);
  361. };
  362. Vector2.Distance = function (value1, value2) {
  363. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  364. };
  365. Vector2.DistanceSquared = function (value1, value2) {
  366. var x = value1.x - value2.x;
  367. var y = value1.y - value2.y;
  368. return (x * x) + (y * y);
  369. };
  370. return Vector2;
  371. })();
  372. BABYLON.Vector2 = Vector2;
  373. var Vector3 = (function () {
  374. function Vector3(x, y, z) {
  375. this.x = x;
  376. this.y = y;
  377. this.z = z;
  378. }
  379. Vector3.prototype.toString = function () {
  380. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  381. };
  382. Vector3.prototype.asArray = function () {
  383. var result = [];
  384. this.toArray(result, 0);
  385. return result;
  386. };
  387. Vector3.prototype.toArray = function (array, index) {
  388. if (index === undefined) {
  389. index = 0;
  390. }
  391. array[index] = this.x;
  392. array[index + 1] = this.y;
  393. array[index + 2] = this.z;
  394. };
  395. Vector3.prototype.addInPlace = function (otherVector) {
  396. this.x += otherVector.x;
  397. this.y += otherVector.y;
  398. this.z += otherVector.z;
  399. };
  400. Vector3.prototype.add = function (otherVector) {
  401. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  402. };
  403. Vector3.prototype.addToRef = function (otherVector, result) {
  404. result.x = this.x + otherVector.x;
  405. result.y = this.y + otherVector.y;
  406. result.z = this.z + otherVector.z;
  407. };
  408. Vector3.prototype.subtractInPlace = function (otherVector) {
  409. this.x -= otherVector.x;
  410. this.y -= otherVector.y;
  411. this.z -= otherVector.z;
  412. };
  413. Vector3.prototype.subtract = function (otherVector) {
  414. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  415. };
  416. Vector3.prototype.subtractToRef = function (otherVector, result) {
  417. result.x = this.x - otherVector.x;
  418. result.y = this.y - otherVector.y;
  419. result.z = this.z - otherVector.z;
  420. };
  421. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  422. return new Vector3(this.x - x, this.y - y, this.z - z);
  423. };
  424. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  425. result.x = this.x - x;
  426. result.y = this.y - y;
  427. result.z = this.z - z;
  428. };
  429. Vector3.prototype.negate = function () {
  430. return new Vector3(-this.x, -this.y, -this.z);
  431. };
  432. Vector3.prototype.scaleInPlace = function (scale) {
  433. this.x *= scale;
  434. this.y *= scale;
  435. this.z *= scale;
  436. return this;
  437. };
  438. Vector3.prototype.scale = function (scale) {
  439. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  440. };
  441. Vector3.prototype.scaleToRef = function (scale, result) {
  442. result.x = this.x * scale;
  443. result.y = this.y * scale;
  444. result.z = this.z * scale;
  445. };
  446. Vector3.prototype.equals = function (otherVector) {
  447. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  448. };
  449. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  450. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  451. };
  452. Vector3.prototype.equalsToFloats = function (x, y, z) {
  453. return this.x === x && this.y === y && this.z === z;
  454. };
  455. Vector3.prototype.multiplyInPlace = function (otherVector) {
  456. this.x *= otherVector.x;
  457. this.y *= otherVector.y;
  458. this.z *= otherVector.z;
  459. };
  460. Vector3.prototype.multiply = function (otherVector) {
  461. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  462. };
  463. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  464. result.x = this.x * otherVector.x;
  465. result.y = this.y * otherVector.y;
  466. result.z = this.z * otherVector.z;
  467. };
  468. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  469. return new Vector3(this.x * x, this.y * y, this.z * z);
  470. };
  471. Vector3.prototype.divide = function (otherVector) {
  472. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  473. };
  474. Vector3.prototype.divideToRef = function (otherVector, result) {
  475. result.x = this.x / otherVector.x;
  476. result.y = this.y / otherVector.y;
  477. result.z = this.z / otherVector.z;
  478. };
  479. Vector3.prototype.MinimizeInPlace = function (other) {
  480. if (other.x < this.x)
  481. this.x = other.x;
  482. if (other.y < this.y)
  483. this.y = other.y;
  484. if (other.z < this.z)
  485. this.z = other.z;
  486. };
  487. Vector3.prototype.MaximizeInPlace = function (other) {
  488. if (other.x > this.x)
  489. this.x = other.x;
  490. if (other.y > this.y)
  491. this.y = other.y;
  492. if (other.z > this.z)
  493. this.z = other.z;
  494. };
  495. Vector3.prototype.length = function () {
  496. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  497. };
  498. Vector3.prototype.lengthSquared = function () {
  499. return (this.x * this.x + this.y * this.y + this.z * this.z);
  500. };
  501. Vector3.prototype.normalize = function () {
  502. var len = this.length();
  503. if (len === 0)
  504. return this;
  505. var num = 1.0 / len;
  506. this.x *= num;
  507. this.y *= num;
  508. this.z *= num;
  509. return this;
  510. };
  511. Vector3.prototype.clone = function () {
  512. return new Vector3(this.x, this.y, this.z);
  513. };
  514. Vector3.prototype.copyFrom = function (source) {
  515. this.x = source.x;
  516. this.y = source.y;
  517. this.z = source.z;
  518. };
  519. Vector3.prototype.copyFromFloats = function (x, y, z) {
  520. this.x = x;
  521. this.y = y;
  522. this.z = z;
  523. };
  524. Vector3.FromArray = function (array, offset) {
  525. if (!offset) {
  526. offset = 0;
  527. }
  528. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  529. };
  530. Vector3.FromArrayToRef = function (array, offset, result) {
  531. result.x = array[offset];
  532. result.y = array[offset + 1];
  533. result.z = array[offset + 2];
  534. };
  535. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  536. result.x = array[offset];
  537. result.y = array[offset + 1];
  538. result.z = array[offset + 2];
  539. };
  540. Vector3.FromFloatsToRef = function (x, y, z, result) {
  541. result.x = x;
  542. result.y = y;
  543. result.z = z;
  544. };
  545. Vector3.Zero = function () {
  546. return new Vector3(0, 0, 0);
  547. };
  548. Vector3.Up = function () {
  549. return new Vector3(0, 1.0, 0);
  550. };
  551. Vector3.TransformCoordinates = function (vector, transformation) {
  552. var result = Vector3.Zero();
  553. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  554. return result;
  555. };
  556. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  557. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  558. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  559. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  560. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  561. result.x = x / w;
  562. result.y = y / w;
  563. result.z = z / w;
  564. };
  565. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  566. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  567. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  568. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  569. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  570. result.x = rx / rw;
  571. result.y = ry / rw;
  572. result.z = rz / rw;
  573. };
  574. Vector3.TransformNormal = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformNormalToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  580. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  581. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  582. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  583. };
  584. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  585. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  586. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  587. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  588. };
  589. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  590. var squared = amount * amount;
  591. var cubed = amount * squared;
  592. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  593. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  594. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  595. return new Vector3(x, y, z);
  596. };
  597. Vector3.Clamp = function (value, min, max) {
  598. var x = value.x;
  599. x = (x > max.x) ? max.x : x;
  600. x = (x < min.x) ? min.x : x;
  601. var y = value.y;
  602. y = (y > max.y) ? max.y : y;
  603. y = (y < min.y) ? min.y : y;
  604. var z = value.z;
  605. z = (z > max.z) ? max.z : z;
  606. z = (z < min.z) ? min.z : z;
  607. return new Vector3(x, y, z);
  608. };
  609. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  610. var squared = amount * amount;
  611. var cubed = amount * squared;
  612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  614. var part3 = (cubed - (2.0 * squared)) + amount;
  615. var part4 = cubed - squared;
  616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  618. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  619. return new Vector3(x, y, z);
  620. };
  621. Vector3.Lerp = function (start, end, amount) {
  622. var x = start.x + ((end.x - start.x) * amount);
  623. var y = start.y + ((end.y - start.y) * amount);
  624. var z = start.z + ((end.z - start.z) * amount);
  625. return new Vector3(x, y, z);
  626. };
  627. Vector3.Dot = function (left, right) {
  628. return (left.x * right.x + left.y * right.y + left.z * right.z);
  629. };
  630. Vector3.Cross = function (left, right) {
  631. var result = Vector3.Zero();
  632. Vector3.CrossToRef(left, right, result);
  633. return result;
  634. };
  635. Vector3.CrossToRef = function (left, right, result) {
  636. result.x = left.y * right.z - left.z * right.y;
  637. result.y = left.z * right.x - left.x * right.z;
  638. result.z = left.x * right.y - left.y * right.x;
  639. };
  640. Vector3.Normalize = function (vector) {
  641. var result = Vector3.Zero();
  642. Vector3.NormalizeToRef(vector, result);
  643. return result;
  644. };
  645. Vector3.NormalizeToRef = function (vector, result) {
  646. result.copyFrom(vector);
  647. result.normalize();
  648. };
  649. Vector3.Project = function (vector, world, transform, viewport) {
  650. var cw = viewport.width;
  651. var ch = viewport.height;
  652. var cx = viewport.x;
  653. var cy = viewport.y;
  654. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  655. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  656. return Vector3.TransformCoordinates(vector, finalMatrix);
  657. };
  658. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  659. var matrix = world.multiply(view).multiply(projection);
  660. matrix.invert();
  661. source.x = source.x / viewportWidth * 2 - 1;
  662. source.y = -(source.y / viewportHeight * 2 - 1);
  663. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  665. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  666. vector = vector.scale(1.0 / num);
  667. }
  668. return vector;
  669. };
  670. Vector3.Minimize = function (left, right) {
  671. var min = left.clone();
  672. min.MinimizeInPlace(right);
  673. return min;
  674. };
  675. Vector3.Maximize = function (left, right) {
  676. var max = left.clone();
  677. max.MaximizeInPlace(right);
  678. return max;
  679. };
  680. Vector3.Distance = function (value1, value2) {
  681. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  682. };
  683. Vector3.DistanceSquared = function (value1, value2) {
  684. var x = value1.x - value2.x;
  685. var y = value1.y - value2.y;
  686. var z = value1.z - value2.z;
  687. return (x * x) + (y * y) + (z * z);
  688. };
  689. Vector3.Center = function (value1, value2) {
  690. var center = value1.add(value2);
  691. center.scaleInPlace(0.5);
  692. return center;
  693. };
  694. return Vector3;
  695. })();
  696. BABYLON.Vector3 = Vector3;
  697. var Vector4 = (function () {
  698. function Vector4(x, y, z, w) {
  699. this.x = x;
  700. this.y = y;
  701. this.z = z;
  702. this.w = w;
  703. }
  704. Vector4.prototype.toString = function () {
  705. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  706. };
  707. Vector4.prototype.asArray = function () {
  708. var result = [];
  709. this.toArray(result, 0);
  710. return result;
  711. };
  712. Vector4.prototype.toArray = function (array, index) {
  713. if (index === undefined) {
  714. index = 0;
  715. }
  716. array[index] = this.x;
  717. array[index + 1] = this.y;
  718. array[index + 2] = this.z;
  719. array[index + 3] = this.w;
  720. };
  721. Vector4.prototype.addInPlace = function (otherVector) {
  722. this.x += otherVector.x;
  723. this.y += otherVector.y;
  724. this.z += otherVector.z;
  725. this.w += otherVector.w;
  726. };
  727. Vector4.prototype.add = function (otherVector) {
  728. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  729. };
  730. Vector4.prototype.addToRef = function (otherVector, result) {
  731. result.x = this.x + otherVector.x;
  732. result.y = this.y + otherVector.y;
  733. result.z = this.z + otherVector.z;
  734. result.w = this.w + otherVector.w;
  735. };
  736. Vector4.prototype.subtractInPlace = function (otherVector) {
  737. this.x -= otherVector.x;
  738. this.y -= otherVector.y;
  739. this.z -= otherVector.z;
  740. this.w -= otherVector.w;
  741. };
  742. Vector4.prototype.subtract = function (otherVector) {
  743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  744. };
  745. Vector4.prototype.subtractToRef = function (otherVector, result) {
  746. result.x = this.x - otherVector.x;
  747. result.y = this.y - otherVector.y;
  748. result.z = this.z - otherVector.z;
  749. result.w = this.w - otherVector.w;
  750. };
  751. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  752. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  753. };
  754. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  755. result.x = this.x - x;
  756. result.y = this.y - y;
  757. result.z = this.z - z;
  758. result.w = this.w - w;
  759. };
  760. Vector4.prototype.negate = function () {
  761. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  762. };
  763. Vector4.prototype.scaleInPlace = function (scale) {
  764. this.x *= scale;
  765. this.y *= scale;
  766. this.z *= scale;
  767. this.w *= scale;
  768. return this;
  769. };
  770. Vector4.prototype.scale = function (scale) {
  771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  772. };
  773. Vector4.prototype.scaleToRef = function (scale, result) {
  774. result.x = this.x * scale;
  775. result.y = this.y * scale;
  776. result.z = this.z * scale;
  777. result.w = this.w * scale;
  778. };
  779. Vector4.prototype.equals = function (otherVector) {
  780. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  781. };
  782. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  783. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  784. };
  785. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  786. return this.x === x && this.y === y && this.z === z && this.w === w;
  787. };
  788. Vector4.prototype.multiplyInPlace = function (otherVector) {
  789. this.x *= otherVector.x;
  790. this.y *= otherVector.y;
  791. this.z *= otherVector.z;
  792. this.w *= otherVector.w;
  793. };
  794. Vector4.prototype.multiply = function (otherVector) {
  795. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  796. };
  797. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  798. result.x = this.x * otherVector.x;
  799. result.y = this.y * otherVector.y;
  800. result.z = this.z * otherVector.z;
  801. result.w = this.w * otherVector.w;
  802. };
  803. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  804. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  805. };
  806. Vector4.prototype.divide = function (otherVector) {
  807. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  808. };
  809. Vector4.prototype.divideToRef = function (otherVector, result) {
  810. result.x = this.x / otherVector.x;
  811. result.y = this.y / otherVector.y;
  812. result.z = this.z / otherVector.z;
  813. result.w = this.w / otherVector.w;
  814. };
  815. Vector4.prototype.MinimizeInPlace = function (other) {
  816. if (other.x < this.x)
  817. this.x = other.x;
  818. if (other.y < this.y)
  819. this.y = other.y;
  820. if (other.z < this.z)
  821. this.z = other.z;
  822. if (other.w < this.w)
  823. this.w = other.w;
  824. };
  825. Vector4.prototype.MaximizeInPlace = function (other) {
  826. if (other.x > this.x)
  827. this.x = other.x;
  828. if (other.y > this.y)
  829. this.y = other.y;
  830. if (other.z > this.z)
  831. this.z = other.z;
  832. if (other.w > this.w)
  833. this.w = other.w;
  834. };
  835. Vector4.prototype.length = function () {
  836. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  837. };
  838. Vector4.prototype.lengthSquared = function () {
  839. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  840. };
  841. Vector4.prototype.normalize = function () {
  842. var len = this.length();
  843. if (len === 0)
  844. return this;
  845. var num = 1.0 / len;
  846. this.x *= num;
  847. this.y *= num;
  848. this.z *= num;
  849. this.w *= num;
  850. return this;
  851. };
  852. Vector4.prototype.clone = function () {
  853. return new Vector4(this.x, this.y, this.z, this.w);
  854. };
  855. Vector4.prototype.copyFrom = function (source) {
  856. this.x = source.x;
  857. this.y = source.y;
  858. this.z = source.z;
  859. this.w = source.w;
  860. };
  861. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. this.w = w;
  866. };
  867. Vector4.FromArray = function (array, offset) {
  868. if (!offset) {
  869. offset = 0;
  870. }
  871. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  872. };
  873. Vector4.FromArrayToRef = function (array, offset, result) {
  874. result.x = array[offset];
  875. result.y = array[offset + 1];
  876. result.z = array[offset + 2];
  877. result.w = array[offset + 3];
  878. };
  879. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  880. result.x = array[offset];
  881. result.y = array[offset + 1];
  882. result.z = array[offset + 2];
  883. result.w = array[offset + 3];
  884. };
  885. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  886. result.x = x;
  887. result.y = y;
  888. result.z = z;
  889. result.w = w;
  890. };
  891. Vector4.Zero = function () {
  892. return new Vector4(0, 0, 0, 0);
  893. };
  894. Vector4.Normalize = function (vector) {
  895. var result = Vector4.Zero();
  896. Vector4.NormalizeToRef(vector, result);
  897. return result;
  898. };
  899. Vector4.NormalizeToRef = function (vector, result) {
  900. result.copyFrom(vector);
  901. result.normalize();
  902. };
  903. Vector4.Minimize = function (left, right) {
  904. var min = left.clone();
  905. min.MinimizeInPlace(right);
  906. return min;
  907. };
  908. Vector4.Maximize = function (left, right) {
  909. var max = left.clone();
  910. max.MaximizeInPlace(right);
  911. return max;
  912. };
  913. Vector4.Distance = function (value1, value2) {
  914. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  915. };
  916. Vector4.DistanceSquared = function (value1, value2) {
  917. var x = value1.x - value2.x;
  918. var y = value1.y - value2.y;
  919. var z = value1.z - value2.z;
  920. var w = value1.w - value2.w;
  921. return (x * x) + (y * y) + (z * z) + (w * w);
  922. };
  923. Vector4.Center = function (value1, value2) {
  924. var center = value1.add(value2);
  925. center.scaleInPlace(0.5);
  926. return center;
  927. };
  928. return Vector4;
  929. })();
  930. BABYLON.Vector4 = Vector4;
  931. var Quaternion = (function () {
  932. function Quaternion(x, y, z, w) {
  933. if (typeof x === "undefined") { x = 0; }
  934. if (typeof y === "undefined") { y = 0; }
  935. if (typeof z === "undefined") { z = 0; }
  936. if (typeof w === "undefined") { w = 1; }
  937. this.x = x;
  938. this.y = y;
  939. this.z = z;
  940. this.w = w;
  941. }
  942. Quaternion.prototype.toString = function () {
  943. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  944. };
  945. Quaternion.prototype.asArray = function () {
  946. return [this.x, this.y, this.z, this.w];
  947. };
  948. Quaternion.prototype.equals = function (otherQuaternion) {
  949. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  950. };
  951. Quaternion.prototype.clone = function () {
  952. return new Quaternion(this.x, this.y, this.z, this.w);
  953. };
  954. Quaternion.prototype.copyFrom = function (other) {
  955. this.x = other.x;
  956. this.y = other.y;
  957. this.z = other.z;
  958. this.w = other.w;
  959. };
  960. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  961. this.x = x;
  962. this.y = y;
  963. this.z = z;
  964. this.w = w;
  965. };
  966. Quaternion.prototype.add = function (other) {
  967. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  968. };
  969. Quaternion.prototype.subtract = function (other) {
  970. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  971. };
  972. Quaternion.prototype.scale = function (value) {
  973. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  974. };
  975. Quaternion.prototype.multiply = function (q1) {
  976. var result = new Quaternion(0, 0, 0, 1.0);
  977. this.multiplyToRef(q1, result);
  978. return result;
  979. };
  980. Quaternion.prototype.multiplyToRef = function (q1, result) {
  981. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  982. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  983. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  984. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  985. };
  986. Quaternion.prototype.length = function () {
  987. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  988. };
  989. Quaternion.prototype.normalize = function () {
  990. var length = 1.0 / this.length();
  991. this.x *= length;
  992. this.y *= length;
  993. this.z *= length;
  994. this.w *= length;
  995. };
  996. Quaternion.prototype.toEulerAngles = function () {
  997. var result = Vector3.Zero();
  998. this.toEulerAnglesToRef(result);
  999. return result;
  1000. };
  1001. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1002. var qx = this.x;
  1003. var qy = this.y;
  1004. var qz = this.z;
  1005. var qw = this.w;
  1006. var qxy = qx * qy;
  1007. var qxz = qx * qz;
  1008. var qwy = qw * qy;
  1009. var qwz = qw * qz;
  1010. var qwx = qw * qx;
  1011. var qyz = qy * qz;
  1012. var sqx = qx * qx;
  1013. var sqy = qy * qy;
  1014. var determinant = sqx + sqy;
  1015. if (determinant != 0.000 && determinant != 1.000) {
  1016. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1017. result.y = Math.acos(1 - 2 * determinant);
  1018. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1019. } else {
  1020. if (determinant == 0.000) {
  1021. result.x = 0.0;
  1022. result.y = 0.0;
  1023. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1024. } else {
  1025. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz);
  1026. result.y = Math.PI;
  1027. result.z = 0.0;
  1028. }
  1029. }
  1030. };
  1031. Quaternion.prototype.toRotationMatrix = function (result) {
  1032. var xx = this.x * this.x;
  1033. var yy = this.y * this.y;
  1034. var zz = this.z * this.z;
  1035. var xy = this.x * this.y;
  1036. var zw = this.z * this.w;
  1037. var zx = this.z * this.x;
  1038. var yw = this.y * this.w;
  1039. var yz = this.y * this.z;
  1040. var xw = this.x * this.w;
  1041. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1042. result.m[1] = 2.0 * (xy + zw);
  1043. result.m[2] = 2.0 * (zx - yw);
  1044. result.m[3] = 0;
  1045. result.m[4] = 2.0 * (xy - zw);
  1046. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1047. result.m[6] = 2.0 * (yz + xw);
  1048. result.m[7] = 0;
  1049. result.m[8] = 2.0 * (zx + yw);
  1050. result.m[9] = 2.0 * (yz - xw);
  1051. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1052. result.m[11] = 0;
  1053. result.m[12] = 0;
  1054. result.m[13] = 0;
  1055. result.m[14] = 0;
  1056. result.m[15] = 1.0;
  1057. };
  1058. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1059. var data = matrix.m;
  1060. var m11 = data[0], m12 = data[4], m13 = data[8];
  1061. var m21 = data[1], m22 = data[5], m23 = data[9];
  1062. var m31 = data[2], m32 = data[6], m33 = data[10];
  1063. var trace = m11 + m22 + m33;
  1064. var s;
  1065. if (trace > 0) {
  1066. s = 0.5 / Math.sqrt(trace + 1.0);
  1067. this.w = 0.25 / s;
  1068. this.x = (m32 - m23) * s;
  1069. this.y = (m13 - m31) * s;
  1070. this.z = (m21 - m12) * s;
  1071. return;
  1072. }
  1073. if (m11 > m22 && m11 > m33) {
  1074. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1075. this.w = (m32 - m23) / s;
  1076. this.x = 0.25 * s;
  1077. this.y = (m12 + m21) / s;
  1078. this.z = (m13 + m31) / s;
  1079. return;
  1080. }
  1081. if (m22 > m33) {
  1082. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1083. this.w = (m13 - m31) / s;
  1084. this.x = (m12 + m21) / s;
  1085. this.y = 0.25 * s;
  1086. this.z = (m23 + m32) / s;
  1087. return;
  1088. }
  1089. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1090. this.w = (m21 - m12) / s;
  1091. this.x = (m13 + m31) / s;
  1092. this.y = (m23 + m32) / s;
  1093. this.z = 0.25 * s;
  1094. };
  1095. Quaternion.Inverse = function (q) {
  1096. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1097. };
  1098. Quaternion.RotationAxis = function (axis, angle) {
  1099. var result = new Quaternion();
  1100. var sin = Math.sin(angle / 2);
  1101. result.w = Math.cos(angle / 2);
  1102. result.x = axis.x * sin;
  1103. result.y = axis.y * sin;
  1104. result.z = axis.z * sin;
  1105. return result;
  1106. };
  1107. Quaternion.FromArray = function (array, offset) {
  1108. if (!offset) {
  1109. offset = 0;
  1110. }
  1111. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1112. };
  1113. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1114. var result = new Quaternion();
  1115. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1116. return result;
  1117. };
  1118. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1119. var halfRoll = roll * 0.5;
  1120. var halfPitch = pitch * 0.5;
  1121. var halfYaw = yaw * 0.5;
  1122. var sinRoll = Math.sin(halfRoll);
  1123. var cosRoll = Math.cos(halfRoll);
  1124. var sinPitch = Math.sin(halfPitch);
  1125. var cosPitch = Math.cos(halfPitch);
  1126. var sinYaw = Math.sin(halfYaw);
  1127. var cosYaw = Math.cos(halfYaw);
  1128. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1129. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1130. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1131. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1132. };
  1133. Quaternion.Slerp = function (left, right, amount) {
  1134. var num2;
  1135. var num3;
  1136. var num = amount;
  1137. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1138. var flag = false;
  1139. if (num4 < 0) {
  1140. flag = true;
  1141. num4 = -num4;
  1142. }
  1143. if (num4 > 0.999999) {
  1144. num3 = 1 - num;
  1145. num2 = flag ? -num : num;
  1146. } else {
  1147. var num5 = Math.acos(num4);
  1148. var num6 = (1.0 / Math.sin(num5));
  1149. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1150. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1151. }
  1152. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1153. };
  1154. return Quaternion;
  1155. })();
  1156. BABYLON.Quaternion = Quaternion;
  1157. var Matrix = (function () {
  1158. function Matrix() {
  1159. this.m = new Float32Array(16);
  1160. }
  1161. Matrix.prototype.isIdentity = function () {
  1162. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1163. return false;
  1164. if (this.m[1] != 0.0 || this.m[2] != 0.0 || this.m[3] != 0.0 || this.m[4] != 0.0 || this.m[6] != 0.0 || this.m[7] != 0.0 || this.m[8] != 0.0 || this.m[9] != 0.0 || this.m[11] != 0.0 || this.m[12] != 0.0 || this.m[13] != 0.0 || this.m[14] != 0.0)
  1165. return false;
  1166. return true;
  1167. };
  1168. Matrix.prototype.determinant = function () {
  1169. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1170. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1171. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1172. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1173. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1174. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1175. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1176. };
  1177. Matrix.prototype.toArray = function () {
  1178. return this.m;
  1179. };
  1180. Matrix.prototype.asArray = function () {
  1181. return this.toArray();
  1182. };
  1183. Matrix.prototype.invert = function () {
  1184. this.invertToRef(this);
  1185. };
  1186. Matrix.prototype.invertToRef = function (other) {
  1187. var l1 = this.m[0];
  1188. var l2 = this.m[1];
  1189. var l3 = this.m[2];
  1190. var l4 = this.m[3];
  1191. var l5 = this.m[4];
  1192. var l6 = this.m[5];
  1193. var l7 = this.m[6];
  1194. var l8 = this.m[7];
  1195. var l9 = this.m[8];
  1196. var l10 = this.m[9];
  1197. var l11 = this.m[10];
  1198. var l12 = this.m[11];
  1199. var l13 = this.m[12];
  1200. var l14 = this.m[13];
  1201. var l15 = this.m[14];
  1202. var l16 = this.m[15];
  1203. var l17 = (l11 * l16) - (l12 * l15);
  1204. var l18 = (l10 * l16) - (l12 * l14);
  1205. var l19 = (l10 * l15) - (l11 * l14);
  1206. var l20 = (l9 * l16) - (l12 * l13);
  1207. var l21 = (l9 * l15) - (l11 * l13);
  1208. var l22 = (l9 * l14) - (l10 * l13);
  1209. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1210. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1211. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1212. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1213. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1214. var l28 = (l7 * l16) - (l8 * l15);
  1215. var l29 = (l6 * l16) - (l8 * l14);
  1216. var l30 = (l6 * l15) - (l7 * l14);
  1217. var l31 = (l5 * l16) - (l8 * l13);
  1218. var l32 = (l5 * l15) - (l7 * l13);
  1219. var l33 = (l5 * l14) - (l6 * l13);
  1220. var l34 = (l7 * l12) - (l8 * l11);
  1221. var l35 = (l6 * l12) - (l8 * l10);
  1222. var l36 = (l6 * l11) - (l7 * l10);
  1223. var l37 = (l5 * l12) - (l8 * l9);
  1224. var l38 = (l5 * l11) - (l7 * l9);
  1225. var l39 = (l5 * l10) - (l6 * l9);
  1226. other.m[0] = l23 * l27;
  1227. other.m[4] = l24 * l27;
  1228. other.m[8] = l25 * l27;
  1229. other.m[12] = l26 * l27;
  1230. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1231. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1232. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1233. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1234. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1235. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1236. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1237. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1238. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1239. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1240. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1241. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1242. };
  1243. Matrix.prototype.setTranslation = function (vector3) {
  1244. this.m[12] = vector3.x;
  1245. this.m[13] = vector3.y;
  1246. this.m[14] = vector3.z;
  1247. };
  1248. Matrix.prototype.multiply = function (other) {
  1249. var result = new Matrix();
  1250. this.multiplyToRef(other, result);
  1251. return result;
  1252. };
  1253. Matrix.prototype.copyFrom = function (other) {
  1254. for (var index = 0; index < 16; index++) {
  1255. this.m[index] = other.m[index];
  1256. }
  1257. };
  1258. Matrix.prototype.copyToArray = function (array, offset) {
  1259. if (typeof offset === "undefined") { offset = 0; }
  1260. for (var index = 0; index < 16; index++) {
  1261. array[offset + index] = this.m[index];
  1262. }
  1263. };
  1264. Matrix.prototype.multiplyToRef = function (other, result) {
  1265. this.multiplyToArray(other, result.m, 0);
  1266. };
  1267. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1268. var tm0 = this.m[0];
  1269. var tm1 = this.m[1];
  1270. var tm2 = this.m[2];
  1271. var tm3 = this.m[3];
  1272. var tm4 = this.m[4];
  1273. var tm5 = this.m[5];
  1274. var tm6 = this.m[6];
  1275. var tm7 = this.m[7];
  1276. var tm8 = this.m[8];
  1277. var tm9 = this.m[9];
  1278. var tm10 = this.m[10];
  1279. var tm11 = this.m[11];
  1280. var tm12 = this.m[12];
  1281. var tm13 = this.m[13];
  1282. var tm14 = this.m[14];
  1283. var tm15 = this.m[15];
  1284. var om0 = other.m[0];
  1285. var om1 = other.m[1];
  1286. var om2 = other.m[2];
  1287. var om3 = other.m[3];
  1288. var om4 = other.m[4];
  1289. var om5 = other.m[5];
  1290. var om6 = other.m[6];
  1291. var om7 = other.m[7];
  1292. var om8 = other.m[8];
  1293. var om9 = other.m[9];
  1294. var om10 = other.m[10];
  1295. var om11 = other.m[11];
  1296. var om12 = other.m[12];
  1297. var om13 = other.m[13];
  1298. var om14 = other.m[14];
  1299. var om15 = other.m[15];
  1300. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1301. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1302. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1303. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1304. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1305. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1306. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1307. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1308. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1309. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1310. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1311. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1312. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1313. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1314. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1315. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1316. };
  1317. Matrix.prototype.equals = function (value) {
  1318. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1319. };
  1320. Matrix.prototype.clone = function () {
  1321. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1322. };
  1323. Matrix.FromArray = function (array, offset) {
  1324. var result = new Matrix();
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. Matrix.FromArrayToRef(array, offset, result);
  1329. return result;
  1330. };
  1331. Matrix.FromArrayToRef = function (array, offset, result) {
  1332. for (var index = 0; index < 16; index++) {
  1333. result.m[index] = array[index + offset];
  1334. }
  1335. };
  1336. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1337. result.m[0] = initialM11;
  1338. result.m[1] = initialM12;
  1339. result.m[2] = initialM13;
  1340. result.m[3] = initialM14;
  1341. result.m[4] = initialM21;
  1342. result.m[5] = initialM22;
  1343. result.m[6] = initialM23;
  1344. result.m[7] = initialM24;
  1345. result.m[8] = initialM31;
  1346. result.m[9] = initialM32;
  1347. result.m[10] = initialM33;
  1348. result.m[11] = initialM34;
  1349. result.m[12] = initialM41;
  1350. result.m[13] = initialM42;
  1351. result.m[14] = initialM43;
  1352. result.m[15] = initialM44;
  1353. };
  1354. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1355. var result = new Matrix();
  1356. result.m[0] = initialM11;
  1357. result.m[1] = initialM12;
  1358. result.m[2] = initialM13;
  1359. result.m[3] = initialM14;
  1360. result.m[4] = initialM21;
  1361. result.m[5] = initialM22;
  1362. result.m[6] = initialM23;
  1363. result.m[7] = initialM24;
  1364. result.m[8] = initialM31;
  1365. result.m[9] = initialM32;
  1366. result.m[10] = initialM33;
  1367. result.m[11] = initialM34;
  1368. result.m[12] = initialM41;
  1369. result.m[13] = initialM42;
  1370. result.m[14] = initialM43;
  1371. result.m[15] = initialM44;
  1372. return result;
  1373. };
  1374. Matrix.Identity = function () {
  1375. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1376. };
  1377. Matrix.IdentityToRef = function (result) {
  1378. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1379. };
  1380. Matrix.Zero = function () {
  1381. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1382. };
  1383. Matrix.RotationX = function (angle) {
  1384. var result = new Matrix();
  1385. Matrix.RotationXToRef(angle, result);
  1386. return result;
  1387. };
  1388. Matrix.Invert = function (source) {
  1389. var result = new Matrix();
  1390. source.invertToRef(result);
  1391. return result;
  1392. };
  1393. Matrix.RotationXToRef = function (angle, result) {
  1394. var s = Math.sin(angle);
  1395. var c = Math.cos(angle);
  1396. result.m[0] = 1.0;
  1397. result.m[15] = 1.0;
  1398. result.m[5] = c;
  1399. result.m[10] = c;
  1400. result.m[9] = -s;
  1401. result.m[6] = s;
  1402. result.m[1] = 0;
  1403. result.m[2] = 0;
  1404. result.m[3] = 0;
  1405. result.m[4] = 0;
  1406. result.m[7] = 0;
  1407. result.m[8] = 0;
  1408. result.m[11] = 0;
  1409. result.m[12] = 0;
  1410. result.m[13] = 0;
  1411. result.m[14] = 0;
  1412. };
  1413. Matrix.RotationY = function (angle) {
  1414. var result = new Matrix();
  1415. Matrix.RotationYToRef(angle, result);
  1416. return result;
  1417. };
  1418. Matrix.RotationYToRef = function (angle, result) {
  1419. var s = Math.sin(angle);
  1420. var c = Math.cos(angle);
  1421. result.m[5] = 1.0;
  1422. result.m[15] = 1.0;
  1423. result.m[0] = c;
  1424. result.m[2] = -s;
  1425. result.m[8] = s;
  1426. result.m[10] = c;
  1427. result.m[1] = 0;
  1428. result.m[3] = 0;
  1429. result.m[4] = 0;
  1430. result.m[6] = 0;
  1431. result.m[7] = 0;
  1432. result.m[9] = 0;
  1433. result.m[11] = 0;
  1434. result.m[12] = 0;
  1435. result.m[13] = 0;
  1436. result.m[14] = 0;
  1437. };
  1438. Matrix.RotationZ = function (angle) {
  1439. var result = new Matrix();
  1440. Matrix.RotationZToRef(angle, result);
  1441. return result;
  1442. };
  1443. Matrix.RotationZToRef = function (angle, result) {
  1444. var s = Math.sin(angle);
  1445. var c = Math.cos(angle);
  1446. result.m[10] = 1.0;
  1447. result.m[15] = 1.0;
  1448. result.m[0] = c;
  1449. result.m[1] = s;
  1450. result.m[4] = -s;
  1451. result.m[5] = c;
  1452. result.m[2] = 0;
  1453. result.m[3] = 0;
  1454. result.m[6] = 0;
  1455. result.m[7] = 0;
  1456. result.m[8] = 0;
  1457. result.m[9] = 0;
  1458. result.m[11] = 0;
  1459. result.m[12] = 0;
  1460. result.m[13] = 0;
  1461. result.m[14] = 0;
  1462. };
  1463. Matrix.RotationAxis = function (axis, angle) {
  1464. var s = Math.sin(-angle);
  1465. var c = Math.cos(-angle);
  1466. var c1 = 1 - c;
  1467. axis.normalize();
  1468. var result = Matrix.Zero();
  1469. result.m[0] = (axis.x * axis.x) * c1 + c;
  1470. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1471. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1472. result.m[3] = 0.0;
  1473. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1474. result.m[5] = (axis.y * axis.y) * c1 + c;
  1475. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1476. result.m[7] = 0.0;
  1477. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1478. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1479. result.m[10] = (axis.z * axis.z) * c1 + c;
  1480. result.m[11] = 0.0;
  1481. result.m[15] = 1.0;
  1482. return result;
  1483. };
  1484. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1485. var result = new Matrix();
  1486. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1487. return result;
  1488. };
  1489. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1491. this._tempQuaternion.toRotationMatrix(result);
  1492. };
  1493. Matrix.Scaling = function (x, y, z) {
  1494. var result = Matrix.Zero();
  1495. Matrix.ScalingToRef(x, y, z, result);
  1496. return result;
  1497. };
  1498. Matrix.ScalingToRef = function (x, y, z, result) {
  1499. result.m[0] = x;
  1500. result.m[1] = 0;
  1501. result.m[2] = 0;
  1502. result.m[3] = 0;
  1503. result.m[4] = 0;
  1504. result.m[5] = y;
  1505. result.m[6] = 0;
  1506. result.m[7] = 0;
  1507. result.m[8] = 0;
  1508. result.m[9] = 0;
  1509. result.m[10] = z;
  1510. result.m[11] = 0;
  1511. result.m[12] = 0;
  1512. result.m[13] = 0;
  1513. result.m[14] = 0;
  1514. result.m[15] = 1.0;
  1515. };
  1516. Matrix.Translation = function (x, y, z) {
  1517. var result = Matrix.Identity();
  1518. Matrix.TranslationToRef(x, y, z, result);
  1519. return result;
  1520. };
  1521. Matrix.TranslationToRef = function (x, y, z, result) {
  1522. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1523. };
  1524. Matrix.LookAtLH = function (eye, target, up) {
  1525. var result = Matrix.Zero();
  1526. Matrix.LookAtLHToRef(eye, target, up, result);
  1527. return result;
  1528. };
  1529. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1530. target.subtractToRef(eye, this._zAxis);
  1531. this._zAxis.normalize();
  1532. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1533. this._xAxis.normalize();
  1534. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1535. this._yAxis.normalize();
  1536. var ex = -Vector3.Dot(this._xAxis, eye);
  1537. var ey = -Vector3.Dot(this._yAxis, eye);
  1538. var ez = -Vector3.Dot(this._zAxis, eye);
  1539. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1540. };
  1541. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1542. var hw = 2.0 / width;
  1543. var hh = 2.0 / height;
  1544. var id = 1.0 / (zfar - znear);
  1545. var nid = znear / (znear - zfar);
  1546. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1547. };
  1548. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1549. var matrix = Matrix.Zero();
  1550. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1551. return matrix;
  1552. };
  1553. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1554. result.m[0] = 2.0 / (right - left);
  1555. result.m[1] = result.m[2] = result.m[3] = 0;
  1556. result.m[5] = 2.0 / (top - bottom);
  1557. result.m[4] = result.m[6] = result.m[7] = 0;
  1558. result.m[10] = -1.0 / (znear - zfar);
  1559. result.m[8] = result.m[9] = result.m[11] = 0;
  1560. result.m[12] = (left + right) / (left - right);
  1561. result.m[13] = (top + bottom) / (bottom - top);
  1562. result.m[14] = znear / (znear - zfar);
  1563. result.m[15] = 1.0;
  1564. };
  1565. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1566. var matrix = Matrix.Zero();
  1567. matrix.m[0] = (2.0 * znear) / width;
  1568. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1569. matrix.m[5] = (2.0 * znear) / height;
  1570. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1571. matrix.m[10] = -zfar / (znear - zfar);
  1572. matrix.m[8] = matrix.m[9] = 0.0;
  1573. matrix.m[11] = 1.0;
  1574. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1575. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1576. return matrix;
  1577. };
  1578. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1579. var matrix = Matrix.Zero();
  1580. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1581. return matrix;
  1582. };
  1583. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1584. var tan = 1.0 / (Math.tan(fov * 0.5));
  1585. result.m[0] = tan / aspect;
  1586. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1587. result.m[5] = tan;
  1588. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1589. result.m[8] = result.m[9] = 0.0;
  1590. result.m[10] = -zfar / (znear - zfar);
  1591. result.m[11] = 1.0;
  1592. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1593. result.m[14] = (znear * zfar) / (znear - zfar);
  1594. };
  1595. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1596. var cw = viewport.width;
  1597. var ch = viewport.height;
  1598. var cx = viewport.x;
  1599. var cy = viewport.y;
  1600. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1601. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1602. };
  1603. Matrix.Transpose = function (matrix) {
  1604. var result = new Matrix();
  1605. result.m[0] = matrix.m[0];
  1606. result.m[1] = matrix.m[4];
  1607. result.m[2] = matrix.m[8];
  1608. result.m[3] = matrix.m[12];
  1609. result.m[4] = matrix.m[1];
  1610. result.m[5] = matrix.m[5];
  1611. result.m[6] = matrix.m[9];
  1612. result.m[7] = matrix.m[13];
  1613. result.m[8] = matrix.m[2];
  1614. result.m[9] = matrix.m[6];
  1615. result.m[10] = matrix.m[10];
  1616. result.m[11] = matrix.m[14];
  1617. result.m[12] = matrix.m[3];
  1618. result.m[13] = matrix.m[7];
  1619. result.m[14] = matrix.m[11];
  1620. result.m[15] = matrix.m[15];
  1621. return result;
  1622. };
  1623. Matrix.Reflection = function (plane) {
  1624. var matrix = new Matrix();
  1625. Matrix.ReflectionToRef(plane, matrix);
  1626. return matrix;
  1627. };
  1628. Matrix.ReflectionToRef = function (plane, result) {
  1629. plane.normalize();
  1630. var x = plane.normal.x;
  1631. var y = plane.normal.y;
  1632. var z = plane.normal.z;
  1633. var temp = -2 * x;
  1634. var temp2 = -2 * y;
  1635. var temp3 = -2 * z;
  1636. result.m[0] = (temp * x) + 1;
  1637. result.m[1] = temp2 * x;
  1638. result.m[2] = temp3 * x;
  1639. result.m[3] = 0.0;
  1640. result.m[4] = temp * y;
  1641. result.m[5] = (temp2 * y) + 1;
  1642. result.m[6] = temp3 * y;
  1643. result.m[7] = 0.0;
  1644. result.m[8] = temp * z;
  1645. result.m[9] = temp2 * z;
  1646. result.m[10] = (temp3 * z) + 1;
  1647. result.m[11] = 0.0;
  1648. result.m[12] = temp * plane.d;
  1649. result.m[13] = temp2 * plane.d;
  1650. result.m[14] = temp3 * plane.d;
  1651. result.m[15] = 1.0;
  1652. };
  1653. Matrix._tempQuaternion = new Quaternion();
  1654. Matrix._xAxis = Vector3.Zero();
  1655. Matrix._yAxis = Vector3.Zero();
  1656. Matrix._zAxis = Vector3.Zero();
  1657. return Matrix;
  1658. })();
  1659. BABYLON.Matrix = Matrix;
  1660. var Plane = (function () {
  1661. function Plane(a, b, c, d) {
  1662. this.normal = new Vector3(a, b, c);
  1663. this.d = d;
  1664. }
  1665. Plane.prototype.asArray = function () {
  1666. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1667. };
  1668. Plane.prototype.clone = function () {
  1669. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1670. };
  1671. Plane.prototype.normalize = function () {
  1672. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1673. var magnitude = 0;
  1674. if (norm != 0) {
  1675. magnitude = 1.0 / norm;
  1676. }
  1677. this.normal.x *= magnitude;
  1678. this.normal.y *= magnitude;
  1679. this.normal.z *= magnitude;
  1680. this.d *= magnitude;
  1681. };
  1682. Plane.prototype.transform = function (transformation) {
  1683. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1684. var x = this.normal.x;
  1685. var y = this.normal.y;
  1686. var z = this.normal.z;
  1687. var d = this.d;
  1688. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1689. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1690. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1691. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1692. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1693. };
  1694. Plane.prototype.dotCoordinate = function (point) {
  1695. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1696. };
  1697. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1698. var x1 = point2.x - point1.x;
  1699. var y1 = point2.y - point1.y;
  1700. var z1 = point2.z - point1.z;
  1701. var x2 = point3.x - point1.x;
  1702. var y2 = point3.y - point1.y;
  1703. var z2 = point3.z - point1.z;
  1704. var yz = (y1 * z2) - (z1 * y2);
  1705. var xz = (z1 * x2) - (x1 * z2);
  1706. var xy = (x1 * y2) - (y1 * x2);
  1707. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1708. var invPyth;
  1709. if (pyth != 0) {
  1710. invPyth = 1.0 / pyth;
  1711. } else {
  1712. invPyth = 0;
  1713. }
  1714. this.normal.x = yz * invPyth;
  1715. this.normal.y = xz * invPyth;
  1716. this.normal.z = xy * invPyth;
  1717. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1718. };
  1719. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1720. var dot = Vector3.Dot(this.normal, direction);
  1721. return (dot <= epsilon);
  1722. };
  1723. Plane.prototype.signedDistanceTo = function (point) {
  1724. return Vector3.Dot(point, this.normal) + this.d;
  1725. };
  1726. Plane.FromArray = function (array) {
  1727. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1728. };
  1729. Plane.FromPoints = function (point1, point2, point3) {
  1730. var result = new BABYLON.Plane(0, 0, 0, 0);
  1731. result.copyFromPoints(point1, point2, point3);
  1732. return result;
  1733. };
  1734. Plane.FromPositionAndNormal = function (origin, normal) {
  1735. var result = new BABYLON.Plane(0, 0, 0, 0);
  1736. normal.normalize();
  1737. result.normal = normal;
  1738. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1739. return result;
  1740. };
  1741. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1742. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1743. return Vector3.Dot(point, normal) + d;
  1744. };
  1745. return Plane;
  1746. })();
  1747. BABYLON.Plane = Plane;
  1748. var Viewport = (function () {
  1749. function Viewport(x, y, width, height) {
  1750. this.x = x;
  1751. this.y = y;
  1752. this.width = width;
  1753. this.height = height;
  1754. }
  1755. Viewport.prototype.toGlobal = function (engine) {
  1756. var width = engine.getRenderWidth();
  1757. var height = engine.getRenderHeight();
  1758. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1759. };
  1760. return Viewport;
  1761. })();
  1762. BABYLON.Viewport = Viewport;
  1763. var Frustum = (function () {
  1764. function Frustum() {
  1765. }
  1766. Frustum.GetPlanes = function (transform) {
  1767. var frustumPlanes = [];
  1768. for (var index = 0; index < 6; index++) {
  1769. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1770. }
  1771. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1772. return frustumPlanes;
  1773. };
  1774. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1775. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1776. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1777. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1778. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1779. frustumPlanes[0].normalize();
  1780. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1781. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1782. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1783. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1784. frustumPlanes[1].normalize();
  1785. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1786. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1787. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1788. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1789. frustumPlanes[2].normalize();
  1790. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1791. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1792. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1793. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1794. frustumPlanes[3].normalize();
  1795. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1796. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1797. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1798. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1799. frustumPlanes[4].normalize();
  1800. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1801. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1802. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1803. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1804. frustumPlanes[5].normalize();
  1805. };
  1806. return Frustum;
  1807. })();
  1808. BABYLON.Frustum = Frustum;
  1809. var Ray = (function () {
  1810. function Ray(origin, direction, length) {
  1811. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1812. this.origin = origin;
  1813. this.direction = direction;
  1814. this.length = length;
  1815. }
  1816. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1817. var d = 0.0;
  1818. var maxValue = Number.MAX_VALUE;
  1819. if (Math.abs(this.direction.x) < 0.0000001) {
  1820. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1821. return false;
  1822. }
  1823. } else {
  1824. var inv = 1.0 / this.direction.x;
  1825. var min = (minimum.x - this.origin.x) * inv;
  1826. var max = (maximum.x - this.origin.x) * inv;
  1827. if (max == -Infinity) {
  1828. max = Infinity;
  1829. }
  1830. if (min > max) {
  1831. var temp = min;
  1832. min = max;
  1833. max = temp;
  1834. }
  1835. d = Math.max(min, d);
  1836. maxValue = Math.min(max, maxValue);
  1837. if (d > maxValue) {
  1838. return false;
  1839. }
  1840. }
  1841. if (Math.abs(this.direction.y) < 0.0000001) {
  1842. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1843. return false;
  1844. }
  1845. } else {
  1846. inv = 1.0 / this.direction.y;
  1847. min = (minimum.y - this.origin.y) * inv;
  1848. max = (maximum.y - this.origin.y) * inv;
  1849. if (max == -Infinity) {
  1850. max = Infinity;
  1851. }
  1852. if (min > max) {
  1853. temp = min;
  1854. min = max;
  1855. max = temp;
  1856. }
  1857. d = Math.max(min, d);
  1858. maxValue = Math.min(max, maxValue);
  1859. if (d > maxValue) {
  1860. return false;
  1861. }
  1862. }
  1863. if (Math.abs(this.direction.z) < 0.0000001) {
  1864. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1865. return false;
  1866. }
  1867. } else {
  1868. inv = 1.0 / this.direction.z;
  1869. min = (minimum.z - this.origin.z) * inv;
  1870. max = (maximum.z - this.origin.z) * inv;
  1871. if (max == -Infinity) {
  1872. max = Infinity;
  1873. }
  1874. if (min > max) {
  1875. temp = min;
  1876. min = max;
  1877. max = temp;
  1878. }
  1879. d = Math.max(min, d);
  1880. maxValue = Math.min(max, maxValue);
  1881. if (d > maxValue) {
  1882. return false;
  1883. }
  1884. }
  1885. return true;
  1886. };
  1887. Ray.prototype.intersectsBox = function (box) {
  1888. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1889. };
  1890. Ray.prototype.intersectsSphere = function (sphere) {
  1891. var x = sphere.center.x - this.origin.x;
  1892. var y = sphere.center.y - this.origin.y;
  1893. var z = sphere.center.z - this.origin.z;
  1894. var pyth = (x * x) + (y * y) + (z * z);
  1895. var rr = sphere.radius * sphere.radius;
  1896. if (pyth <= rr) {
  1897. return true;
  1898. }
  1899. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1900. if (dot < 0.0) {
  1901. return false;
  1902. }
  1903. var temp = pyth - (dot * dot);
  1904. return temp <= rr;
  1905. };
  1906. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1907. if (!this._edge1) {
  1908. this._edge1 = BABYLON.Vector3.Zero();
  1909. this._edge2 = BABYLON.Vector3.Zero();
  1910. this._pvec = BABYLON.Vector3.Zero();
  1911. this._tvec = BABYLON.Vector3.Zero();
  1912. this._qvec = BABYLON.Vector3.Zero();
  1913. }
  1914. vertex1.subtractToRef(vertex0, this._edge1);
  1915. vertex2.subtractToRef(vertex0, this._edge2);
  1916. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1917. var det = Vector3.Dot(this._edge1, this._pvec);
  1918. if (det === 0) {
  1919. return null;
  1920. }
  1921. var invdet = 1 / det;
  1922. this.origin.subtractToRef(vertex0, this._tvec);
  1923. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1924. if (bu < 0 || bu > 1.0) {
  1925. return null;
  1926. }
  1927. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1928. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1929. if (bv < 0 || bu + bv > 1.0) {
  1930. return null;
  1931. }
  1932. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1933. if (distance > this.length) {
  1934. return null;
  1935. }
  1936. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1937. };
  1938. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1939. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1940. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1941. var direction = end.subtract(start);
  1942. direction.normalize();
  1943. return new Ray(start, direction);
  1944. };
  1945. /**
  1946. * 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
  1947. * transformed to the given world matrix.
  1948. * @param origin The origin point
  1949. * @param end The end point
  1950. * @param world a matrix to transform the ray to. Default is the identity matrix.
  1951. */
  1952. Ray.CreateNewFromTo = function (origin, end, world) {
  1953. if (typeof world === "undefined") { world = BABYLON.Matrix.Identity(); }
  1954. var direction = end.subtract(origin);
  1955. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  1956. direction.normalize();
  1957. return Ray.Transform(new Ray(origin, direction, length), world);
  1958. };
  1959. Ray.Transform = function (ray, matrix) {
  1960. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  1961. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  1962. return new Ray(newOrigin, newDirection, ray.length);
  1963. };
  1964. return Ray;
  1965. })();
  1966. BABYLON.Ray = Ray;
  1967. (function (Space) {
  1968. Space[Space["LOCAL"] = 0] = "LOCAL";
  1969. Space[Space["WORLD"] = 1] = "WORLD";
  1970. })(BABYLON.Space || (BABYLON.Space = {}));
  1971. var Space = BABYLON.Space;
  1972. var Axis = (function () {
  1973. function Axis() {
  1974. }
  1975. Axis.X = new BABYLON.Vector3(1, 0, 0);
  1976. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  1977. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  1978. return Axis;
  1979. })();
  1980. BABYLON.Axis = Axis;
  1981. ;
  1982. var BezierCurve = (function () {
  1983. function BezierCurve() {
  1984. }
  1985. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  1986. var f0 = 1 - 3 * x2 + 3 * x1;
  1987. var f1 = 3 * x2 - 6 * x1;
  1988. var f2 = 3 * x1;
  1989. var refinedT = t;
  1990. for (var i = 0; i < 5; i++) {
  1991. var refinedT2 = refinedT * refinedT;
  1992. var refinedT3 = refinedT2 * refinedT;
  1993. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  1994. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  1995. refinedT -= (x - t) * slope;
  1996. refinedT = Math.min(1, Math.max(0, refinedT));
  1997. }
  1998. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  1999. };
  2000. return BezierCurve;
  2001. })();
  2002. BABYLON.BezierCurve = BezierCurve;
  2003. })(BABYLON || (BABYLON = {}));
  2004. var BABYLON;
  2005. (function (BABYLON) {
  2006. var screenshotCanvas;
  2007. var fpsRange = 60;
  2008. var previousFramesDuration = [];
  2009. var fps = 60;
  2010. var deltaTime = 0;
  2011. var cloneValue = function (source, destinationObject) {
  2012. if (!source)
  2013. return null;
  2014. if (source instanceof BABYLON.Mesh) {
  2015. return null;
  2016. }
  2017. if (source instanceof BABYLON.SubMesh) {
  2018. return source.clone(destinationObject);
  2019. } else if (source.clone) {
  2020. return source.clone();
  2021. }
  2022. return null;
  2023. };
  2024. var Tools = (function () {
  2025. function Tools() {
  2026. }
  2027. Tools.GetFilename = function (path) {
  2028. var index = path.lastIndexOf("/");
  2029. if (index < 0)
  2030. return path;
  2031. return path.substring(index + 1);
  2032. };
  2033. Tools.GetDOMTextContent = function (element) {
  2034. var result = "";
  2035. var child = element.firstChild;
  2036. while (child) {
  2037. if (child.nodeType == 3) {
  2038. result += child.textContent;
  2039. }
  2040. child = child.nextSibling;
  2041. }
  2042. return result;
  2043. };
  2044. Tools.ToDegrees = function (angle) {
  2045. return angle * 180 / Math.PI;
  2046. };
  2047. Tools.ToRadians = function (angle) {
  2048. return angle * Math.PI / 180;
  2049. };
  2050. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2051. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2052. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2053. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2054. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2055. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2056. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2057. }
  2058. return {
  2059. minimum: minimum,
  2060. maximum: maximum
  2061. };
  2062. };
  2063. Tools.ExtractMinAndMax = function (positions, start, count) {
  2064. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2065. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2066. for (var index = start; index < start + count; index++) {
  2067. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2068. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2069. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2070. }
  2071. return {
  2072. minimum: minimum,
  2073. maximum: maximum
  2074. };
  2075. };
  2076. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2077. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2078. return undefined;
  2079. return Array.isArray(obj) ? obj : [obj];
  2080. };
  2081. Tools.GetPointerPrefix = function () {
  2082. var eventPrefix = "pointer";
  2083. if (!navigator.pointerEnabled) {
  2084. eventPrefix = "mouse";
  2085. }
  2086. return eventPrefix;
  2087. };
  2088. Tools.QueueNewFrame = function (func) {
  2089. if (window.requestAnimationFrame)
  2090. window.requestAnimationFrame(func);
  2091. else if (window.msRequestAnimationFrame)
  2092. window.msRequestAnimationFrame(func);
  2093. else if (window.webkitRequestAnimationFrame)
  2094. window.webkitRequestAnimationFrame(func);
  2095. else if (window.mozRequestAnimationFrame)
  2096. window.mozRequestAnimationFrame(func);
  2097. else if (window.oRequestAnimationFrame)
  2098. window.oRequestAnimationFrame(func);
  2099. else {
  2100. window.setTimeout(func, 16);
  2101. }
  2102. };
  2103. Tools.RequestFullscreen = function (element) {
  2104. if (element.requestFullscreen)
  2105. element.requestFullscreen();
  2106. else if (element.msRequestFullscreen)
  2107. element.msRequestFullscreen();
  2108. else if (element.webkitRequestFullscreen)
  2109. element.webkitRequestFullscreen();
  2110. else if (element.mozRequestFullScreen)
  2111. element.mozRequestFullScreen();
  2112. };
  2113. Tools.ExitFullscreen = function () {
  2114. if (document.exitFullscreen) {
  2115. document.exitFullscreen();
  2116. } else if (document.mozCancelFullScreen) {
  2117. document.mozCancelFullScreen();
  2118. } else if (document.webkitCancelFullScreen) {
  2119. document.webkitCancelFullScreen();
  2120. } else if (document.msCancelFullScreen) {
  2121. document.msCancelFullScreen();
  2122. }
  2123. };
  2124. Tools.CleanUrl = function (url) {
  2125. url = url.replace(/#/mg, "%23");
  2126. return url;
  2127. };
  2128. Tools.LoadImage = function (url, onload, onerror, database) {
  2129. url = Tools.CleanUrl(url);
  2130. var img = new Image();
  2131. if (url.substr(0, 5) != "data:")
  2132. img.crossOrigin = 'anonymous';
  2133. img.onload = function () {
  2134. onload(img);
  2135. };
  2136. img.onerror = function (err) {
  2137. onerror(img, err);
  2138. };
  2139. var noIndexedDB = function () {
  2140. img.src = url;
  2141. };
  2142. var loadFromIndexedDB = function () {
  2143. database.loadImageFromDB(url, img);
  2144. };
  2145. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2146. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2147. } else {
  2148. if (url.indexOf("file:") === -1) {
  2149. noIndexedDB();
  2150. } else {
  2151. try {
  2152. var textureName = url.substring(5);
  2153. var blobURL;
  2154. try {
  2155. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2156. } catch (ex) {
  2157. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2158. }
  2159. img.src = blobURL;
  2160. } catch (e) {
  2161. Tools.Log("Error while trying to load texture: " + textureName);
  2162. img.src = null;
  2163. }
  2164. }
  2165. }
  2166. return img;
  2167. };
  2168. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2169. url = Tools.CleanUrl(url);
  2170. var noIndexedDB = function () {
  2171. var request = new XMLHttpRequest();
  2172. var loadUrl = Tools.BaseUrl + url;
  2173. request.open('GET', loadUrl, true);
  2174. if (useArrayBuffer) {
  2175. request.responseType = "arraybuffer";
  2176. }
  2177. request.onprogress = progressCallBack;
  2178. request.onreadystatechange = function () {
  2179. if (request.readyState == 4) {
  2180. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2181. callback(!useArrayBuffer ? request.responseText : request.response);
  2182. } else {
  2183. if (onError) {
  2184. onError();
  2185. } else {
  2186. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2187. }
  2188. }
  2189. }
  2190. };
  2191. request.send(null);
  2192. };
  2193. var loadFromIndexedDB = function () {
  2194. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2195. };
  2196. if (url.indexOf("file:") !== -1) {
  2197. var fileName = url.substring(5);
  2198. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2199. } else {
  2200. if (database && database.enableSceneOffline) {
  2201. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2202. } else {
  2203. noIndexedDB();
  2204. }
  2205. }
  2206. };
  2207. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2208. var reader = new FileReader();
  2209. reader.onload = function (e) {
  2210. callback(e.target.result);
  2211. };
  2212. reader.onprogress = progressCallback;
  2213. reader.readAsDataURL(fileToLoad);
  2214. };
  2215. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2216. var reader = new FileReader();
  2217. reader.onload = function (e) {
  2218. callback(e.target.result);
  2219. };
  2220. reader.onprogress = progressCallBack;
  2221. if (!useArrayBuffer) {
  2222. reader.readAsText(fileToLoad);
  2223. } else {
  2224. reader.readAsArrayBuffer(fileToLoad);
  2225. }
  2226. };
  2227. Tools.Clamp = function (value, min, max) {
  2228. if (typeof min === "undefined") { min = 0; }
  2229. if (typeof max === "undefined") { max = 1; }
  2230. return Math.min(max, Math.max(min, value));
  2231. };
  2232. Tools.Format = function (value, decimals) {
  2233. if (typeof decimals === "undefined") { decimals = 2; }
  2234. return value.toFixed(decimals);
  2235. };
  2236. Tools.CheckExtends = function (v, min, max) {
  2237. if (v.x < min.x)
  2238. min.x = v.x;
  2239. if (v.y < min.y)
  2240. min.y = v.y;
  2241. if (v.z < min.z)
  2242. min.z = v.z;
  2243. if (v.x > max.x)
  2244. max.x = v.x;
  2245. if (v.y > max.y)
  2246. max.y = v.y;
  2247. if (v.z > max.z)
  2248. max.z = v.z;
  2249. };
  2250. Tools.WithinEpsilon = function (a, b) {
  2251. var num = a - b;
  2252. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2253. };
  2254. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2255. for (var prop in source) {
  2256. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2257. continue;
  2258. }
  2259. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2260. continue;
  2261. }
  2262. var sourceValue = source[prop];
  2263. var typeOfSourceValue = typeof sourceValue;
  2264. if (typeOfSourceValue == "function") {
  2265. continue;
  2266. }
  2267. if (typeOfSourceValue == "object") {
  2268. if (sourceValue instanceof Array) {
  2269. destination[prop] = [];
  2270. if (sourceValue.length > 0) {
  2271. if (typeof sourceValue[0] == "object") {
  2272. for (var index = 0; index < sourceValue.length; index++) {
  2273. var clonedValue = cloneValue(sourceValue[index], destination);
  2274. if (destination[prop].indexOf(clonedValue) === -1) {
  2275. destination[prop].push(clonedValue);
  2276. }
  2277. }
  2278. } else {
  2279. destination[prop] = sourceValue.slice(0);
  2280. }
  2281. }
  2282. } else {
  2283. destination[prop] = cloneValue(sourceValue, destination);
  2284. }
  2285. } else {
  2286. destination[prop] = sourceValue;
  2287. }
  2288. }
  2289. };
  2290. Tools.IsEmpty = function (obj) {
  2291. for (var i in obj) {
  2292. return false;
  2293. }
  2294. return true;
  2295. };
  2296. Tools.RegisterTopRootEvents = function (events) {
  2297. for (var index = 0; index < events.length; index++) {
  2298. var event = events[index];
  2299. window.addEventListener(event.name, event.handler, false);
  2300. try {
  2301. if (window.parent) {
  2302. window.parent.addEventListener(event.name, event.handler, false);
  2303. }
  2304. } catch (e) {
  2305. }
  2306. }
  2307. };
  2308. Tools.UnregisterTopRootEvents = function (events) {
  2309. for (var index = 0; index < events.length; index++) {
  2310. var event = events[index];
  2311. window.removeEventListener(event.name, event.handler);
  2312. try {
  2313. if (window.parent) {
  2314. window.parent.removeEventListener(event.name, event.handler);
  2315. }
  2316. } catch (e) {
  2317. }
  2318. }
  2319. };
  2320. Tools.GetFps = function () {
  2321. return fps;
  2322. };
  2323. Tools.GetDeltaTime = function () {
  2324. return deltaTime;
  2325. };
  2326. Tools._MeasureFps = function () {
  2327. previousFramesDuration.push(Tools.Now);
  2328. var length = previousFramesDuration.length;
  2329. if (length >= 2) {
  2330. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  2331. }
  2332. if (length >= fpsRange) {
  2333. if (length > fpsRange) {
  2334. previousFramesDuration.splice(0, 1);
  2335. length = previousFramesDuration.length;
  2336. }
  2337. var sum = 0;
  2338. for (var id = 0; id < length - 1; id++) {
  2339. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  2340. }
  2341. fps = 1000.0 / (sum / (length - 1));
  2342. }
  2343. };
  2344. Tools.CreateScreenshot = function (engine, camera, size) {
  2345. var width;
  2346. var height;
  2347. var scene = camera.getScene();
  2348. var previousCamera = null;
  2349. if (scene.activeCamera !== camera) {
  2350. previousCamera = scene.activeCamera;
  2351. scene.activeCamera = camera;
  2352. }
  2353. if (size.precision) {
  2354. width = Math.round(engine.getRenderWidth() * size.precision);
  2355. height = Math.round(width / engine.getAspectRatio(camera));
  2356. size = { width: width, height: height };
  2357. } else if (size.width && size.height) {
  2358. width = size.width;
  2359. height = size.height;
  2360. } else if (size.width && !size.height) {
  2361. width = size.width;
  2362. height = Math.round(width / engine.getAspectRatio(camera));
  2363. size = { width: width, height: height };
  2364. } else if (size.height && !size.width) {
  2365. height = size.height;
  2366. width = Math.round(height * engine.getAspectRatio(camera));
  2367. size = { width: width, height: height };
  2368. } else if (!isNaN(size)) {
  2369. height = size;
  2370. width = size;
  2371. } else {
  2372. Tools.Error("Invalid 'size' parameter !");
  2373. return;
  2374. }
  2375. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2376. texture.renderList = engine.scenes[0].meshes;
  2377. texture.onAfterRender = function () {
  2378. var numberOfChannelsByLine = width * 4;
  2379. var halfHeight = height / 2;
  2380. var data = engine.readPixels(0, 0, width, height);
  2381. for (var i = 0; i < halfHeight; i++) {
  2382. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2383. var currentCell = j + i * numberOfChannelsByLine;
  2384. var targetLine = height - i - 1;
  2385. var targetCell = j + targetLine * numberOfChannelsByLine;
  2386. var temp = data[currentCell];
  2387. data[currentCell] = data[targetCell];
  2388. data[targetCell] = temp;
  2389. }
  2390. }
  2391. if (!screenshotCanvas) {
  2392. screenshotCanvas = document.createElement('canvas');
  2393. }
  2394. screenshotCanvas.width = width;
  2395. screenshotCanvas.height = height;
  2396. var context = screenshotCanvas.getContext('2d');
  2397. var imageData = context.createImageData(width, height);
  2398. imageData.data.set(data);
  2399. context.putImageData(imageData, 0, 0);
  2400. var base64Image = screenshotCanvas.toDataURL();
  2401. if (("download" in document.createElement("a"))) {
  2402. var a = window.document.createElement("a");
  2403. a.href = base64Image;
  2404. var date = new Date();
  2405. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2406. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2407. window.document.body.appendChild(a);
  2408. a.addEventListener("click", function () {
  2409. a.parentElement.removeChild(a);
  2410. });
  2411. a.click();
  2412. } else {
  2413. var newWindow = window.open("");
  2414. var img = newWindow.document.createElement("img");
  2415. img.src = base64Image;
  2416. newWindow.document.body.appendChild(img);
  2417. }
  2418. };
  2419. texture.render(true);
  2420. texture.dispose();
  2421. if (previousCamera) {
  2422. scene.activeCamera = previousCamera;
  2423. }
  2424. };
  2425. Tools.ValidateXHRData = function (xhr, dataType) {
  2426. if (typeof dataType === "undefined") { dataType = 7; }
  2427. try {
  2428. if (dataType & 1) {
  2429. if (xhr.responseText && xhr.responseText.length > 0) {
  2430. return true;
  2431. } else if (dataType === 1) {
  2432. return false;
  2433. }
  2434. }
  2435. if (dataType & 2) {
  2436. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2437. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2438. return true;
  2439. } else if (dataType === 2) {
  2440. return false;
  2441. }
  2442. }
  2443. if (dataType & 4) {
  2444. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2445. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2446. return true;
  2447. } else {
  2448. return false;
  2449. }
  2450. }
  2451. } catch (e) {
  2452. }
  2453. return false;
  2454. };
  2455. Object.defineProperty(Tools, "NoneLogLevel", {
  2456. get: function () {
  2457. return Tools._NoneLogLevel;
  2458. },
  2459. enumerable: true,
  2460. configurable: true
  2461. });
  2462. Object.defineProperty(Tools, "MessageLogLevel", {
  2463. get: function () {
  2464. return Tools._MessageLogLevel;
  2465. },
  2466. enumerable: true,
  2467. configurable: true
  2468. });
  2469. Object.defineProperty(Tools, "WarningLogLevel", {
  2470. get: function () {
  2471. return Tools._WarningLogLevel;
  2472. },
  2473. enumerable: true,
  2474. configurable: true
  2475. });
  2476. Object.defineProperty(Tools, "ErrorLogLevel", {
  2477. get: function () {
  2478. return Tools._ErrorLogLevel;
  2479. },
  2480. enumerable: true,
  2481. configurable: true
  2482. });
  2483. Object.defineProperty(Tools, "AllLogLevel", {
  2484. get: function () {
  2485. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2486. },
  2487. enumerable: true,
  2488. configurable: true
  2489. });
  2490. Tools._AddLogEntry = function (entry) {
  2491. Tools._LogCache = entry + Tools._LogCache;
  2492. if (Tools.OnNewCacheEntry) {
  2493. Tools.OnNewCacheEntry(entry);
  2494. }
  2495. };
  2496. Tools._FormatMessage = function (message) {
  2497. var padStr = function (i) {
  2498. return (i < 10) ? "0" + i : "" + i;
  2499. };
  2500. var date = new Date();
  2501. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2502. };
  2503. Tools._LogDisabled = function (message) {
  2504. };
  2505. Tools._LogEnabled = function (message) {
  2506. var formattedMessage = Tools._FormatMessage(message);
  2507. console.log("BJS - " + formattedMessage);
  2508. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2509. Tools._AddLogEntry(entry);
  2510. };
  2511. Tools._WarnDisabled = function (message) {
  2512. };
  2513. Tools._WarnEnabled = function (message) {
  2514. var formattedMessage = Tools._FormatMessage(message);
  2515. console.warn("BJS - " + formattedMessage);
  2516. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2517. Tools._AddLogEntry(entry);
  2518. };
  2519. Tools._ErrorDisabled = function (message) {
  2520. };
  2521. Tools._ErrorEnabled = function (message) {
  2522. var formattedMessage = Tools._FormatMessage(message);
  2523. console.error("BJS - " + formattedMessage);
  2524. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2525. Tools._AddLogEntry(entry);
  2526. };
  2527. Object.defineProperty(Tools, "LogCache", {
  2528. get: function () {
  2529. return Tools._LogCache;
  2530. },
  2531. enumerable: true,
  2532. configurable: true
  2533. });
  2534. Object.defineProperty(Tools, "LogLevels", {
  2535. set: function (level) {
  2536. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2537. Tools.Log = Tools._LogEnabled;
  2538. } else {
  2539. Tools.Log = Tools._LogDisabled;
  2540. }
  2541. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2542. Tools.Warn = Tools._WarnEnabled;
  2543. } else {
  2544. Tools.Warn = Tools._WarnDisabled;
  2545. }
  2546. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2547. Tools.Error = Tools._ErrorEnabled;
  2548. } else {
  2549. Tools.Error = Tools._ErrorDisabled;
  2550. }
  2551. },
  2552. enumerable: true,
  2553. configurable: true
  2554. });
  2555. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2556. get: function () {
  2557. return Tools._PerformanceNoneLogLevel;
  2558. },
  2559. enumerable: true,
  2560. configurable: true
  2561. });
  2562. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2563. get: function () {
  2564. return Tools._PerformanceUserMarkLogLevel;
  2565. },
  2566. enumerable: true,
  2567. configurable: true
  2568. });
  2569. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2570. get: function () {
  2571. return Tools._PerformanceConsoleLogLevel;
  2572. },
  2573. enumerable: true,
  2574. configurable: true
  2575. });
  2576. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2577. set: function (level) {
  2578. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2579. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2580. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2581. return;
  2582. }
  2583. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2584. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2585. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2586. return;
  2587. }
  2588. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2589. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2590. },
  2591. enumerable: true,
  2592. configurable: true
  2593. });
  2594. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2595. };
  2596. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2597. };
  2598. Tools._StartUserMark = function (counterName, condition) {
  2599. if (typeof condition === "undefined") { condition = true; }
  2600. if (!condition || !Tools._performance.mark) {
  2601. return;
  2602. }
  2603. Tools._performance.mark(counterName + "-Begin");
  2604. };
  2605. Tools._EndUserMark = function (counterName, condition) {
  2606. if (typeof condition === "undefined") { condition = true; }
  2607. if (!condition || !Tools._performance.mark) {
  2608. return;
  2609. }
  2610. Tools._performance.mark(counterName + "-End");
  2611. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2612. };
  2613. Tools._StartPerformanceConsole = function (counterName, condition) {
  2614. if (typeof condition === "undefined") { condition = true; }
  2615. if (!condition) {
  2616. return;
  2617. }
  2618. Tools._StartUserMark(counterName, condition);
  2619. if (console.time) {
  2620. console.time(counterName);
  2621. }
  2622. };
  2623. Tools._EndPerformanceConsole = function (counterName, condition) {
  2624. if (typeof condition === "undefined") { condition = true; }
  2625. if (!condition) {
  2626. return;
  2627. }
  2628. Tools._EndUserMark(counterName, condition);
  2629. if (console.time) {
  2630. console.timeEnd(counterName);
  2631. }
  2632. };
  2633. Object.defineProperty(Tools, "Now", {
  2634. get: function () {
  2635. if (window.performance && window.performance.now) {
  2636. return window.performance.now();
  2637. }
  2638. return new Date().getTime();
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Tools.BaseUrl = "";
  2644. Tools.GetExponantOfTwo = function (value, max) {
  2645. var count = 1;
  2646. do {
  2647. count *= 2;
  2648. } while(count < value);
  2649. if (count > max)
  2650. count = max;
  2651. return count;
  2652. };
  2653. Tools._NoneLogLevel = 0;
  2654. Tools._MessageLogLevel = 1;
  2655. Tools._WarningLogLevel = 2;
  2656. Tools._ErrorLogLevel = 4;
  2657. Tools._LogCache = "";
  2658. Tools.Log = Tools._LogEnabled;
  2659. Tools.Warn = Tools._WarnEnabled;
  2660. Tools.Error = Tools._ErrorEnabled;
  2661. Tools._PerformanceNoneLogLevel = 0;
  2662. Tools._PerformanceUserMarkLogLevel = 1;
  2663. Tools._PerformanceConsoleLogLevel = 2;
  2664. Tools._performance = window.performance;
  2665. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2666. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2667. return Tools;
  2668. })();
  2669. BABYLON.Tools = Tools;
  2670. })(BABYLON || (BABYLON = {}));
  2671. var BABYLON;
  2672. (function (BABYLON) {
  2673. var _DepthCullingState = (function () {
  2674. function _DepthCullingState() {
  2675. this._isDepthTestDirty = false;
  2676. this._isDepthMaskDirty = false;
  2677. this._isDepthFuncDirty = false;
  2678. this._isCullFaceDirty = false;
  2679. this._isCullDirty = false;
  2680. }
  2681. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2682. get: function () {
  2683. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2684. },
  2685. enumerable: true,
  2686. configurable: true
  2687. });
  2688. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2689. get: function () {
  2690. return this._cullFace;
  2691. },
  2692. set: function (value) {
  2693. if (this._cullFace === value) {
  2694. return;
  2695. }
  2696. this._cullFace = value;
  2697. this._isCullFaceDirty = true;
  2698. },
  2699. enumerable: true,
  2700. configurable: true
  2701. });
  2702. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2703. get: function () {
  2704. return this._cull;
  2705. },
  2706. set: function (value) {
  2707. if (this._cull === value) {
  2708. return;
  2709. }
  2710. this._cull = value;
  2711. this._isCullDirty = true;
  2712. },
  2713. enumerable: true,
  2714. configurable: true
  2715. });
  2716. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2717. get: function () {
  2718. return this._depthFunc;
  2719. },
  2720. set: function (value) {
  2721. if (this._depthFunc === value) {
  2722. return;
  2723. }
  2724. this._depthFunc = value;
  2725. this._isDepthFuncDirty = true;
  2726. },
  2727. enumerable: true,
  2728. configurable: true
  2729. });
  2730. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2731. get: function () {
  2732. return this._depthMask;
  2733. },
  2734. set: function (value) {
  2735. if (this._depthMask === value) {
  2736. return;
  2737. }
  2738. this._depthMask = value;
  2739. this._isDepthMaskDirty = true;
  2740. },
  2741. enumerable: true,
  2742. configurable: true
  2743. });
  2744. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2745. get: function () {
  2746. return this._depthTest;
  2747. },
  2748. set: function (value) {
  2749. if (this._depthTest === value) {
  2750. return;
  2751. }
  2752. this._depthTest = value;
  2753. this._isDepthTestDirty = true;
  2754. },
  2755. enumerable: true,
  2756. configurable: true
  2757. });
  2758. _DepthCullingState.prototype.reset = function () {
  2759. this._depthMask = true;
  2760. this._depthTest = true;
  2761. this._depthFunc = null;
  2762. this._cull = null;
  2763. this._cullFace = null;
  2764. this._isDepthTestDirty = true;
  2765. this._isDepthMaskDirty = true;
  2766. this._isDepthFuncDirty = false;
  2767. this._isCullFaceDirty = false;
  2768. this._isCullDirty = false;
  2769. };
  2770. _DepthCullingState.prototype.apply = function (gl) {
  2771. if (!this.isDirty) {
  2772. return;
  2773. }
  2774. if (this._isCullDirty) {
  2775. if (this.cull === true) {
  2776. gl.enable(gl.CULL_FACE);
  2777. } else if (this.cull === false) {
  2778. gl.disable(gl.CULL_FACE);
  2779. }
  2780. this._isCullDirty = false;
  2781. }
  2782. if (this._isCullFaceDirty) {
  2783. gl.cullFace(this.cullFace);
  2784. this._isCullFaceDirty = false;
  2785. }
  2786. if (this._isDepthMaskDirty) {
  2787. gl.depthMask(this.depthMask);
  2788. this._isDepthMaskDirty = false;
  2789. }
  2790. if (this._isDepthTestDirty) {
  2791. if (this.depthTest === true) {
  2792. gl.enable(gl.DEPTH_TEST);
  2793. } else if (this.depthTest === false) {
  2794. gl.disable(gl.DEPTH_TEST);
  2795. }
  2796. this._isDepthTestDirty = false;
  2797. }
  2798. if (this._isDepthFuncDirty) {
  2799. gl.depthFunc(this.depthFunc);
  2800. this._isDepthFuncDirty = false;
  2801. }
  2802. };
  2803. return _DepthCullingState;
  2804. })();
  2805. BABYLON._DepthCullingState = _DepthCullingState;
  2806. var _AlphaState = (function () {
  2807. function _AlphaState() {
  2808. this._isAlphaBlendDirty = false;
  2809. this._isBlendFunctionParametersDirty = false;
  2810. this._alphaBlend = false;
  2811. this._blendFunctionParameters = new Array(4);
  2812. }
  2813. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2814. get: function () {
  2815. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2816. },
  2817. enumerable: true,
  2818. configurable: true
  2819. });
  2820. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2821. get: function () {
  2822. return this._alphaBlend;
  2823. },
  2824. set: function (value) {
  2825. if (this._alphaBlend === value) {
  2826. return;
  2827. }
  2828. this._alphaBlend = value;
  2829. this._isAlphaBlendDirty = true;
  2830. },
  2831. enumerable: true,
  2832. configurable: true
  2833. });
  2834. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2835. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2836. return;
  2837. }
  2838. this._blendFunctionParameters[0] = value0;
  2839. this._blendFunctionParameters[1] = value1;
  2840. this._blendFunctionParameters[2] = value2;
  2841. this._blendFunctionParameters[3] = value3;
  2842. this._isBlendFunctionParametersDirty = true;
  2843. };
  2844. _AlphaState.prototype.reset = function () {
  2845. this._alphaBlend = false;
  2846. this._blendFunctionParameters[0] = null;
  2847. this._blendFunctionParameters[1] = null;
  2848. this._blendFunctionParameters[2] = null;
  2849. this._blendFunctionParameters[3] = null;
  2850. this._isAlphaBlendDirty = true;
  2851. this._isBlendFunctionParametersDirty = false;
  2852. };
  2853. _AlphaState.prototype.apply = function (gl) {
  2854. if (!this.isDirty) {
  2855. return;
  2856. }
  2857. if (this._isAlphaBlendDirty) {
  2858. if (this._alphaBlend === true) {
  2859. gl.enable(gl.BLEND);
  2860. } else if (this._alphaBlend === false) {
  2861. gl.disable(gl.BLEND);
  2862. }
  2863. this._isAlphaBlendDirty = false;
  2864. }
  2865. if (this._isBlendFunctionParametersDirty) {
  2866. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2867. this._isBlendFunctionParametersDirty = false;
  2868. }
  2869. };
  2870. return _AlphaState;
  2871. })();
  2872. BABYLON._AlphaState = _AlphaState;
  2873. var compileShader = function (gl, source, type, defines) {
  2874. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2875. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2876. gl.compileShader(shader);
  2877. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2878. throw new Error(gl.getShaderInfoLog(shader));
  2879. }
  2880. return shader;
  2881. };
  2882. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2883. var magFilter = gl.NEAREST;
  2884. var minFilter = gl.NEAREST;
  2885. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2886. magFilter = gl.LINEAR;
  2887. if (generateMipMaps) {
  2888. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2889. } else {
  2890. minFilter = gl.LINEAR;
  2891. }
  2892. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2893. magFilter = gl.LINEAR;
  2894. if (generateMipMaps) {
  2895. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2896. } else {
  2897. minFilter = gl.LINEAR;
  2898. }
  2899. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2900. magFilter = gl.NEAREST;
  2901. if (generateMipMaps) {
  2902. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2903. } else {
  2904. minFilter = gl.NEAREST;
  2905. }
  2906. }
  2907. return {
  2908. min: minFilter,
  2909. mag: magFilter
  2910. };
  2911. };
  2912. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2913. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2914. var engine = scene.getEngine();
  2915. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2916. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2917. gl.bindTexture(gl.TEXTURE_2D, texture);
  2918. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2919. processFunction(potWidth, potHeight);
  2920. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2921. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2922. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2923. if (!noMipmap && !isCompressed) {
  2924. gl.generateMipmap(gl.TEXTURE_2D);
  2925. }
  2926. gl.bindTexture(gl.TEXTURE_2D, null);
  2927. engine._activeTexturesCache = [];
  2928. texture._baseWidth = width;
  2929. texture._baseHeight = height;
  2930. texture._width = potWidth;
  2931. texture._height = potHeight;
  2932. texture.isReady = true;
  2933. scene._removePendingData(texture);
  2934. };
  2935. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  2936. var img;
  2937. var onload = function () {
  2938. loadedImages[index] = img;
  2939. loadedImages._internalCount++;
  2940. scene._removePendingData(img);
  2941. if (loadedImages._internalCount == 6) {
  2942. onfinish(loadedImages);
  2943. }
  2944. };
  2945. var onerror = function () {
  2946. scene._removePendingData(img);
  2947. };
  2948. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  2949. scene._addPendingData(img);
  2950. };
  2951. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  2952. var loadedImages = [];
  2953. loadedImages._internalCount = 0;
  2954. for (var index = 0; index < 6; index++) {
  2955. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  2956. }
  2957. };
  2958. var EngineCapabilities = (function () {
  2959. function EngineCapabilities() {
  2960. }
  2961. return EngineCapabilities;
  2962. })();
  2963. BABYLON.EngineCapabilities = EngineCapabilities;
  2964. var Engine = (function () {
  2965. function Engine(canvas, antialias, options) {
  2966. var _this = this;
  2967. this.isFullscreen = false;
  2968. this.isPointerLock = false;
  2969. this.cullBackFaces = true;
  2970. this.renderEvenInBackground = true;
  2971. this.scenes = new Array();
  2972. this._windowIsBackground = false;
  2973. this._runningLoop = false;
  2974. this._loadingDivBackgroundColor = "black";
  2975. this._drawCalls = 0;
  2976. this._depthCullingState = new _DepthCullingState();
  2977. this._alphaState = new _AlphaState();
  2978. this._alphaMode = Engine.ALPHA_DISABLE;
  2979. this._loadedTexturesCache = new Array();
  2980. this._activeTexturesCache = new Array();
  2981. this._compiledEffects = {};
  2982. this._uintIndicesCurrentlySet = false;
  2983. this._renderingCanvas = canvas;
  2984. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  2985. options = options || {};
  2986. options.antialias = antialias;
  2987. try {
  2988. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  2989. } catch (e) {
  2990. throw new Error("WebGL not supported");
  2991. }
  2992. if (!this._gl) {
  2993. throw new Error("WebGL not supported");
  2994. }
  2995. this._onBlur = function () {
  2996. _this._windowIsBackground = true;
  2997. };
  2998. this._onFocus = function () {
  2999. _this._windowIsBackground = false;
  3000. };
  3001. window.addEventListener("blur", this._onBlur);
  3002. window.addEventListener("focus", this._onFocus);
  3003. this._workingCanvas = document.createElement("canvas");
  3004. this._workingContext = this._workingCanvas.getContext("2d");
  3005. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3006. this.resize();
  3007. this._caps = new EngineCapabilities();
  3008. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3009. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3010. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3011. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3012. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3013. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3014. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3015. 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');
  3016. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3017. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3018. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3019. this.setDepthBuffer(true);
  3020. this.setDepthFunctionToLessOrEqual();
  3021. this.setDepthWrite(true);
  3022. this._onFullscreenChange = function () {
  3023. if (document.fullscreen !== undefined) {
  3024. _this.isFullscreen = document.fullscreen;
  3025. } else if (document.mozFullScreen !== undefined) {
  3026. _this.isFullscreen = document.mozFullScreen;
  3027. } else if (document.webkitIsFullScreen !== undefined) {
  3028. _this.isFullscreen = document.webkitIsFullScreen;
  3029. } else if (document.msIsFullScreen !== undefined) {
  3030. _this.isFullscreen = document.msIsFullScreen;
  3031. }
  3032. if (_this.isFullscreen && _this._pointerLockRequested) {
  3033. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3034. if (canvas.requestPointerLock) {
  3035. canvas.requestPointerLock();
  3036. }
  3037. }
  3038. };
  3039. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3040. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3041. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3042. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3043. this._onPointerLockChange = function () {
  3044. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3045. };
  3046. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3047. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3048. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3049. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3050. this._audioEngine = new BABYLON.AudioEngine();
  3051. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3052. }
  3053. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3054. get: function () {
  3055. return Engine._ALPHA_DISABLE;
  3056. },
  3057. enumerable: true,
  3058. configurable: true
  3059. });
  3060. Object.defineProperty(Engine, "ALPHA_ADD", {
  3061. get: function () {
  3062. return Engine._ALPHA_ADD;
  3063. },
  3064. enumerable: true,
  3065. configurable: true
  3066. });
  3067. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3068. get: function () {
  3069. return Engine._ALPHA_COMBINE;
  3070. },
  3071. enumerable: true,
  3072. configurable: true
  3073. });
  3074. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3075. get: function () {
  3076. return Engine._DELAYLOADSTATE_NONE;
  3077. },
  3078. enumerable: true,
  3079. configurable: true
  3080. });
  3081. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3082. get: function () {
  3083. return Engine._DELAYLOADSTATE_LOADED;
  3084. },
  3085. enumerable: true,
  3086. configurable: true
  3087. });
  3088. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3089. get: function () {
  3090. return Engine._DELAYLOADSTATE_LOADING;
  3091. },
  3092. enumerable: true,
  3093. configurable: true
  3094. });
  3095. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3096. get: function () {
  3097. return Engine._DELAYLOADSTATE_NOTLOADED;
  3098. },
  3099. enumerable: true,
  3100. configurable: true
  3101. });
  3102. Object.defineProperty(Engine, "Version", {
  3103. get: function () {
  3104. return "2.0.0";
  3105. },
  3106. enumerable: true,
  3107. configurable: true
  3108. });
  3109. Engine.prototype.getAudioEngine = function () {
  3110. return this._audioEngine;
  3111. };
  3112. Engine.prototype.getAspectRatio = function (camera) {
  3113. var viewport = camera.viewport;
  3114. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3115. };
  3116. Engine.prototype.getRenderWidth = function () {
  3117. if (this._currentRenderTarget) {
  3118. return this._currentRenderTarget._width;
  3119. }
  3120. return this._renderingCanvas.width;
  3121. };
  3122. Engine.prototype.getRenderHeight = function () {
  3123. if (this._currentRenderTarget) {
  3124. return this._currentRenderTarget._height;
  3125. }
  3126. return this._renderingCanvas.height;
  3127. };
  3128. Engine.prototype.getRenderingCanvas = function () {
  3129. return this._renderingCanvas;
  3130. };
  3131. Engine.prototype.getRenderingCanvasClientRect = function () {
  3132. return this._renderingCanvas.getBoundingClientRect();
  3133. };
  3134. Engine.prototype.setHardwareScalingLevel = function (level) {
  3135. this._hardwareScalingLevel = level;
  3136. this.resize();
  3137. };
  3138. Engine.prototype.getHardwareScalingLevel = function () {
  3139. return this._hardwareScalingLevel;
  3140. };
  3141. Engine.prototype.getLoadedTexturesCache = function () {
  3142. return this._loadedTexturesCache;
  3143. };
  3144. Engine.prototype.getCaps = function () {
  3145. return this._caps;
  3146. };
  3147. Object.defineProperty(Engine.prototype, "drawCalls", {
  3148. get: function () {
  3149. return this._drawCalls;
  3150. },
  3151. enumerable: true,
  3152. configurable: true
  3153. });
  3154. Engine.prototype.resetDrawCalls = function () {
  3155. this._drawCalls = 0;
  3156. };
  3157. Engine.prototype.setDepthFunctionToGreater = function () {
  3158. this._depthCullingState.depthFunc = this._gl.GREATER;
  3159. };
  3160. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3161. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3162. };
  3163. Engine.prototype.setDepthFunctionToLess = function () {
  3164. this._depthCullingState.depthFunc = this._gl.LESS;
  3165. };
  3166. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3167. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3168. };
  3169. Engine.prototype.stopRenderLoop = function () {
  3170. this._renderFunction = null;
  3171. this._runningLoop = false;
  3172. };
  3173. Engine.prototype._renderLoop = function () {
  3174. var _this = this;
  3175. var shouldRender = true;
  3176. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3177. shouldRender = false;
  3178. }
  3179. if (shouldRender) {
  3180. this.beginFrame();
  3181. if (this._renderFunction) {
  3182. this._renderFunction();
  3183. }
  3184. this.endFrame();
  3185. }
  3186. if (this._runningLoop) {
  3187. BABYLON.Tools.QueueNewFrame(function () {
  3188. _this._renderLoop();
  3189. });
  3190. }
  3191. };
  3192. Engine.prototype.runRenderLoop = function (renderFunction) {
  3193. var _this = this;
  3194. this._runningLoop = true;
  3195. this._renderFunction = renderFunction;
  3196. BABYLON.Tools.QueueNewFrame(function () {
  3197. _this._renderLoop();
  3198. });
  3199. };
  3200. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3201. if (this.isFullscreen) {
  3202. BABYLON.Tools.ExitFullscreen();
  3203. } else {
  3204. this._pointerLockRequested = requestPointerLock;
  3205. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3206. }
  3207. };
  3208. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3209. this.applyStates();
  3210. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3211. if (this._depthCullingState.depthMask) {
  3212. this._gl.clearDepth(1.0);
  3213. }
  3214. var mode = 0;
  3215. if (backBuffer)
  3216. mode |= this._gl.COLOR_BUFFER_BIT;
  3217. if (depthStencil && this._depthCullingState.depthMask)
  3218. mode |= this._gl.DEPTH_BUFFER_BIT;
  3219. this._gl.clear(mode);
  3220. };
  3221. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3222. var width = requiredWidth || this._renderingCanvas.width;
  3223. var height = requiredHeight || this._renderingCanvas.height;
  3224. var x = viewport.x || 0;
  3225. var y = viewport.y || 0;
  3226. this._cachedViewport = viewport;
  3227. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3228. };
  3229. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3230. this._cachedViewport = null;
  3231. this._gl.viewport(x, y, width, height);
  3232. };
  3233. Engine.prototype.beginFrame = function () {
  3234. BABYLON.Tools._MeasureFps();
  3235. };
  3236. Engine.prototype.endFrame = function () {
  3237. this.flushFramebuffer();
  3238. };
  3239. Engine.prototype.resize = function () {
  3240. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3241. };
  3242. Engine.prototype.setSize = function (width, height) {
  3243. this._renderingCanvas.width = width;
  3244. this._renderingCanvas.height = height;
  3245. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3246. };
  3247. Engine.prototype.bindFramebuffer = function (texture) {
  3248. this._currentRenderTarget = texture;
  3249. var gl = this._gl;
  3250. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3251. this._gl.viewport(0, 0, texture._width, texture._height);
  3252. this.wipeCaches();
  3253. };
  3254. Engine.prototype.unBindFramebuffer = function (texture) {
  3255. this._currentRenderTarget = null;
  3256. if (texture.generateMipMaps) {
  3257. var gl = this._gl;
  3258. gl.bindTexture(gl.TEXTURE_2D, texture);
  3259. gl.generateMipmap(gl.TEXTURE_2D);
  3260. gl.bindTexture(gl.TEXTURE_2D, null);
  3261. }
  3262. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3263. };
  3264. Engine.prototype.flushFramebuffer = function () {
  3265. };
  3266. Engine.prototype.restoreDefaultFramebuffer = function () {
  3267. this._currentRenderTarget = null;
  3268. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3269. this.setViewport(this._cachedViewport);
  3270. this.wipeCaches();
  3271. };
  3272. Engine.prototype._resetVertexBufferBinding = function () {
  3273. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3274. this._cachedVertexBuffers = null;
  3275. };
  3276. Engine.prototype.createVertexBuffer = function (vertices) {
  3277. var vbo = this._gl.createBuffer();
  3278. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3279. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3280. this._resetVertexBufferBinding();
  3281. vbo.references = 1;
  3282. return vbo;
  3283. };
  3284. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3285. var vbo = this._gl.createBuffer();
  3286. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3287. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3288. this._resetVertexBufferBinding();
  3289. vbo.references = 1;
  3290. return vbo;
  3291. };
  3292. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, length) {
  3293. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3294. if (vertices instanceof Float32Array) {
  3295. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices);
  3296. } else {
  3297. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices));
  3298. }
  3299. this._resetVertexBufferBinding();
  3300. };
  3301. Engine.prototype._resetIndexBufferBinding = function () {
  3302. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3303. this._cachedIndexBuffer = null;
  3304. };
  3305. Engine.prototype.createIndexBuffer = function (indices) {
  3306. var vbo = this._gl.createBuffer();
  3307. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3308. var arrayBuffer;
  3309. var need32Bits = false;
  3310. if (this._caps.uintIndices) {
  3311. for (var index = 0; index < indices.length; index++) {
  3312. if (indices[index] > 65535) {
  3313. need32Bits = true;
  3314. break;
  3315. }
  3316. }
  3317. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3318. } else {
  3319. arrayBuffer = new Uint16Array(indices);
  3320. }
  3321. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3322. this._resetIndexBufferBinding();
  3323. vbo.references = 1;
  3324. vbo.is32Bits = need32Bits;
  3325. return vbo;
  3326. };
  3327. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3328. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3329. this._cachedVertexBuffers = vertexBuffer;
  3330. this._cachedEffectForVertexBuffers = effect;
  3331. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3332. var offset = 0;
  3333. for (var index = 0; index < vertexDeclaration.length; index++) {
  3334. var order = effect.getAttributeLocation(index);
  3335. if (order >= 0) {
  3336. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3337. }
  3338. offset += vertexDeclaration[index] * 4;
  3339. }
  3340. }
  3341. if (this._cachedIndexBuffer !== indexBuffer) {
  3342. this._cachedIndexBuffer = indexBuffer;
  3343. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3344. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3345. }
  3346. };
  3347. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3348. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3349. this._cachedVertexBuffers = vertexBuffers;
  3350. this._cachedEffectForVertexBuffers = effect;
  3351. var attributes = effect.getAttributesNames();
  3352. for (var index = 0; index < attributes.length; index++) {
  3353. var order = effect.getAttributeLocation(index);
  3354. if (order >= 0) {
  3355. var vertexBuffer = vertexBuffers[attributes[index]];
  3356. if (!vertexBuffer) {
  3357. continue;
  3358. }
  3359. var stride = vertexBuffer.getStrideSize();
  3360. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3361. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3362. }
  3363. }
  3364. }
  3365. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3366. this._cachedIndexBuffer = indexBuffer;
  3367. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3368. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3369. }
  3370. };
  3371. Engine.prototype._releaseBuffer = function (buffer) {
  3372. buffer.references--;
  3373. if (buffer.references === 0) {
  3374. this._gl.deleteBuffer(buffer);
  3375. return true;
  3376. }
  3377. return false;
  3378. };
  3379. Engine.prototype.createInstancesBuffer = function (capacity) {
  3380. var buffer = this._gl.createBuffer();
  3381. buffer.capacity = capacity;
  3382. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3383. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3384. return buffer;
  3385. };
  3386. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3387. this._gl.deleteBuffer(buffer);
  3388. };
  3389. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3390. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3391. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3392. for (var index = 0; index < 4; index++) {
  3393. var offsetLocation = offsetLocations[index];
  3394. this._gl.enableVertexAttribArray(offsetLocation);
  3395. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3396. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3397. }
  3398. };
  3399. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3400. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3401. for (var index = 0; index < 4; index++) {
  3402. var offsetLocation = offsetLocations[index];
  3403. this._gl.disableVertexAttribArray(offsetLocation);
  3404. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3405. }
  3406. };
  3407. Engine.prototype.applyStates = function () {
  3408. this._depthCullingState.apply(this._gl);
  3409. this._alphaState.apply(this._gl);
  3410. };
  3411. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3412. this.applyStates();
  3413. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3414. if (instancesCount) {
  3415. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3416. return;
  3417. }
  3418. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3419. this._drawCalls++;
  3420. };
  3421. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3422. this.applyStates();
  3423. if (instancesCount) {
  3424. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3425. return;
  3426. }
  3427. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3428. this._drawCalls++;
  3429. };
  3430. Engine.prototype._releaseEffect = function (effect) {
  3431. if (this._compiledEffects[effect._key]) {
  3432. delete this._compiledEffects[effect._key];
  3433. if (effect.getProgram()) {
  3434. this._gl.deleteProgram(effect.getProgram());
  3435. }
  3436. }
  3437. };
  3438. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3439. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3440. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3441. var name = vertex + "+" + fragment + "@" + defines;
  3442. if (this._compiledEffects[name]) {
  3443. return this._compiledEffects[name];
  3444. }
  3445. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3446. effect._key = name;
  3447. this._compiledEffects[name] = effect;
  3448. return effect;
  3449. };
  3450. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3451. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3452. if (typeof samplers === "undefined") { samplers = []; }
  3453. if (typeof defines === "undefined") { defines = ""; }
  3454. return this.createEffect({
  3455. vertex: "particles",
  3456. fragmentElement: fragmentName
  3457. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3458. };
  3459. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3460. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3461. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3462. var shaderProgram = this._gl.createProgram();
  3463. this._gl.attachShader(shaderProgram, vertexShader);
  3464. this._gl.attachShader(shaderProgram, fragmentShader);
  3465. this._gl.linkProgram(shaderProgram);
  3466. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3467. if (!linked) {
  3468. var error = this._gl.getProgramInfoLog(shaderProgram);
  3469. if (error) {
  3470. throw new Error(error);
  3471. }
  3472. }
  3473. this._gl.deleteShader(vertexShader);
  3474. this._gl.deleteShader(fragmentShader);
  3475. return shaderProgram;
  3476. };
  3477. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3478. var results = [];
  3479. for (var index = 0; index < uniformsNames.length; index++) {
  3480. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3481. }
  3482. return results;
  3483. };
  3484. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3485. var results = [];
  3486. for (var index = 0; index < attributesNames.length; index++) {
  3487. try {
  3488. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3489. } catch (e) {
  3490. results.push(-1);
  3491. }
  3492. }
  3493. return results;
  3494. };
  3495. Engine.prototype.enableEffect = function (effect) {
  3496. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3497. if (effect && effect.onBind) {
  3498. effect.onBind(effect);
  3499. }
  3500. return;
  3501. }
  3502. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3503. this._gl.useProgram(effect.getProgram());
  3504. for (var i in this._vertexAttribArrays) {
  3505. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3506. continue;
  3507. }
  3508. this._vertexAttribArrays[i] = false;
  3509. this._gl.disableVertexAttribArray(i);
  3510. }
  3511. var attributesCount = effect.getAttributesCount();
  3512. for (var index = 0; index < attributesCount; index++) {
  3513. var order = effect.getAttributeLocation(index);
  3514. if (order >= 0) {
  3515. this._vertexAttribArrays[order] = true;
  3516. this._gl.enableVertexAttribArray(order);
  3517. }
  3518. }
  3519. this._currentEffect = effect;
  3520. if (effect.onBind) {
  3521. effect.onBind(effect);
  3522. }
  3523. };
  3524. Engine.prototype.setArray = function (uniform, array) {
  3525. if (!uniform)
  3526. return;
  3527. this._gl.uniform1fv(uniform, array);
  3528. };
  3529. Engine.prototype.setMatrices = function (uniform, matrices) {
  3530. if (!uniform)
  3531. return;
  3532. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3533. };
  3534. Engine.prototype.setMatrix = function (uniform, matrix) {
  3535. if (!uniform)
  3536. return;
  3537. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3538. };
  3539. Engine.prototype.setFloat = function (uniform, value) {
  3540. if (!uniform)
  3541. return;
  3542. this._gl.uniform1f(uniform, value);
  3543. };
  3544. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3545. if (!uniform)
  3546. return;
  3547. this._gl.uniform2f(uniform, x, y);
  3548. };
  3549. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3550. if (!uniform)
  3551. return;
  3552. this._gl.uniform3f(uniform, x, y, z);
  3553. };
  3554. Engine.prototype.setBool = function (uniform, bool) {
  3555. if (!uniform)
  3556. return;
  3557. this._gl.uniform1i(uniform, bool);
  3558. };
  3559. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3560. if (!uniform)
  3561. return;
  3562. this._gl.uniform4f(uniform, x, y, z, w);
  3563. };
  3564. Engine.prototype.setColor3 = function (uniform, color3) {
  3565. if (!uniform)
  3566. return;
  3567. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3568. };
  3569. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3570. if (!uniform)
  3571. return;
  3572. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3573. };
  3574. Engine.prototype.setState = function (culling, force) {
  3575. if (this._depthCullingState.cull !== culling || force) {
  3576. if (culling) {
  3577. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3578. this._depthCullingState.cull = true;
  3579. } else {
  3580. this._depthCullingState.cull = false;
  3581. }
  3582. }
  3583. };
  3584. Engine.prototype.setDepthBuffer = function (enable) {
  3585. this._depthCullingState.depthTest = enable;
  3586. };
  3587. Engine.prototype.getDepthWrite = function () {
  3588. return this._depthCullingState.depthMask;
  3589. };
  3590. Engine.prototype.setDepthWrite = function (enable) {
  3591. this._depthCullingState.depthMask = enable;
  3592. };
  3593. Engine.prototype.setColorWrite = function (enable) {
  3594. this._gl.colorMask(enable, enable, enable, enable);
  3595. };
  3596. Engine.prototype.setAlphaMode = function (mode) {
  3597. switch (mode) {
  3598. case BABYLON.Engine.ALPHA_DISABLE:
  3599. this.setDepthWrite(true);
  3600. this._alphaState.alphaBlend = false;
  3601. break;
  3602. case BABYLON.Engine.ALPHA_COMBINE:
  3603. this.setDepthWrite(false);
  3604. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3605. this._alphaState.alphaBlend = true;
  3606. break;
  3607. case BABYLON.Engine.ALPHA_ADD:
  3608. this.setDepthWrite(false);
  3609. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3610. this._alphaState.alphaBlend = true;
  3611. break;
  3612. }
  3613. this._alphaMode = mode;
  3614. };
  3615. Engine.prototype.getAlphaMode = function () {
  3616. return this._alphaMode;
  3617. };
  3618. Engine.prototype.setAlphaTesting = function (enable) {
  3619. this._alphaTest = enable;
  3620. };
  3621. Engine.prototype.getAlphaTesting = function () {
  3622. return this._alphaTest;
  3623. };
  3624. Engine.prototype.wipeCaches = function () {
  3625. this._activeTexturesCache = [];
  3626. this._currentEffect = null;
  3627. this._depthCullingState.reset();
  3628. this._alphaState.reset();
  3629. this._cachedVertexBuffers = null;
  3630. this._cachedIndexBuffer = null;
  3631. this._cachedEffectForVertexBuffers = null;
  3632. };
  3633. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3634. var gl = this._gl;
  3635. gl.bindTexture(gl.TEXTURE_2D, texture);
  3636. var magFilter = gl.NEAREST;
  3637. var minFilter = gl.NEAREST;
  3638. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3639. magFilter = gl.LINEAR;
  3640. minFilter = gl.LINEAR;
  3641. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3642. magFilter = gl.LINEAR;
  3643. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3644. }
  3645. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3646. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3647. gl.bindTexture(gl.TEXTURE_2D, null);
  3648. };
  3649. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3650. var _this = this;
  3651. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3652. if (typeof onLoad === "undefined") { onLoad = null; }
  3653. if (typeof onError === "undefined") { onError = null; }
  3654. if (typeof buffer === "undefined") { buffer = null; }
  3655. var texture = this._gl.createTexture();
  3656. var extension;
  3657. var fromData = false;
  3658. if (url.substr(0, 5) === "data:") {
  3659. fromData = true;
  3660. }
  3661. if (!fromData)
  3662. extension = url.substr(url.length - 4, 4).toLowerCase();
  3663. else {
  3664. var oldUrl = url;
  3665. fromData = oldUrl.split(':');
  3666. url = oldUrl;
  3667. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3668. }
  3669. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3670. var isTGA = (extension === ".tga");
  3671. scene._addPendingData(texture);
  3672. texture.url = url;
  3673. texture.noMipmap = noMipmap;
  3674. texture.references = 1;
  3675. this._loadedTexturesCache.push(texture);
  3676. var onerror = function () {
  3677. scene._removePendingData(texture);
  3678. if (onError) {
  3679. onError();
  3680. }
  3681. };
  3682. if (isTGA) {
  3683. var callback = function (arrayBuffer) {
  3684. var data = new Uint8Array(arrayBuffer);
  3685. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3686. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3687. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3688. if (onLoad) {
  3689. onLoad();
  3690. }
  3691. }, samplingMode);
  3692. };
  3693. if (!(fromData instanceof Array))
  3694. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3695. callback(arrayBuffer);
  3696. }, onerror, scene.database, true);
  3697. else
  3698. callback(buffer);
  3699. } else if (isDDS) {
  3700. callback = function (data) {
  3701. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3702. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3703. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3704. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3705. if (onLoad) {
  3706. onLoad();
  3707. }
  3708. }, samplingMode);
  3709. };
  3710. if (!(fromData instanceof Array))
  3711. BABYLON.Tools.LoadFile(url, function (data) {
  3712. callback(data);
  3713. }, onerror, scene.database, true);
  3714. else
  3715. callback(buffer);
  3716. } else {
  3717. var onload = function (img) {
  3718. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3719. var isPot = (img.width == potWidth && img.height == potHeight);
  3720. if (!isPot) {
  3721. _this._workingCanvas.width = potWidth;
  3722. _this._workingCanvas.height = potHeight;
  3723. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3724. }
  3725. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3726. if (onLoad) {
  3727. onLoad();
  3728. }
  3729. }, samplingMode);
  3730. };
  3731. if (!(fromData instanceof Array))
  3732. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3733. else
  3734. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3735. }
  3736. return texture;
  3737. };
  3738. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3739. var texture = this._gl.createTexture();
  3740. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3741. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3742. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3743. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3744. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3745. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3746. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3747. this._activeTexturesCache = [];
  3748. texture._baseWidth = width;
  3749. texture._baseHeight = height;
  3750. texture._width = width;
  3751. texture._height = height;
  3752. texture.isReady = false;
  3753. texture.generateMipMaps = generateMipMaps;
  3754. texture.references = 1;
  3755. this._loadedTexturesCache.push(texture);
  3756. return texture;
  3757. };
  3758. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3759. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3760. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3762. if (texture.generateMipMaps) {
  3763. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3764. }
  3765. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3766. this._activeTexturesCache = [];
  3767. texture.isReady = true;
  3768. };
  3769. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3770. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3771. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1);
  3772. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3773. if (!texture._workingCanvas) {
  3774. texture._workingCanvas = document.createElement("canvas");
  3775. texture._workingContext = texture._workingCanvas.getContext("2d");
  3776. texture._workingCanvas.width = texture._width;
  3777. texture._workingCanvas.height = texture._height;
  3778. }
  3779. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3780. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3781. } else {
  3782. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3783. }
  3784. if (texture.generateMipMaps) {
  3785. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3786. }
  3787. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3788. this._activeTexturesCache = [];
  3789. texture.isReady = true;
  3790. };
  3791. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3792. var generateMipMaps = false;
  3793. var generateDepthBuffer = true;
  3794. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3795. if (options !== undefined) {
  3796. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3797. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3798. if (options.samplingMode !== undefined) {
  3799. samplingMode = options.samplingMode;
  3800. }
  3801. }
  3802. var gl = this._gl;
  3803. var texture = gl.createTexture();
  3804. gl.bindTexture(gl.TEXTURE_2D, texture);
  3805. var width = size.width || size;
  3806. var height = size.height || size;
  3807. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3808. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3812. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  3813. var depthBuffer;
  3814. if (generateDepthBuffer) {
  3815. depthBuffer = gl.createRenderbuffer();
  3816. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  3817. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  3818. }
  3819. var framebuffer = gl.createFramebuffer();
  3820. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  3821. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3822. if (generateDepthBuffer) {
  3823. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  3824. }
  3825. gl.bindTexture(gl.TEXTURE_2D, null);
  3826. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3827. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3828. texture._framebuffer = framebuffer;
  3829. if (generateDepthBuffer) {
  3830. texture._depthBuffer = depthBuffer;
  3831. }
  3832. texture._width = width;
  3833. texture._height = height;
  3834. texture.isReady = true;
  3835. texture.generateMipMaps = generateMipMaps;
  3836. texture.references = 1;
  3837. this._activeTexturesCache = [];
  3838. this._loadedTexturesCache.push(texture);
  3839. return texture;
  3840. };
  3841. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  3842. var _this = this;
  3843. var gl = this._gl;
  3844. var texture = gl.createTexture();
  3845. texture.isCube = true;
  3846. texture.url = rootUrl;
  3847. texture.references = 1;
  3848. this._loadedTexturesCache.push(texture);
  3849. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  3850. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3851. if (isDDS) {
  3852. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  3853. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3854. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  3855. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3856. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  3857. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  3858. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  3859. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3860. }
  3861. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  3863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3865. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3866. _this._activeTexturesCache = [];
  3867. texture._width = info.width;
  3868. texture._height = info.height;
  3869. texture.isReady = true;
  3870. }, null, null, true);
  3871. } else {
  3872. cascadeLoad(rootUrl, scene, function (imgs) {
  3873. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  3874. var height = width;
  3875. _this._workingCanvas.width = width;
  3876. _this._workingCanvas.height = height;
  3877. var faces = [
  3878. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  3879. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  3880. ];
  3881. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  3882. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3883. for (var index = 0; index < faces.length; index++) {
  3884. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  3885. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  3886. }
  3887. if (!noMipmap) {
  3888. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  3889. }
  3890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  3892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3894. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  3895. _this._activeTexturesCache = [];
  3896. texture._width = width;
  3897. texture._height = height;
  3898. texture.isReady = true;
  3899. }, extensions);
  3900. }
  3901. return texture;
  3902. };
  3903. Engine.prototype._releaseTexture = function (texture) {
  3904. var gl = this._gl;
  3905. if (texture._framebuffer) {
  3906. gl.deleteFramebuffer(texture._framebuffer);
  3907. }
  3908. if (texture._depthBuffer) {
  3909. gl.deleteRenderbuffer(texture._depthBuffer);
  3910. }
  3911. gl.deleteTexture(texture);
  3912. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3913. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3914. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3915. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3916. this._activeTexturesCache[channel] = null;
  3917. }
  3918. var index = this._loadedTexturesCache.indexOf(texture);
  3919. if (index !== -1) {
  3920. this._loadedTexturesCache.splice(index, 1);
  3921. }
  3922. };
  3923. Engine.prototype.bindSamplers = function (effect) {
  3924. this._gl.useProgram(effect.getProgram());
  3925. var samplers = effect.getSamplers();
  3926. for (var index = 0; index < samplers.length; index++) {
  3927. var uniform = effect.getUniform(samplers[index]);
  3928. this._gl.uniform1i(uniform, index);
  3929. }
  3930. this._currentEffect = null;
  3931. };
  3932. Engine.prototype._bindTexture = function (channel, texture) {
  3933. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3934. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3935. this._activeTexturesCache[channel] = null;
  3936. };
  3937. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  3938. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3939. };
  3940. Engine.prototype.setTexture = function (channel, texture) {
  3941. if (channel < 0) {
  3942. return;
  3943. }
  3944. if (!texture || !texture.isReady()) {
  3945. if (this._activeTexturesCache[channel] != null) {
  3946. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3947. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3948. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  3949. this._activeTexturesCache[channel] = null;
  3950. }
  3951. return;
  3952. }
  3953. if (texture instanceof BABYLON.VideoTexture) {
  3954. if (texture.update()) {
  3955. this._activeTexturesCache[channel] = null;
  3956. }
  3957. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  3958. texture.delayLoad();
  3959. return;
  3960. }
  3961. if (this._activeTexturesCache[channel] == texture) {
  3962. return;
  3963. }
  3964. this._activeTexturesCache[channel] = texture;
  3965. var internalTexture = texture.getInternalTexture();
  3966. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  3967. if (internalTexture.isCube) {
  3968. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3969. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3970. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3971. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3972. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3973. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3974. }
  3975. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3976. } else {
  3977. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  3978. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3979. internalTexture._cachedWrapU = texture.wrapU;
  3980. switch (texture.wrapU) {
  3981. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3982. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3983. break;
  3984. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3985. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3986. break;
  3987. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  3988. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3989. break;
  3990. }
  3991. }
  3992. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3993. internalTexture._cachedWrapV = texture.wrapV;
  3994. switch (texture.wrapV) {
  3995. case BABYLON.Texture.WRAP_ADDRESSMODE:
  3996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3997. break;
  3998. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  3999. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4000. break;
  4001. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4002. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4003. break;
  4004. }
  4005. }
  4006. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4007. }
  4008. };
  4009. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4010. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4011. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4012. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4013. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4014. }
  4015. };
  4016. Engine.prototype.readPixels = function (x, y, width, height) {
  4017. var data = new Uint8Array(height * width * 4);
  4018. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4019. return data;
  4020. };
  4021. Engine.prototype.dispose = function () {
  4022. this.hideLoadingUI();
  4023. this.stopRenderLoop();
  4024. while (this.scenes.length) {
  4025. this.scenes[0].dispose();
  4026. }
  4027. for (var name in this._compiledEffects) {
  4028. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4029. }
  4030. for (var i in this._vertexAttribArrays) {
  4031. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4032. continue;
  4033. }
  4034. this._gl.disableVertexAttribArray(i);
  4035. }
  4036. window.removeEventListener("blur", this._onBlur);
  4037. window.removeEventListener("focus", this._onFocus);
  4038. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4039. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4040. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4041. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4042. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4043. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4044. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4045. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4046. };
  4047. Engine.prototype.displayLoadingUI = function () {
  4048. var _this = this;
  4049. this._loadingDiv = document.createElement("div");
  4050. this._loadingDiv.style.opacity = "0";
  4051. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4052. this._loadingTextDiv = document.createElement("div");
  4053. this._loadingTextDiv.style.position = "absolute";
  4054. this._loadingTextDiv.style.left = "0";
  4055. this._loadingTextDiv.style.top = "50%";
  4056. this._loadingTextDiv.style.marginTop = "80px";
  4057. this._loadingTextDiv.style.width = "100%";
  4058. this._loadingTextDiv.style.height = "20px";
  4059. this._loadingTextDiv.style.fontFamily = "Arial";
  4060. this._loadingTextDiv.style.fontSize = "14px";
  4061. this._loadingTextDiv.style.color = "white";
  4062. this._loadingTextDiv.style.textAlign = "center";
  4063. this._loadingTextDiv.innerHTML = "Loading";
  4064. this._loadingDiv.appendChild(this._loadingTextDiv);
  4065. var imgBack = new Image();
  4066. 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==";
  4067. imgBack.style.position = "absolute";
  4068. imgBack.style.left = "50%";
  4069. imgBack.style.top = "50%";
  4070. imgBack.style.marginLeft = "-50px";
  4071. imgBack.style.marginTop = "-50px";
  4072. imgBack.style.transition = "transform 1.0s ease";
  4073. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4074. var deg = 360;
  4075. var onTransitionEnd = function () {
  4076. deg += 360;
  4077. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4078. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4079. };
  4080. imgBack.addEventListener("transitionend", onTransitionEnd);
  4081. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4082. this._loadingDiv.appendChild(imgBack);
  4083. var imgFront = new Image();
  4084. 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=";
  4085. imgFront.style.position = "absolute";
  4086. imgFront.style.left = "50%";
  4087. imgFront.style.top = "50%";
  4088. imgFront.style.marginLeft = "-50px";
  4089. imgFront.style.marginTop = "-50px";
  4090. this._loadingDiv.appendChild(imgFront);
  4091. this._resizeLoadingUI = function () {
  4092. var canvasRect = _this.getRenderingCanvasClientRect();
  4093. _this._loadingDiv.style.position = "absolute";
  4094. _this._loadingDiv.style.left = canvasRect.left + "px";
  4095. _this._loadingDiv.style.top = canvasRect.top + "px";
  4096. _this._loadingDiv.style.width = canvasRect.width + "px";
  4097. _this._loadingDiv.style.height = canvasRect.height + "px";
  4098. };
  4099. this._resizeLoadingUI();
  4100. window.addEventListener("resize", this._resizeLoadingUI);
  4101. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4102. document.body.appendChild(this._loadingDiv);
  4103. setTimeout(function () {
  4104. _this._loadingDiv.style.opacity = "1";
  4105. imgBack.style.transform = "rotateZ(360deg)";
  4106. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4107. }, 0);
  4108. };
  4109. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4110. set: function (text) {
  4111. if (!this._loadingDiv) {
  4112. return;
  4113. }
  4114. this._loadingTextDiv.innerHTML = text;
  4115. },
  4116. enumerable: true,
  4117. configurable: true
  4118. });
  4119. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4120. get: function () {
  4121. return this._loadingDivBackgroundColor;
  4122. },
  4123. set: function (color) {
  4124. this._loadingDivBackgroundColor = color;
  4125. if (!this._loadingDiv) {
  4126. return;
  4127. }
  4128. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4129. },
  4130. enumerable: true,
  4131. configurable: true
  4132. });
  4133. Engine.prototype.hideLoadingUI = function () {
  4134. var _this = this;
  4135. if (!this._loadingDiv) {
  4136. return;
  4137. }
  4138. var onTransitionEnd = function () {
  4139. if (!_this._loadingDiv) {
  4140. return;
  4141. }
  4142. document.body.removeChild(_this._loadingDiv);
  4143. window.removeEventListener("resize", _this._resizeLoadingUI);
  4144. _this._loadingDiv = null;
  4145. };
  4146. this._loadingDiv.style.opacity = "0";
  4147. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4148. };
  4149. Engine.isSupported = function () {
  4150. try {
  4151. if (navigator.isCocoonJS) {
  4152. return true;
  4153. }
  4154. var tempcanvas = document.createElement("canvas");
  4155. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4156. return gl != null && !!window.WebGLRenderingContext;
  4157. } catch (e) {
  4158. return false;
  4159. }
  4160. };
  4161. Engine._ALPHA_DISABLE = 0;
  4162. Engine._ALPHA_ADD = 1;
  4163. Engine._ALPHA_COMBINE = 2;
  4164. Engine._DELAYLOADSTATE_NONE = 0;
  4165. Engine._DELAYLOADSTATE_LOADED = 1;
  4166. Engine._DELAYLOADSTATE_LOADING = 2;
  4167. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4168. Engine.Epsilon = 0.001;
  4169. Engine.CollisionsEpsilon = 0.001;
  4170. Engine.ShadersRepository = "Babylon/Shaders/";
  4171. return Engine;
  4172. })();
  4173. BABYLON.Engine = Engine;
  4174. })(BABYLON || (BABYLON = {}));
  4175. var BABYLON;
  4176. (function (BABYLON) {
  4177. var Node = (function () {
  4178. function Node(name, scene) {
  4179. this.state = "";
  4180. this.animations = new Array();
  4181. this._childrenFlag = -1;
  4182. this._isEnabled = true;
  4183. this._isReady = true;
  4184. this._currentRenderId = -1;
  4185. this.name = name;
  4186. this.id = name;
  4187. this._scene = scene;
  4188. this._initCache();
  4189. }
  4190. Node.prototype.getScene = function () {
  4191. return this._scene;
  4192. };
  4193. Node.prototype.getEngine = function () {
  4194. return this._scene.getEngine();
  4195. };
  4196. Node.prototype.getWorldMatrix = function () {
  4197. return BABYLON.Matrix.Identity();
  4198. };
  4199. Node.prototype._initCache = function () {
  4200. this._cache = {};
  4201. this._cache.parent = undefined;
  4202. };
  4203. Node.prototype.updateCache = function (force) {
  4204. if (!force && this.isSynchronized())
  4205. return;
  4206. this._cache.parent = this.parent;
  4207. this._updateCache();
  4208. };
  4209. Node.prototype._updateCache = function (ignoreParentClass) {
  4210. };
  4211. Node.prototype._isSynchronized = function () {
  4212. return true;
  4213. };
  4214. Node.prototype.isSynchronizedWithParent = function () {
  4215. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4216. };
  4217. Node.prototype.isSynchronized = function (updateCache) {
  4218. var check = this.hasNewParent();
  4219. check = check || !this.isSynchronizedWithParent();
  4220. check = check || !this._isSynchronized();
  4221. if (updateCache)
  4222. this.updateCache(true);
  4223. return !check;
  4224. };
  4225. Node.prototype.hasNewParent = function (update) {
  4226. if (this._cache.parent === this.parent)
  4227. return false;
  4228. if (update)
  4229. this._cache.parent = this.parent;
  4230. return true;
  4231. };
  4232. Node.prototype.isReady = function () {
  4233. return this._isReady;
  4234. };
  4235. Node.prototype.isEnabled = function () {
  4236. if (!this._isEnabled) {
  4237. return false;
  4238. }
  4239. if (this.parent) {
  4240. return this.parent.isEnabled();
  4241. }
  4242. return true;
  4243. };
  4244. Node.prototype.setEnabled = function (value) {
  4245. this._isEnabled = value;
  4246. };
  4247. Node.prototype.isDescendantOf = function (ancestor) {
  4248. if (this.parent) {
  4249. if (this.parent === ancestor) {
  4250. return true;
  4251. }
  4252. return this.parent.isDescendantOf(ancestor);
  4253. }
  4254. return false;
  4255. };
  4256. Node.prototype._getDescendants = function (list, results) {
  4257. for (var index = 0; index < list.length; index++) {
  4258. var item = list[index];
  4259. if (item.isDescendantOf(this)) {
  4260. results.push(item);
  4261. }
  4262. }
  4263. };
  4264. Node.prototype.getDescendants = function () {
  4265. var results = [];
  4266. this._getDescendants(this._scene.meshes, results);
  4267. this._getDescendants(this._scene.lights, results);
  4268. this._getDescendants(this._scene.cameras, results);
  4269. return results;
  4270. };
  4271. Node.prototype._setReady = function (state) {
  4272. if (state == this._isReady) {
  4273. return;
  4274. }
  4275. if (!state) {
  4276. this._isReady = false;
  4277. return;
  4278. }
  4279. this._isReady = true;
  4280. if (this.onReady) {
  4281. this.onReady(this);
  4282. }
  4283. };
  4284. return Node;
  4285. })();
  4286. BABYLON.Node = Node;
  4287. })(BABYLON || (BABYLON = {}));
  4288. var BABYLON;
  4289. (function (BABYLON) {
  4290. var BoundingSphere = (function () {
  4291. function BoundingSphere(minimum, maximum) {
  4292. this.minimum = minimum;
  4293. this.maximum = maximum;
  4294. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4295. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4296. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4297. this.radius = distance * 0.5;
  4298. this.centerWorld = BABYLON.Vector3.Zero();
  4299. this._update(BABYLON.Matrix.Identity());
  4300. }
  4301. BoundingSphere.prototype._update = function (world) {
  4302. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4303. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4304. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4305. };
  4306. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4307. for (var i = 0; i < 6; i++) {
  4308. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4309. return false;
  4310. }
  4311. return true;
  4312. };
  4313. BoundingSphere.prototype.intersectsPoint = function (point) {
  4314. var x = this.centerWorld.x - point.x;
  4315. var y = this.centerWorld.y - point.y;
  4316. var z = this.centerWorld.z - point.z;
  4317. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4318. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4319. return false;
  4320. return true;
  4321. };
  4322. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4323. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4324. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4325. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4326. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4327. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4328. return false;
  4329. return true;
  4330. };
  4331. return BoundingSphere;
  4332. })();
  4333. BABYLON.BoundingSphere = BoundingSphere;
  4334. })(BABYLON || (BABYLON = {}));
  4335. var BABYLON;
  4336. (function (BABYLON) {
  4337. var BoundingBox = (function () {
  4338. function BoundingBox(minimum, maximum) {
  4339. this.minimum = minimum;
  4340. this.maximum = maximum;
  4341. this.vectors = new Array();
  4342. this.vectorsWorld = new Array();
  4343. this.vectors.push(this.minimum.clone());
  4344. this.vectors.push(this.maximum.clone());
  4345. this.vectors.push(this.minimum.clone());
  4346. this.vectors[2].x = this.maximum.x;
  4347. this.vectors.push(this.minimum.clone());
  4348. this.vectors[3].y = this.maximum.y;
  4349. this.vectors.push(this.minimum.clone());
  4350. this.vectors[4].z = this.maximum.z;
  4351. this.vectors.push(this.maximum.clone());
  4352. this.vectors[5].z = this.minimum.z;
  4353. this.vectors.push(this.maximum.clone());
  4354. this.vectors[6].x = this.minimum.x;
  4355. this.vectors.push(this.maximum.clone());
  4356. this.vectors[7].y = this.minimum.y;
  4357. this.center = this.maximum.add(this.minimum).scale(0.5);
  4358. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4359. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4360. for (var index = 0; index < this.vectors.length; index++) {
  4361. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4362. }
  4363. this.minimumWorld = BABYLON.Vector3.Zero();
  4364. this.maximumWorld = BABYLON.Vector3.Zero();
  4365. this._update(BABYLON.Matrix.Identity());
  4366. }
  4367. BoundingBox.prototype.getWorldMatrix = function () {
  4368. return this._worldMatrix;
  4369. };
  4370. BoundingBox.prototype._update = function (world) {
  4371. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4372. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4373. for (var index = 0; index < this.vectors.length; index++) {
  4374. var v = this.vectorsWorld[index];
  4375. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4376. if (v.x < this.minimumWorld.x)
  4377. this.minimumWorld.x = v.x;
  4378. if (v.y < this.minimumWorld.y)
  4379. this.minimumWorld.y = v.y;
  4380. if (v.z < this.minimumWorld.z)
  4381. this.minimumWorld.z = v.z;
  4382. if (v.x > this.maximumWorld.x)
  4383. this.maximumWorld.x = v.x;
  4384. if (v.y > this.maximumWorld.y)
  4385. this.maximumWorld.y = v.y;
  4386. if (v.z > this.maximumWorld.z)
  4387. this.maximumWorld.z = v.z;
  4388. }
  4389. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4390. this.center.scaleInPlace(0.5);
  4391. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4392. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4393. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4394. this._worldMatrix = world;
  4395. };
  4396. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4397. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4398. };
  4399. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4400. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4401. };
  4402. BoundingBox.prototype.intersectsPoint = function (point) {
  4403. var delta = BABYLON.Engine.Epsilon;
  4404. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4405. return false;
  4406. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4407. return false;
  4408. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4409. return false;
  4410. return true;
  4411. };
  4412. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4413. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4414. };
  4415. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4416. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4417. return false;
  4418. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4419. return false;
  4420. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4421. return false;
  4422. return true;
  4423. };
  4424. BoundingBox.Intersects = function (box0, box1) {
  4425. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4426. return false;
  4427. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4428. return false;
  4429. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4430. return false;
  4431. return true;
  4432. };
  4433. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4434. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4435. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4436. return (num <= (sphereRadius * sphereRadius));
  4437. };
  4438. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4439. for (var p = 0; p < 6; p++) {
  4440. for (var i = 0; i < 8; i++) {
  4441. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4442. return false;
  4443. }
  4444. }
  4445. }
  4446. return true;
  4447. };
  4448. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4449. for (var p = 0; p < 6; p++) {
  4450. var inCount = 8;
  4451. for (var i = 0; i < 8; i++) {
  4452. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4453. --inCount;
  4454. } else {
  4455. break;
  4456. }
  4457. }
  4458. if (inCount == 0)
  4459. return false;
  4460. }
  4461. return true;
  4462. };
  4463. return BoundingBox;
  4464. })();
  4465. BABYLON.BoundingBox = BoundingBox;
  4466. })(BABYLON || (BABYLON = {}));
  4467. var BABYLON;
  4468. (function (BABYLON) {
  4469. var computeBoxExtents = function (axis, box) {
  4470. var p = BABYLON.Vector3.Dot(box.center, axis);
  4471. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4472. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4473. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4474. var r = r0 + r1 + r2;
  4475. return {
  4476. min: p - r,
  4477. max: p + r
  4478. };
  4479. };
  4480. var extentsOverlap = function (min0, max0, min1, max1) {
  4481. return !(min0 > max1 || min1 > max0);
  4482. };
  4483. var axisOverlap = function (axis, box0, box1) {
  4484. var result0 = computeBoxExtents(axis, box0);
  4485. var result1 = computeBoxExtents(axis, box1);
  4486. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4487. };
  4488. var BoundingInfo = (function () {
  4489. function BoundingInfo(minimum, maximum) {
  4490. this.minimum = minimum;
  4491. this.maximum = maximum;
  4492. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4493. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4494. }
  4495. BoundingInfo.prototype._update = function (world) {
  4496. this.boundingBox._update(world);
  4497. this.boundingSphere._update(world);
  4498. };
  4499. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4500. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4501. return false;
  4502. return this.boundingBox.isInFrustum(frustumPlanes);
  4503. };
  4504. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4505. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4506. };
  4507. BoundingInfo.prototype._checkCollision = function (collider) {
  4508. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4509. };
  4510. BoundingInfo.prototype.intersectsPoint = function (point) {
  4511. if (!this.boundingSphere.centerWorld) {
  4512. return false;
  4513. }
  4514. if (!this.boundingSphere.intersectsPoint(point)) {
  4515. return false;
  4516. }
  4517. if (!this.boundingBox.intersectsPoint(point)) {
  4518. return false;
  4519. }
  4520. return true;
  4521. };
  4522. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4523. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4524. return false;
  4525. }
  4526. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4527. return false;
  4528. }
  4529. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4530. return false;
  4531. }
  4532. if (!precise) {
  4533. return true;
  4534. }
  4535. var box0 = this.boundingBox;
  4536. var box1 = boundingInfo.boundingBox;
  4537. if (!axisOverlap(box0.directions[0], box0, box1))
  4538. return false;
  4539. if (!axisOverlap(box0.directions[1], box0, box1))
  4540. return false;
  4541. if (!axisOverlap(box0.directions[2], box0, box1))
  4542. return false;
  4543. if (!axisOverlap(box1.directions[0], box0, box1))
  4544. return false;
  4545. if (!axisOverlap(box1.directions[1], box0, box1))
  4546. return false;
  4547. if (!axisOverlap(box1.directions[2], box0, box1))
  4548. return false;
  4549. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4550. return false;
  4551. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4552. return false;
  4553. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4554. return false;
  4555. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4556. return false;
  4557. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4558. return false;
  4559. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4560. return false;
  4561. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4562. return false;
  4563. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4564. return false;
  4565. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4566. return false;
  4567. return true;
  4568. };
  4569. return BoundingInfo;
  4570. })();
  4571. BABYLON.BoundingInfo = BoundingInfo;
  4572. })(BABYLON || (BABYLON = {}));
  4573. var __extends = this.__extends || function (d, b) {
  4574. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4575. function __() { this.constructor = d; }
  4576. __.prototype = b.prototype;
  4577. d.prototype = new __();
  4578. };
  4579. var BABYLON;
  4580. (function (BABYLON) {
  4581. var Light = (function (_super) {
  4582. __extends(Light, _super);
  4583. function Light(name, scene) {
  4584. _super.call(this, name, scene);
  4585. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4586. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4587. this.intensity = 1.0;
  4588. this.range = Number.MAX_VALUE;
  4589. this.includedOnlyMeshes = new Array();
  4590. this.excludedMeshes = new Array();
  4591. this._excludedMeshesIds = new Array();
  4592. this._includedOnlyMeshesIds = new Array();
  4593. scene.lights.push(this);
  4594. }
  4595. Light.prototype.getShadowGenerator = function () {
  4596. return this._shadowGenerator;
  4597. };
  4598. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4599. };
  4600. Light.prototype._getWorldMatrix = function () {
  4601. return BABYLON.Matrix.Identity();
  4602. };
  4603. Light.prototype.canAffectMesh = function (mesh) {
  4604. if (!mesh) {
  4605. return true;
  4606. }
  4607. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4608. return false;
  4609. }
  4610. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4611. return false;
  4612. }
  4613. return true;
  4614. };
  4615. Light.prototype.getWorldMatrix = function () {
  4616. this._currentRenderId = this.getScene().getRenderId();
  4617. var worldMatrix = this._getWorldMatrix();
  4618. if (this.parent && this.parent.getWorldMatrix) {
  4619. if (!this._parentedWorldMatrix) {
  4620. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4621. }
  4622. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4623. return this._parentedWorldMatrix;
  4624. }
  4625. return worldMatrix;
  4626. };
  4627. Light.prototype.dispose = function () {
  4628. if (this._shadowGenerator) {
  4629. this._shadowGenerator.dispose();
  4630. this._shadowGenerator = null;
  4631. }
  4632. var index = this.getScene().lights.indexOf(this);
  4633. this.getScene().lights.splice(index, 1);
  4634. };
  4635. return Light;
  4636. })(BABYLON.Node);
  4637. BABYLON.Light = Light;
  4638. })(BABYLON || (BABYLON = {}));
  4639. var __extends = this.__extends || function (d, b) {
  4640. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4641. function __() { this.constructor = d; }
  4642. __.prototype = b.prototype;
  4643. d.prototype = new __();
  4644. };
  4645. var BABYLON;
  4646. (function (BABYLON) {
  4647. var PointLight = (function (_super) {
  4648. __extends(PointLight, _super);
  4649. function PointLight(name, position, scene) {
  4650. _super.call(this, name, scene);
  4651. this.position = position;
  4652. }
  4653. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4654. if (this.parent && this.parent.getWorldMatrix) {
  4655. if (!this._transformedPosition) {
  4656. this._transformedPosition = BABYLON.Vector3.Zero();
  4657. }
  4658. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4659. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4660. return;
  4661. }
  4662. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4663. };
  4664. PointLight.prototype.getShadowGenerator = function () {
  4665. return null;
  4666. };
  4667. PointLight.prototype._getWorldMatrix = function () {
  4668. if (!this._worldMatrix) {
  4669. this._worldMatrix = BABYLON.Matrix.Identity();
  4670. }
  4671. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4672. return this._worldMatrix;
  4673. };
  4674. return PointLight;
  4675. })(BABYLON.Light);
  4676. BABYLON.PointLight = PointLight;
  4677. })(BABYLON || (BABYLON = {}));
  4678. var __extends = this.__extends || function (d, b) {
  4679. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4680. function __() { this.constructor = d; }
  4681. __.prototype = b.prototype;
  4682. d.prototype = new __();
  4683. };
  4684. var BABYLON;
  4685. (function (BABYLON) {
  4686. var SpotLight = (function (_super) {
  4687. __extends(SpotLight, _super);
  4688. function SpotLight(name, position, direction, angle, exponent, scene) {
  4689. _super.call(this, name, scene);
  4690. this.position = position;
  4691. this.direction = direction;
  4692. this.angle = angle;
  4693. this.exponent = exponent;
  4694. }
  4695. SpotLight.prototype.setDirectionToTarget = function (target) {
  4696. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4697. return this.direction;
  4698. };
  4699. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4700. var normalizeDirection;
  4701. if (this.parent && this.parent.getWorldMatrix) {
  4702. if (!this._transformedDirection) {
  4703. this._transformedDirection = BABYLON.Vector3.Zero();
  4704. }
  4705. if (!this._transformedPosition) {
  4706. this._transformedPosition = BABYLON.Vector3.Zero();
  4707. }
  4708. var parentWorldMatrix = this.parent.getWorldMatrix();
  4709. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4710. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4711. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4712. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4713. } else {
  4714. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4715. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4716. }
  4717. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4718. };
  4719. SpotLight.prototype._getWorldMatrix = function () {
  4720. if (!this._worldMatrix) {
  4721. this._worldMatrix = BABYLON.Matrix.Identity();
  4722. }
  4723. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4724. return this._worldMatrix;
  4725. };
  4726. return SpotLight;
  4727. })(BABYLON.Light);
  4728. BABYLON.SpotLight = SpotLight;
  4729. })(BABYLON || (BABYLON = {}));
  4730. var __extends = this.__extends || function (d, b) {
  4731. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4732. function __() { this.constructor = d; }
  4733. __.prototype = b.prototype;
  4734. d.prototype = new __();
  4735. };
  4736. var BABYLON;
  4737. (function (BABYLON) {
  4738. var DirectionalLight = (function (_super) {
  4739. __extends(DirectionalLight, _super);
  4740. function DirectionalLight(name, direction, scene) {
  4741. _super.call(this, name, scene);
  4742. this.direction = direction;
  4743. this.position = direction.scale(-1);
  4744. }
  4745. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  4746. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4747. return this.direction;
  4748. };
  4749. DirectionalLight.prototype._computeTransformedPosition = function () {
  4750. if (this.parent && this.parent.getWorldMatrix) {
  4751. if (!this._transformedPosition) {
  4752. this._transformedPosition = BABYLON.Vector3.Zero();
  4753. }
  4754. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4755. return true;
  4756. }
  4757. return false;
  4758. };
  4759. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  4760. if (this.parent && this.parent.getWorldMatrix) {
  4761. if (!this._transformedDirection) {
  4762. this._transformedDirection = BABYLON.Vector3.Zero();
  4763. }
  4764. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  4765. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  4766. return;
  4767. }
  4768. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  4769. };
  4770. DirectionalLight.prototype._getWorldMatrix = function () {
  4771. if (!this._worldMatrix) {
  4772. this._worldMatrix = BABYLON.Matrix.Identity();
  4773. }
  4774. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4775. return this._worldMatrix;
  4776. };
  4777. return DirectionalLight;
  4778. })(BABYLON.Light);
  4779. BABYLON.DirectionalLight = DirectionalLight;
  4780. })(BABYLON || (BABYLON = {}));
  4781. var BABYLON;
  4782. (function (BABYLON) {
  4783. var ShadowGenerator = (function () {
  4784. function ShadowGenerator(mapSize, light) {
  4785. var _this = this;
  4786. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4787. this._darkness = 0;
  4788. this._transparencyShadow = false;
  4789. this._viewMatrix = BABYLON.Matrix.Zero();
  4790. this._projectionMatrix = BABYLON.Matrix.Zero();
  4791. this._transformMatrix = BABYLON.Matrix.Zero();
  4792. this._worldViewProjection = BABYLON.Matrix.Zero();
  4793. this._light = light;
  4794. this._scene = light.getScene();
  4795. light._shadowGenerator = this;
  4796. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  4797. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4798. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  4799. this._shadowMap.renderParticles = false;
  4800. var renderSubMesh = function (subMesh) {
  4801. var mesh = subMesh.getRenderingMesh();
  4802. var scene = _this._scene;
  4803. var engine = scene.getEngine();
  4804. engine.setState(subMesh.getMaterial().backFaceCulling);
  4805. var batch = mesh._getInstancesRenderList(subMesh._id);
  4806. if (batch.mustReturn) {
  4807. return;
  4808. }
  4809. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  4810. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  4811. engine.enableEffect(_this._effect);
  4812. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  4813. var material = subMesh.getMaterial();
  4814. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  4815. if (material && material.needAlphaTesting()) {
  4816. var alphaTexture = material.getAlphaTestTexture();
  4817. _this._effect.setTexture("diffuseSampler", alphaTexture);
  4818. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  4819. }
  4820. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  4821. if (useBones) {
  4822. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  4823. }
  4824. if (hardwareInstancedRendering) {
  4825. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  4826. } else {
  4827. if (batch.renderSelf[subMesh._id]) {
  4828. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  4829. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4830. }
  4831. if (batch.visibleInstances[subMesh._id]) {
  4832. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  4833. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  4834. _this._effect.setMatrix("world", instance.getWorldMatrix());
  4835. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  4836. }
  4837. }
  4838. }
  4839. } else {
  4840. _this._shadowMap.resetRefreshCounter();
  4841. }
  4842. };
  4843. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  4844. var index;
  4845. for (index = 0; index < opaqueSubMeshes.length; index++) {
  4846. renderSubMesh(opaqueSubMeshes.data[index]);
  4847. }
  4848. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  4849. renderSubMesh(alphaTestSubMeshes.data[index]);
  4850. }
  4851. if (_this._transparencyShadow) {
  4852. for (index = 0; index < transparentSubMeshes.length; index++) {
  4853. renderSubMesh(transparentSubMeshes.data[index]);
  4854. }
  4855. }
  4856. };
  4857. }
  4858. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  4859. get: function () {
  4860. return ShadowGenerator._FILTER_NONE;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  4866. get: function () {
  4867. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  4873. get: function () {
  4874. return ShadowGenerator._FILTER_POISSONSAMPLING;
  4875. },
  4876. enumerable: true,
  4877. configurable: true
  4878. });
  4879. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  4880. get: function () {
  4881. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  4882. },
  4883. set: function (value) {
  4884. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  4885. },
  4886. enumerable: true,
  4887. configurable: true
  4888. });
  4889. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  4890. get: function () {
  4891. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  4892. },
  4893. set: function (value) {
  4894. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  4895. },
  4896. enumerable: true,
  4897. configurable: true
  4898. });
  4899. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  4900. var defines = [];
  4901. if (this.useVarianceShadowMap) {
  4902. defines.push("#define VSM");
  4903. }
  4904. var attribs = [BABYLON.VertexBuffer.PositionKind];
  4905. var mesh = subMesh.getMesh();
  4906. var material = subMesh.getMaterial();
  4907. if (material && material.needAlphaTesting()) {
  4908. defines.push("#define ALPHATEST");
  4909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  4910. attribs.push(BABYLON.VertexBuffer.UVKind);
  4911. defines.push("#define UV1");
  4912. }
  4913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  4914. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  4915. defines.push("#define UV2");
  4916. }
  4917. }
  4918. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  4919. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  4920. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  4921. defines.push("#define BONES");
  4922. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  4923. }
  4924. if (useInstances) {
  4925. defines.push("#define INSTANCES");
  4926. attribs.push("world0");
  4927. attribs.push("world1");
  4928. attribs.push("world2");
  4929. attribs.push("world3");
  4930. }
  4931. var join = defines.join("\n");
  4932. if (this._cachedDefines != join) {
  4933. this._cachedDefines = join;
  4934. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  4935. }
  4936. return this._effect.isReady();
  4937. };
  4938. ShadowGenerator.prototype.getShadowMap = function () {
  4939. return this._shadowMap;
  4940. };
  4941. ShadowGenerator.prototype.getLight = function () {
  4942. return this._light;
  4943. };
  4944. ShadowGenerator.prototype.getTransformMatrix = function () {
  4945. var lightPosition = this._light.position;
  4946. var lightDirection = this._light.direction;
  4947. if (this._light._computeTransformedPosition()) {
  4948. lightPosition = this._light._transformedPosition;
  4949. }
  4950. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  4951. this._cachedPosition = lightPosition.clone();
  4952. this._cachedDirection = lightDirection.clone();
  4953. var activeCamera = this._scene.activeCamera;
  4954. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  4955. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  4956. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  4957. }
  4958. return this._transformMatrix;
  4959. };
  4960. ShadowGenerator.prototype.getDarkness = function () {
  4961. return this._darkness;
  4962. };
  4963. ShadowGenerator.prototype.setDarkness = function (darkness) {
  4964. if (darkness >= 1.0)
  4965. this._darkness = 1.0;
  4966. else if (darkness <= 0.0)
  4967. this._darkness = 0.0;
  4968. else
  4969. this._darkness = darkness;
  4970. };
  4971. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  4972. this._transparencyShadow = hasShadow;
  4973. };
  4974. ShadowGenerator.prototype.dispose = function () {
  4975. this._shadowMap.dispose();
  4976. };
  4977. ShadowGenerator._FILTER_NONE = 0;
  4978. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  4979. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  4980. return ShadowGenerator;
  4981. })();
  4982. BABYLON.ShadowGenerator = ShadowGenerator;
  4983. })(BABYLON || (BABYLON = {}));
  4984. var __extends = this.__extends || function (d, b) {
  4985. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4986. function __() { this.constructor = d; }
  4987. __.prototype = b.prototype;
  4988. d.prototype = new __();
  4989. };
  4990. var BABYLON;
  4991. (function (BABYLON) {
  4992. var HemisphericLight = (function (_super) {
  4993. __extends(HemisphericLight, _super);
  4994. function HemisphericLight(name, direction, scene) {
  4995. _super.call(this, name, scene);
  4996. this.direction = direction;
  4997. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  4998. }
  4999. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5000. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5001. return this.direction;
  5002. };
  5003. HemisphericLight.prototype.getShadowGenerator = function () {
  5004. return null;
  5005. };
  5006. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5007. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5008. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5009. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5010. };
  5011. HemisphericLight.prototype._getWorldMatrix = function () {
  5012. if (!this._worldMatrix) {
  5013. this._worldMatrix = BABYLON.Matrix.Identity();
  5014. }
  5015. return this._worldMatrix;
  5016. };
  5017. return HemisphericLight;
  5018. })(BABYLON.Light);
  5019. BABYLON.HemisphericLight = HemisphericLight;
  5020. })(BABYLON || (BABYLON = {}));
  5021. var BABYLON;
  5022. (function (BABYLON) {
  5023. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5024. if (boxMin.x > sphereCenter.x + sphereRadius)
  5025. return false;
  5026. if (sphereCenter.x - sphereRadius > boxMax.x)
  5027. return false;
  5028. if (boxMin.y > sphereCenter.y + sphereRadius)
  5029. return false;
  5030. if (sphereCenter.y - sphereRadius > boxMax.y)
  5031. return false;
  5032. if (boxMin.z > sphereCenter.z + sphereRadius)
  5033. return false;
  5034. if (sphereCenter.z - sphereRadius > boxMax.z)
  5035. return false;
  5036. return true;
  5037. };
  5038. var getLowestRoot = function (a, b, c, maxR) {
  5039. var determinant = b * b - 4.0 * a * c;
  5040. var result = { root: 0, found: false };
  5041. if (determinant < 0)
  5042. return result;
  5043. var sqrtD = Math.sqrt(determinant);
  5044. var r1 = (-b - sqrtD) / (2.0 * a);
  5045. var r2 = (-b + sqrtD) / (2.0 * a);
  5046. if (r1 > r2) {
  5047. var temp = r2;
  5048. r2 = r1;
  5049. r1 = temp;
  5050. }
  5051. if (r1 > 0 && r1 < maxR) {
  5052. result.root = r1;
  5053. result.found = true;
  5054. return result;
  5055. }
  5056. if (r2 > 0 && r2 < maxR) {
  5057. result.root = r2;
  5058. result.found = true;
  5059. return result;
  5060. }
  5061. return result;
  5062. };
  5063. var Collider = (function () {
  5064. function Collider() {
  5065. this.radius = new BABYLON.Vector3(1, 1, 1);
  5066. this.retry = 0;
  5067. this.basePointWorld = BABYLON.Vector3.Zero();
  5068. this.velocityWorld = BABYLON.Vector3.Zero();
  5069. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5070. this._collisionPoint = BABYLON.Vector3.Zero();
  5071. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5072. this._tempVector = BABYLON.Vector3.Zero();
  5073. this._tempVector2 = BABYLON.Vector3.Zero();
  5074. this._tempVector3 = BABYLON.Vector3.Zero();
  5075. this._tempVector4 = BABYLON.Vector3.Zero();
  5076. this._edge = BABYLON.Vector3.Zero();
  5077. this._baseToVertex = BABYLON.Vector3.Zero();
  5078. this._destinationPoint = BABYLON.Vector3.Zero();
  5079. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5080. this._displacementVector = BABYLON.Vector3.Zero();
  5081. }
  5082. Collider.prototype._initialize = function (source, dir, e) {
  5083. this.velocity = dir;
  5084. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5085. this.basePoint = source;
  5086. source.multiplyToRef(this.radius, this.basePointWorld);
  5087. dir.multiplyToRef(this.radius, this.velocityWorld);
  5088. this.velocityWorldLength = this.velocityWorld.length();
  5089. this.epsilon = e;
  5090. this.collisionFound = false;
  5091. };
  5092. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5093. pa.subtractToRef(point, this._tempVector);
  5094. pb.subtractToRef(point, this._tempVector2);
  5095. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5096. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5097. if (d < 0)
  5098. return false;
  5099. pc.subtractToRef(point, this._tempVector3);
  5100. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5101. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5102. if (d < 0)
  5103. return false;
  5104. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5105. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5106. return d >= 0;
  5107. };
  5108. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5109. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5110. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5111. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5112. return false;
  5113. }
  5114. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5115. return false;
  5116. return true;
  5117. };
  5118. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5119. var t0;
  5120. var embeddedInPlane = false;
  5121. if (!subMesh._trianglePlanes) {
  5122. subMesh._trianglePlanes = [];
  5123. }
  5124. if (!subMesh._trianglePlanes[faceIndex]) {
  5125. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5126. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5127. }
  5128. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5129. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5130. return;
  5131. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5132. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5133. if (normalDotVelocity == 0) {
  5134. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5135. return;
  5136. embeddedInPlane = true;
  5137. t0 = 0;
  5138. } else {
  5139. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5140. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5141. if (t0 > t1) {
  5142. var temp = t1;
  5143. t1 = t0;
  5144. t0 = temp;
  5145. }
  5146. if (t0 > 1.0 || t1 < 0.0)
  5147. return;
  5148. if (t0 < 0)
  5149. t0 = 0;
  5150. if (t0 > 1.0)
  5151. t0 = 1.0;
  5152. }
  5153. this._collisionPoint.copyFromFloats(0, 0, 0);
  5154. var found = false;
  5155. var t = 1.0;
  5156. if (!embeddedInPlane) {
  5157. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5158. this.velocity.scaleToRef(t0, this._tempVector);
  5159. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5160. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5161. found = true;
  5162. t = t0;
  5163. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5164. }
  5165. }
  5166. if (!found) {
  5167. var velocitySquaredLength = this.velocity.lengthSquared();
  5168. var a = velocitySquaredLength;
  5169. this.basePoint.subtractToRef(p1, this._tempVector);
  5170. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5171. var c = this._tempVector.lengthSquared() - 1.0;
  5172. var lowestRoot = getLowestRoot(a, b, c, t);
  5173. if (lowestRoot.found) {
  5174. t = lowestRoot.root;
  5175. found = true;
  5176. this._collisionPoint.copyFrom(p1);
  5177. }
  5178. this.basePoint.subtractToRef(p2, this._tempVector);
  5179. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5180. c = this._tempVector.lengthSquared() - 1.0;
  5181. lowestRoot = getLowestRoot(a, b, c, t);
  5182. if (lowestRoot.found) {
  5183. t = lowestRoot.root;
  5184. found = true;
  5185. this._collisionPoint.copyFrom(p2);
  5186. }
  5187. this.basePoint.subtractToRef(p3, this._tempVector);
  5188. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5189. c = this._tempVector.lengthSquared() - 1.0;
  5190. lowestRoot = getLowestRoot(a, b, c, t);
  5191. if (lowestRoot.found) {
  5192. t = lowestRoot.root;
  5193. found = true;
  5194. this._collisionPoint.copyFrom(p3);
  5195. }
  5196. p2.subtractToRef(p1, this._edge);
  5197. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5198. var edgeSquaredLength = this._edge.lengthSquared();
  5199. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5200. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5201. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5202. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5203. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5204. lowestRoot = getLowestRoot(a, b, c, t);
  5205. if (lowestRoot.found) {
  5206. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5207. if (f >= 0.0 && f <= 1.0) {
  5208. t = lowestRoot.root;
  5209. found = true;
  5210. this._edge.scaleInPlace(f);
  5211. p1.addToRef(this._edge, this._collisionPoint);
  5212. }
  5213. }
  5214. p3.subtractToRef(p2, this._edge);
  5215. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5216. edgeSquaredLength = this._edge.lengthSquared();
  5217. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5218. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5219. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5220. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5221. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5222. lowestRoot = getLowestRoot(a, b, c, t);
  5223. if (lowestRoot.found) {
  5224. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5225. if (f >= 0.0 && f <= 1.0) {
  5226. t = lowestRoot.root;
  5227. found = true;
  5228. this._edge.scaleInPlace(f);
  5229. p2.addToRef(this._edge, this._collisionPoint);
  5230. }
  5231. }
  5232. p1.subtractToRef(p3, this._edge);
  5233. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5234. edgeSquaredLength = this._edge.lengthSquared();
  5235. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5236. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5237. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5238. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5239. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5240. lowestRoot = getLowestRoot(a, b, c, t);
  5241. if (lowestRoot.found) {
  5242. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5243. if (f >= 0.0 && f <= 1.0) {
  5244. t = lowestRoot.root;
  5245. found = true;
  5246. this._edge.scaleInPlace(f);
  5247. p3.addToRef(this._edge, this._collisionPoint);
  5248. }
  5249. }
  5250. }
  5251. if (found) {
  5252. var distToCollision = t * this.velocity.length();
  5253. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5254. if (!this.intersectionPoint) {
  5255. this.intersectionPoint = this._collisionPoint.clone();
  5256. } else {
  5257. this.intersectionPoint.copyFrom(this._collisionPoint);
  5258. }
  5259. this.nearestDistance = distToCollision;
  5260. this.collisionFound = true;
  5261. this.collidedMesh = subMesh.getMesh();
  5262. }
  5263. }
  5264. };
  5265. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5266. for (var i = indexStart; i < indexEnd; i += 3) {
  5267. var p1 = pts[indices[i] - decal];
  5268. var p2 = pts[indices[i + 1] - decal];
  5269. var p3 = pts[indices[i + 2] - decal];
  5270. this._testTriangle(i, subMesh, p3, p2, p1);
  5271. }
  5272. };
  5273. Collider.prototype._getResponse = function (pos, vel) {
  5274. pos.addToRef(vel, this._destinationPoint);
  5275. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5276. this.basePoint.addToRef(vel, pos);
  5277. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5278. this._slidePlaneNormal.normalize();
  5279. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5280. pos.addInPlace(this._displacementVector);
  5281. this.intersectionPoint.addInPlace(this._displacementVector);
  5282. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5283. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5284. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5285. };
  5286. return Collider;
  5287. })();
  5288. BABYLON.Collider = Collider;
  5289. })(BABYLON || (BABYLON = {}));
  5290. var __extends = this.__extends || function (d, b) {
  5291. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5292. function __() { this.constructor = d; }
  5293. __.prototype = b.prototype;
  5294. d.prototype = new __();
  5295. };
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var Camera = (function (_super) {
  5299. __extends(Camera, _super);
  5300. function Camera(name, position, scene) {
  5301. _super.call(this, name, scene);
  5302. this.position = position;
  5303. this.upVector = BABYLON.Vector3.Up();
  5304. this.orthoLeft = null;
  5305. this.orthoRight = null;
  5306. this.orthoBottom = null;
  5307. this.orthoTop = null;
  5308. this.fov = 0.8;
  5309. this.minZ = 1.0;
  5310. this.maxZ = 10000.0;
  5311. this.inertia = 0.9;
  5312. this.mode = Camera.PERSPECTIVE_CAMERA;
  5313. this.isIntermediate = false;
  5314. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5315. this.subCameras = [];
  5316. this.layerMask = 0xFFFFFFFF;
  5317. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5318. this._projectionMatrix = new BABYLON.Matrix();
  5319. this._postProcesses = new Array();
  5320. this._postProcessesTakenIndices = [];
  5321. scene.cameras.push(this);
  5322. if (!scene.activeCamera) {
  5323. scene.activeCamera = this;
  5324. }
  5325. }
  5326. Camera.prototype._initCache = function () {
  5327. _super.prototype._initCache.call(this);
  5328. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5329. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5330. this._cache.mode = undefined;
  5331. this._cache.minZ = undefined;
  5332. this._cache.maxZ = undefined;
  5333. this._cache.fov = undefined;
  5334. this._cache.aspectRatio = undefined;
  5335. this._cache.orthoLeft = undefined;
  5336. this._cache.orthoRight = undefined;
  5337. this._cache.orthoBottom = undefined;
  5338. this._cache.orthoTop = undefined;
  5339. this._cache.renderWidth = undefined;
  5340. this._cache.renderHeight = undefined;
  5341. };
  5342. Camera.prototype._updateCache = function (ignoreParentClass) {
  5343. if (!ignoreParentClass) {
  5344. _super.prototype._updateCache.call(this);
  5345. }
  5346. var engine = this.getEngine();
  5347. this._cache.position.copyFrom(this.position);
  5348. this._cache.upVector.copyFrom(this.upVector);
  5349. this._cache.mode = this.mode;
  5350. this._cache.minZ = this.minZ;
  5351. this._cache.maxZ = this.maxZ;
  5352. this._cache.fov = this.fov;
  5353. this._cache.aspectRatio = engine.getAspectRatio(this);
  5354. this._cache.orthoLeft = this.orthoLeft;
  5355. this._cache.orthoRight = this.orthoRight;
  5356. this._cache.orthoBottom = this.orthoBottom;
  5357. this._cache.orthoTop = this.orthoTop;
  5358. this._cache.renderWidth = engine.getRenderWidth();
  5359. this._cache.renderHeight = engine.getRenderHeight();
  5360. };
  5361. Camera.prototype._updateFromScene = function () {
  5362. this.updateCache();
  5363. this._update();
  5364. };
  5365. Camera.prototype._isSynchronized = function () {
  5366. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5367. };
  5368. Camera.prototype._isSynchronizedViewMatrix = function () {
  5369. if (!_super.prototype._isSynchronized.call(this))
  5370. return false;
  5371. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5372. };
  5373. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5374. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5375. if (!check) {
  5376. return false;
  5377. }
  5378. var engine = this.getEngine();
  5379. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5380. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5381. } else {
  5382. 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();
  5383. }
  5384. return check;
  5385. };
  5386. Camera.prototype.attachControl = function (element) {
  5387. };
  5388. Camera.prototype.detachControl = function (element) {
  5389. };
  5390. Camera.prototype._update = function () {
  5391. };
  5392. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5393. if (typeof insertAt === "undefined") { insertAt = null; }
  5394. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5395. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5396. return 0;
  5397. }
  5398. if (insertAt == null || insertAt < 0) {
  5399. this._postProcesses.push(postProcess);
  5400. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5401. return this._postProcesses.length - 1;
  5402. }
  5403. var add = 0;
  5404. if (this._postProcesses[insertAt]) {
  5405. var start = this._postProcesses.length - 1;
  5406. for (var i = start; i >= insertAt + 1; --i) {
  5407. this._postProcesses[i + 1] = this._postProcesses[i];
  5408. }
  5409. add = 1;
  5410. }
  5411. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5412. if (this._postProcessesTakenIndices[i] < insertAt) {
  5413. continue;
  5414. }
  5415. start = this._postProcessesTakenIndices.length - 1;
  5416. for (var j = start; j >= i; --j) {
  5417. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5418. }
  5419. this._postProcessesTakenIndices[i] = insertAt;
  5420. break;
  5421. }
  5422. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5423. this._postProcessesTakenIndices.push(insertAt);
  5424. }
  5425. var result = insertAt + add;
  5426. this._postProcesses[result] = postProcess;
  5427. return result;
  5428. };
  5429. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5430. if (typeof atIndices === "undefined") { atIndices = null; }
  5431. var result = [];
  5432. if (!atIndices) {
  5433. var length = this._postProcesses.length;
  5434. for (var i = 0; i < length; i++) {
  5435. if (this._postProcesses[i] !== postProcess) {
  5436. continue;
  5437. }
  5438. delete this._postProcesses[i];
  5439. var index = this._postProcessesTakenIndices.indexOf(i);
  5440. this._postProcessesTakenIndices.splice(index, 1);
  5441. }
  5442. } else {
  5443. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5444. for (i = 0; i < atIndices.length; i++) {
  5445. var foundPostProcess = this._postProcesses[atIndices[i]];
  5446. if (foundPostProcess !== postProcess) {
  5447. result.push(i);
  5448. continue;
  5449. }
  5450. delete this._postProcesses[atIndices[i]];
  5451. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5452. this._postProcessesTakenIndices.splice(index, 1);
  5453. }
  5454. }
  5455. return result;
  5456. };
  5457. Camera.prototype.getWorldMatrix = function () {
  5458. if (!this._worldMatrix) {
  5459. this._worldMatrix = BABYLON.Matrix.Identity();
  5460. }
  5461. var viewMatrix = this.getViewMatrix();
  5462. viewMatrix.invertToRef(this._worldMatrix);
  5463. return this._worldMatrix;
  5464. };
  5465. Camera.prototype._getViewMatrix = function () {
  5466. return BABYLON.Matrix.Identity();
  5467. };
  5468. Camera.prototype.getViewMatrix = function () {
  5469. this._computedViewMatrix = this._computeViewMatrix();
  5470. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5471. return this._computedViewMatrix;
  5472. }
  5473. if (!this._worldMatrix) {
  5474. this._worldMatrix = BABYLON.Matrix.Identity();
  5475. }
  5476. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5477. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5478. this._computedViewMatrix.invert();
  5479. this._currentRenderId = this.getScene().getRenderId();
  5480. return this._computedViewMatrix;
  5481. };
  5482. Camera.prototype._computeViewMatrix = function (force) {
  5483. if (!force && this._isSynchronizedViewMatrix()) {
  5484. return this._computedViewMatrix;
  5485. }
  5486. this._computedViewMatrix = this._getViewMatrix();
  5487. if (!this.parent || !this.parent.getWorldMatrix) {
  5488. this._currentRenderId = this.getScene().getRenderId();
  5489. }
  5490. return this._computedViewMatrix;
  5491. };
  5492. Camera.prototype.getProjectionMatrix = function (force) {
  5493. if (!force && this._isSynchronizedProjectionMatrix()) {
  5494. return this._projectionMatrix;
  5495. }
  5496. var engine = this.getEngine();
  5497. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5498. if (this.minZ <= 0) {
  5499. this.minZ = 0.1;
  5500. }
  5501. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5502. return this._projectionMatrix;
  5503. }
  5504. var halfWidth = engine.getRenderWidth() / 2.0;
  5505. var halfHeight = engine.getRenderHeight() / 2.0;
  5506. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5507. return this._projectionMatrix;
  5508. };
  5509. Camera.prototype.dispose = function () {
  5510. var index = this.getScene().cameras.indexOf(this);
  5511. this.getScene().cameras.splice(index, 1);
  5512. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5513. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5514. }
  5515. };
  5516. Camera.PERSPECTIVE_CAMERA = 0;
  5517. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5518. return Camera;
  5519. })(BABYLON.Node);
  5520. BABYLON.Camera = Camera;
  5521. })(BABYLON || (BABYLON = {}));
  5522. var __extends = this.__extends || function (d, b) {
  5523. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5524. function __() { this.constructor = d; }
  5525. __.prototype = b.prototype;
  5526. d.prototype = new __();
  5527. };
  5528. var BABYLON;
  5529. (function (BABYLON) {
  5530. var TargetCamera = (function (_super) {
  5531. __extends(TargetCamera, _super);
  5532. function TargetCamera(name, position, scene) {
  5533. _super.call(this, name, position, scene);
  5534. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5535. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5536. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5537. this.speed = 2.0;
  5538. this.noRotationConstraint = false;
  5539. this.lockedTarget = null;
  5540. this._currentTarget = BABYLON.Vector3.Zero();
  5541. this._viewMatrix = BABYLON.Matrix.Zero();
  5542. this._camMatrix = BABYLON.Matrix.Zero();
  5543. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5544. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5545. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5546. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5547. this._lookAtTemp = BABYLON.Matrix.Zero();
  5548. this._tempMatrix = BABYLON.Matrix.Zero();
  5549. }
  5550. TargetCamera.prototype._getLockedTargetPosition = function () {
  5551. if (!this.lockedTarget) {
  5552. return null;
  5553. }
  5554. return this.lockedTarget.position || this.lockedTarget;
  5555. };
  5556. TargetCamera.prototype._initCache = function () {
  5557. _super.prototype._initCache.call(this);
  5558. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5559. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5560. };
  5561. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5562. if (!ignoreParentClass) {
  5563. _super.prototype._updateCache.call(this);
  5564. }
  5565. var lockedTargetPosition = this._getLockedTargetPosition();
  5566. if (!lockedTargetPosition) {
  5567. this._cache.lockedTarget = null;
  5568. } else {
  5569. if (!this._cache.lockedTarget) {
  5570. this._cache.lockedTarget = lockedTargetPosition.clone();
  5571. } else {
  5572. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5573. }
  5574. }
  5575. this._cache.rotation.copyFrom(this.rotation);
  5576. };
  5577. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5578. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5579. return false;
  5580. }
  5581. var lockedTargetPosition = this._getLockedTargetPosition();
  5582. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5583. };
  5584. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5585. return this.speed * ((BABYLON.Tools.GetDeltaTime() / (BABYLON.Tools.GetFps() * 10.0)));
  5586. };
  5587. TargetCamera.prototype.setTarget = function (target) {
  5588. this.upVector.normalize();
  5589. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5590. this._camMatrix.invert();
  5591. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5592. var vDir = target.subtract(this.position);
  5593. if (vDir.x >= 0.0) {
  5594. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5595. } else {
  5596. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5597. }
  5598. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5599. if (isNaN(this.rotation.x)) {
  5600. this.rotation.x = 0;
  5601. }
  5602. if (isNaN(this.rotation.y)) {
  5603. this.rotation.y = 0;
  5604. }
  5605. if (isNaN(this.rotation.z)) {
  5606. this.rotation.z = 0;
  5607. }
  5608. };
  5609. TargetCamera.prototype.getTarget = function () {
  5610. return this._currentTarget;
  5611. };
  5612. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5613. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5614. };
  5615. TargetCamera.prototype._updatePosition = function () {
  5616. this.position.addInPlace(this.cameraDirection);
  5617. };
  5618. TargetCamera.prototype._update = function () {
  5619. var needToMove = this._decideIfNeedsToMove();
  5620. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5621. if (needToMove) {
  5622. this._updatePosition();
  5623. }
  5624. if (needToRotate) {
  5625. this.rotation.x += this.cameraRotation.x;
  5626. this.rotation.y += this.cameraRotation.y;
  5627. if (!this.noRotationConstraint) {
  5628. var limit = (Math.PI / 2) * 0.95;
  5629. if (this.rotation.x > limit)
  5630. this.rotation.x = limit;
  5631. if (this.rotation.x < -limit)
  5632. this.rotation.x = -limit;
  5633. }
  5634. }
  5635. if (needToMove) {
  5636. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5637. this.cameraDirection.x = 0;
  5638. }
  5639. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5640. this.cameraDirection.y = 0;
  5641. }
  5642. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5643. this.cameraDirection.z = 0;
  5644. }
  5645. this.cameraDirection.scaleInPlace(this.inertia);
  5646. }
  5647. if (needToRotate) {
  5648. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5649. this.cameraRotation.x = 0;
  5650. }
  5651. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5652. this.cameraRotation.y = 0;
  5653. }
  5654. this.cameraRotation.scaleInPlace(this.inertia);
  5655. }
  5656. };
  5657. TargetCamera.prototype._getViewMatrix = function () {
  5658. if (!this.lockedTarget) {
  5659. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5660. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5661. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5662. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5663. this._lookAtTemp.invert();
  5664. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5665. } else {
  5666. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5667. }
  5668. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5669. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5670. } else {
  5671. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5672. }
  5673. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5674. return this._viewMatrix;
  5675. };
  5676. return TargetCamera;
  5677. })(BABYLON.Camera);
  5678. BABYLON.TargetCamera = TargetCamera;
  5679. })(BABYLON || (BABYLON = {}));
  5680. var __extends = this.__extends || function (d, b) {
  5681. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5682. function __() { this.constructor = d; }
  5683. __.prototype = b.prototype;
  5684. d.prototype = new __();
  5685. };
  5686. var BABYLON;
  5687. (function (BABYLON) {
  5688. var FollowCamera = (function (_super) {
  5689. __extends(FollowCamera, _super);
  5690. function FollowCamera(name, position, scene) {
  5691. _super.call(this, name, position, scene);
  5692. this.radius = 12;
  5693. this.rotationOffset = 0;
  5694. this.heightOffset = 4;
  5695. this.cameraAcceleration = 0.05;
  5696. this.maxCameraSpeed = 20;
  5697. }
  5698. FollowCamera.prototype.getRadians = function (degrees) {
  5699. return degrees * Math.PI / 180;
  5700. };
  5701. FollowCamera.prototype.follow = function (cameraTarget) {
  5702. if (!cameraTarget)
  5703. return;
  5704. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5705. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5706. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5707. var dx = targetX - this.position.x;
  5708. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5709. var dz = (targetZ) - this.position.z;
  5710. var vx = dx * this.cameraAcceleration * 2;
  5711. var vy = dy * this.cameraAcceleration;
  5712. var vz = dz * this.cameraAcceleration * 2;
  5713. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5714. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5715. }
  5716. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5717. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5718. }
  5719. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5720. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5721. }
  5722. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5723. this.setTarget(cameraTarget.position);
  5724. };
  5725. FollowCamera.prototype._update = function () {
  5726. _super.prototype._update.call(this);
  5727. this.follow(this.target);
  5728. };
  5729. return FollowCamera;
  5730. })(BABYLON.TargetCamera);
  5731. BABYLON.FollowCamera = FollowCamera;
  5732. })(BABYLON || (BABYLON = {}));
  5733. var __extends = this.__extends || function (d, b) {
  5734. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5735. function __() { this.constructor = d; }
  5736. __.prototype = b.prototype;
  5737. d.prototype = new __();
  5738. };
  5739. var BABYLON;
  5740. (function (BABYLON) {
  5741. var FreeCamera = (function (_super) {
  5742. __extends(FreeCamera, _super);
  5743. function FreeCamera(name, position, scene) {
  5744. _super.call(this, name, position, scene);
  5745. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  5746. this.keysUp = [38];
  5747. this.keysDown = [40];
  5748. this.keysLeft = [37];
  5749. this.keysRight = [39];
  5750. this.checkCollisions = false;
  5751. this.applyGravity = false;
  5752. this.angularSensibility = 2000.0;
  5753. this._keys = [];
  5754. this._collider = new BABYLON.Collider();
  5755. this._needMoveForGravity = true;
  5756. this._oldPosition = BABYLON.Vector3.Zero();
  5757. this._diffPosition = BABYLON.Vector3.Zero();
  5758. this._newPosition = BABYLON.Vector3.Zero();
  5759. }
  5760. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  5761. var _this = this;
  5762. var previousPosition;
  5763. var engine = this.getEngine();
  5764. if (this._attachedElement) {
  5765. return;
  5766. }
  5767. this._attachedElement = element;
  5768. if (this._onMouseDown === undefined) {
  5769. this._onMouseDown = function (evt) {
  5770. previousPosition = {
  5771. x: evt.clientX,
  5772. y: evt.clientY
  5773. };
  5774. if (!noPreventDefault) {
  5775. evt.preventDefault();
  5776. }
  5777. };
  5778. this._onMouseUp = function (evt) {
  5779. previousPosition = null;
  5780. if (!noPreventDefault) {
  5781. evt.preventDefault();
  5782. }
  5783. };
  5784. this._onMouseOut = function (evt) {
  5785. previousPosition = null;
  5786. _this._keys = [];
  5787. if (!noPreventDefault) {
  5788. evt.preventDefault();
  5789. }
  5790. };
  5791. this._onMouseMove = function (evt) {
  5792. if (!previousPosition && !engine.isPointerLock) {
  5793. return;
  5794. }
  5795. var offsetX;
  5796. var offsetY;
  5797. if (!engine.isPointerLock) {
  5798. offsetX = evt.clientX - previousPosition.x;
  5799. offsetY = evt.clientY - previousPosition.y;
  5800. } else {
  5801. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  5802. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  5803. }
  5804. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  5805. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  5806. previousPosition = {
  5807. x: evt.clientX,
  5808. y: evt.clientY
  5809. };
  5810. if (!noPreventDefault) {
  5811. evt.preventDefault();
  5812. }
  5813. };
  5814. this._onKeyDown = function (evt) {
  5815. 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) {
  5816. var index = _this._keys.indexOf(evt.keyCode);
  5817. if (index === -1) {
  5818. _this._keys.push(evt.keyCode);
  5819. }
  5820. if (!noPreventDefault) {
  5821. evt.preventDefault();
  5822. }
  5823. }
  5824. };
  5825. this._onKeyUp = function (evt) {
  5826. 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) {
  5827. var index = _this._keys.indexOf(evt.keyCode);
  5828. if (index >= 0) {
  5829. _this._keys.splice(index, 1);
  5830. }
  5831. if (!noPreventDefault) {
  5832. evt.preventDefault();
  5833. }
  5834. }
  5835. };
  5836. this._onLostFocus = function () {
  5837. _this._keys = [];
  5838. };
  5839. this._reset = function () {
  5840. _this._keys = [];
  5841. previousPosition = null;
  5842. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5843. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  5844. };
  5845. }
  5846. element.addEventListener("mousedown", this._onMouseDown, false);
  5847. element.addEventListener("mouseup", this._onMouseUp, false);
  5848. element.addEventListener("mouseout", this._onMouseOut, false);
  5849. element.addEventListener("mousemove", this._onMouseMove, false);
  5850. BABYLON.Tools.RegisterTopRootEvents([
  5851. { name: "keydown", handler: this._onKeyDown },
  5852. { name: "keyup", handler: this._onKeyUp },
  5853. { name: "blur", handler: this._onLostFocus }
  5854. ]);
  5855. };
  5856. FreeCamera.prototype.detachControl = function (element) {
  5857. if (this._attachedElement != element) {
  5858. return;
  5859. }
  5860. element.removeEventListener("mousedown", this._onMouseDown);
  5861. element.removeEventListener("mouseup", this._onMouseUp);
  5862. element.removeEventListener("mouseout", this._onMouseOut);
  5863. element.removeEventListener("mousemove", this._onMouseMove);
  5864. BABYLON.Tools.UnregisterTopRootEvents([
  5865. { name: "keydown", handler: this._onKeyDown },
  5866. { name: "keyup", handler: this._onKeyUp },
  5867. { name: "blur", handler: this._onLostFocus }
  5868. ]);
  5869. this._attachedElement = null;
  5870. if (this._reset) {
  5871. this._reset();
  5872. }
  5873. };
  5874. FreeCamera.prototype._collideWithWorld = function (velocity) {
  5875. var globalPosition;
  5876. if (this.parent) {
  5877. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  5878. } else {
  5879. globalPosition = this.position;
  5880. }
  5881. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  5882. this._collider.radius = this.ellipsoid;
  5883. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  5884. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  5885. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  5886. this.position.addInPlace(this._diffPosition);
  5887. if (this.onCollide) {
  5888. this.onCollide(this._collider.collidedMesh);
  5889. }
  5890. }
  5891. };
  5892. FreeCamera.prototype._checkInputs = function () {
  5893. if (!this._localDirection) {
  5894. this._localDirection = BABYLON.Vector3.Zero();
  5895. this._transformedDirection = BABYLON.Vector3.Zero();
  5896. }
  5897. for (var index = 0; index < this._keys.length; index++) {
  5898. var keyCode = this._keys[index];
  5899. var speed = this._computeLocalCameraSpeed();
  5900. if (this.keysLeft.indexOf(keyCode) !== -1) {
  5901. this._localDirection.copyFromFloats(-speed, 0, 0);
  5902. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  5903. this._localDirection.copyFromFloats(0, 0, speed);
  5904. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  5905. this._localDirection.copyFromFloats(speed, 0, 0);
  5906. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  5907. this._localDirection.copyFromFloats(0, 0, -speed);
  5908. }
  5909. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  5910. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  5911. this.cameraDirection.addInPlace(this._transformedDirection);
  5912. }
  5913. };
  5914. FreeCamera.prototype._decideIfNeedsToMove = function () {
  5915. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5916. };
  5917. FreeCamera.prototype._updatePosition = function () {
  5918. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  5919. this._collideWithWorld(this.cameraDirection);
  5920. if (this.applyGravity) {
  5921. var oldPosition = this.position;
  5922. this._collideWithWorld(this.getScene().gravity);
  5923. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  5924. }
  5925. } else {
  5926. this.position.addInPlace(this.cameraDirection);
  5927. }
  5928. };
  5929. FreeCamera.prototype._update = function () {
  5930. this._checkInputs();
  5931. _super.prototype._update.call(this);
  5932. };
  5933. return FreeCamera;
  5934. })(BABYLON.TargetCamera);
  5935. BABYLON.FreeCamera = FreeCamera;
  5936. })(BABYLON || (BABYLON = {}));
  5937. var __extends = this.__extends || function (d, b) {
  5938. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5939. function __() { this.constructor = d; }
  5940. __.prototype = b.prototype;
  5941. d.prototype = new __();
  5942. };
  5943. var BABYLON;
  5944. (function (BABYLON) {
  5945. var TouchCamera = (function (_super) {
  5946. __extends(TouchCamera, _super);
  5947. function TouchCamera(name, position, scene) {
  5948. _super.call(this, name, position, scene);
  5949. this._offsetX = null;
  5950. this._offsetY = null;
  5951. this._pointerCount = 0;
  5952. this._pointerPressed = [];
  5953. this.angularSensibility = 200000.0;
  5954. this.moveSensibility = 500.0;
  5955. }
  5956. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  5957. var _this = this;
  5958. var previousPosition;
  5959. if (this._attachedCanvas) {
  5960. return;
  5961. }
  5962. this._attachedCanvas = canvas;
  5963. if (this._onPointerDown === undefined) {
  5964. this._onPointerDown = function (evt) {
  5965. if (!noPreventDefault) {
  5966. evt.preventDefault();
  5967. }
  5968. _this._pointerPressed.push(evt.pointerId);
  5969. if (_this._pointerPressed.length !== 1) {
  5970. return;
  5971. }
  5972. previousPosition = {
  5973. x: evt.clientX,
  5974. y: evt.clientY
  5975. };
  5976. };
  5977. this._onPointerUp = function (evt) {
  5978. if (!noPreventDefault) {
  5979. evt.preventDefault();
  5980. }
  5981. var index = _this._pointerPressed.indexOf(evt.pointerId);
  5982. if (index === -1) {
  5983. return;
  5984. }
  5985. _this._pointerPressed.splice(index, 1);
  5986. if (index != 0) {
  5987. return;
  5988. }
  5989. previousPosition = null;
  5990. _this._offsetX = null;
  5991. _this._offsetY = null;
  5992. };
  5993. this._onPointerMove = function (evt) {
  5994. if (!noPreventDefault) {
  5995. evt.preventDefault();
  5996. }
  5997. if (!previousPosition) {
  5998. return;
  5999. }
  6000. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6001. if (index != 0) {
  6002. return;
  6003. }
  6004. _this._offsetX = evt.clientX - previousPosition.x;
  6005. _this._offsetY = -(evt.clientY - previousPosition.y);
  6006. };
  6007. this._onLostFocus = function () {
  6008. _this._offsetX = null;
  6009. _this._offsetY = null;
  6010. };
  6011. }
  6012. canvas.addEventListener("pointerdown", this._onPointerDown);
  6013. canvas.addEventListener("pointerup", this._onPointerUp);
  6014. canvas.addEventListener("pointerout", this._onPointerUp);
  6015. canvas.addEventListener("pointermove", this._onPointerMove);
  6016. BABYLON.Tools.RegisterTopRootEvents([
  6017. { name: "blur", handler: this._onLostFocus }
  6018. ]);
  6019. };
  6020. TouchCamera.prototype.detachControl = function (canvas) {
  6021. if (this._attachedCanvas != canvas) {
  6022. return;
  6023. }
  6024. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6025. canvas.removeEventListener("pointerup", this._onPointerUp);
  6026. canvas.removeEventListener("pointerout", this._onPointerUp);
  6027. canvas.removeEventListener("pointermove", this._onPointerMove);
  6028. BABYLON.Tools.UnregisterTopRootEvents([
  6029. { name: "blur", handler: this._onLostFocus }
  6030. ]);
  6031. this._attachedCanvas = null;
  6032. };
  6033. TouchCamera.prototype._checkInputs = function () {
  6034. if (!this._offsetX) {
  6035. return;
  6036. }
  6037. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6038. if (this._pointerPressed.length > 1) {
  6039. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6040. } else {
  6041. var speed = this._computeLocalCameraSpeed();
  6042. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6043. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6044. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6045. }
  6046. };
  6047. return TouchCamera;
  6048. })(BABYLON.FreeCamera);
  6049. BABYLON.TouchCamera = TouchCamera;
  6050. })(BABYLON || (BABYLON = {}));
  6051. var __extends = this.__extends || function (d, b) {
  6052. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6053. function __() { this.constructor = d; }
  6054. __.prototype = b.prototype;
  6055. d.prototype = new __();
  6056. };
  6057. var BABYLON;
  6058. (function (BABYLON) {
  6059. var DeviceOrientationCamera = (function (_super) {
  6060. __extends(DeviceOrientationCamera, _super);
  6061. function DeviceOrientationCamera(name, position, scene) {
  6062. var _this = this;
  6063. _super.call(this, name, position, scene);
  6064. this._offsetX = null;
  6065. this._offsetY = null;
  6066. this._orientationGamma = 0;
  6067. this._orientationBeta = 0;
  6068. this._initialOrientationGamma = 0;
  6069. this._initialOrientationBeta = 0;
  6070. this.angularSensibility = 10000.0;
  6071. this.moveSensibility = 50.0;
  6072. window.addEventListener("resize", function () {
  6073. _this._initialOrientationGamma = null;
  6074. }, false);
  6075. }
  6076. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6077. var _this = this;
  6078. if (this._attachedCanvas) {
  6079. return;
  6080. }
  6081. this._attachedCanvas = canvas;
  6082. if (!this._orientationChanged) {
  6083. this._orientationChanged = function (evt) {
  6084. if (!_this._initialOrientationGamma) {
  6085. _this._initialOrientationGamma = evt.gamma;
  6086. _this._initialOrientationBeta = evt.beta;
  6087. }
  6088. _this._orientationGamma = evt.gamma;
  6089. _this._orientationBeta = evt.beta;
  6090. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6091. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6092. };
  6093. }
  6094. window.addEventListener("deviceorientation", this._orientationChanged);
  6095. };
  6096. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6097. if (this._attachedCanvas != canvas) {
  6098. return;
  6099. }
  6100. window.removeEventListener("deviceorientation", this._orientationChanged);
  6101. this._attachedCanvas = null;
  6102. this._orientationGamma = 0;
  6103. this._orientationBeta = 0;
  6104. this._initialOrientationGamma = 0;
  6105. this._initialOrientationBeta = 0;
  6106. };
  6107. DeviceOrientationCamera.prototype._checkInputs = function () {
  6108. if (!this._offsetX) {
  6109. return;
  6110. }
  6111. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6112. var speed = this._computeLocalCameraSpeed();
  6113. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6114. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6115. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6116. };
  6117. return DeviceOrientationCamera;
  6118. })(BABYLON.FreeCamera);
  6119. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6120. })(BABYLON || (BABYLON = {}));
  6121. var __extends = this.__extends || function (d, b) {
  6122. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  6123. function __() { this.constructor = d; }
  6124. __.prototype = b.prototype;
  6125. d.prototype = new __();
  6126. };
  6127. var BABYLON;
  6128. (function (BABYLON) {
  6129. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6130. var ArcRotateCamera = (function (_super) {
  6131. __extends(ArcRotateCamera, _super);
  6132. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6133. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6134. this.alpha = alpha;
  6135. this.beta = beta;
  6136. this.radius = radius;
  6137. this.target = target;
  6138. this.inertialAlphaOffset = 0;
  6139. this.inertialBetaOffset = 0;
  6140. this.inertialRadiusOffset = 0;
  6141. this.lowerAlphaLimit = null;
  6142. this.upperAlphaLimit = null;
  6143. this.lowerBetaLimit = 0.01;
  6144. this.upperBetaLimit = Math.PI;
  6145. this.lowerRadiusLimit = null;
  6146. this.upperRadiusLimit = null;
  6147. this.angularSensibility = 1000.0;
  6148. this.wheelPrecision = 3.0;
  6149. this.keysUp = [38];
  6150. this.keysDown = [40];
  6151. this.keysLeft = [37];
  6152. this.keysRight = [39];
  6153. this.zoomOnFactor = 1;
  6154. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6155. this._keys = [];
  6156. this._viewMatrix = new BABYLON.Matrix();
  6157. this.checkCollisions = false;
  6158. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6159. this._collider = new BABYLON.Collider();
  6160. this._previousPosition = BABYLON.Vector3.Zero();
  6161. this._collisionVelocity = BABYLON.Vector3.Zero();
  6162. this._newPosition = BABYLON.Vector3.Zero();
  6163. this.pinchPrecision = 20;
  6164. this.getViewMatrix();
  6165. }
  6166. ArcRotateCamera.prototype._getTargetPosition = function () {
  6167. return this.target.position || this.target;
  6168. };
  6169. ArcRotateCamera.prototype._initCache = function () {
  6170. _super.prototype._initCache.call(this);
  6171. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6172. this._cache.alpha = undefined;
  6173. this._cache.beta = undefined;
  6174. this._cache.radius = undefined;
  6175. this._cache.targetScreenOffset = undefined;
  6176. };
  6177. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6178. if (!ignoreParentClass) {
  6179. _super.prototype._updateCache.call(this);
  6180. }
  6181. this._cache.target.copyFrom(this._getTargetPosition());
  6182. this._cache.alpha = this.alpha;
  6183. this._cache.beta = this.beta;
  6184. this._cache.radius = this.radius;
  6185. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6186. };
  6187. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6188. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6189. return false;
  6190. 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);
  6191. };
  6192. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6193. var _this = this;
  6194. var previousPosition;
  6195. var pointerId;
  6196. var pinchStarted = false;
  6197. var pinchPointX1, pinchPointX2;
  6198. if (this._attachedElement) {
  6199. return;
  6200. }
  6201. this._attachedElement = element;
  6202. var engine = this.getEngine();
  6203. if (this._onPointerDown === undefined) {
  6204. this._onPointerDown = function (evt) {
  6205. if (pointerId) {
  6206. return;
  6207. }
  6208. pointerId = evt.pointerId;
  6209. previousPosition = {
  6210. x: evt.clientX,
  6211. y: evt.clientY
  6212. };
  6213. if (!noPreventDefault) {
  6214. evt.preventDefault();
  6215. }
  6216. };
  6217. this._onPointerUp = function (evt) {
  6218. previousPosition = null;
  6219. pointerId = null;
  6220. if (!noPreventDefault) {
  6221. evt.preventDefault();
  6222. }
  6223. };
  6224. this._onPointerMove = function (evt) {
  6225. if (!previousPosition) {
  6226. return;
  6227. }
  6228. if (pointerId !== evt.pointerId) {
  6229. return;
  6230. }
  6231. if (pinchStarted) {
  6232. return;
  6233. }
  6234. var offsetX = evt.clientX - previousPosition.x;
  6235. var offsetY = evt.clientY - previousPosition.y;
  6236. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6237. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6238. previousPosition = {
  6239. x: evt.clientX,
  6240. y: evt.clientY
  6241. };
  6242. if (!noPreventDefault) {
  6243. evt.preventDefault();
  6244. }
  6245. };
  6246. this._onMouseMove = function (evt) {
  6247. if (!engine.isPointerLock) {
  6248. return;
  6249. }
  6250. if (pinchStarted) {
  6251. return;
  6252. }
  6253. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6254. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6255. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6256. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6257. if (!noPreventDefault) {
  6258. evt.preventDefault();
  6259. }
  6260. };
  6261. this._wheel = function (event) {
  6262. var delta = 0;
  6263. if (event.wheelDelta) {
  6264. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6265. } else if (event.detail) {
  6266. delta = -event.detail / _this.wheelPrecision;
  6267. }
  6268. if (delta)
  6269. _this.inertialRadiusOffset += delta;
  6270. if (event.preventDefault) {
  6271. if (!noPreventDefault) {
  6272. event.preventDefault();
  6273. }
  6274. }
  6275. };
  6276. this._onKeyDown = function (evt) {
  6277. 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) {
  6278. var index = _this._keys.indexOf(evt.keyCode);
  6279. if (index === -1) {
  6280. _this._keys.push(evt.keyCode);
  6281. }
  6282. if (evt.preventDefault) {
  6283. if (!noPreventDefault) {
  6284. evt.preventDefault();
  6285. }
  6286. }
  6287. }
  6288. };
  6289. this._onKeyUp = function (evt) {
  6290. 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) {
  6291. var index = _this._keys.indexOf(evt.keyCode);
  6292. if (index >= 0) {
  6293. _this._keys.splice(index, 1);
  6294. }
  6295. if (evt.preventDefault) {
  6296. if (!noPreventDefault) {
  6297. evt.preventDefault();
  6298. }
  6299. }
  6300. }
  6301. };
  6302. this._onLostFocus = function () {
  6303. _this._keys = [];
  6304. pointerId = null;
  6305. };
  6306. this._onGestureStart = function (e) {
  6307. if (window.MSGesture === undefined) {
  6308. return;
  6309. }
  6310. if (!_this._MSGestureHandler) {
  6311. _this._MSGestureHandler = new MSGesture();
  6312. _this._MSGestureHandler.target = element;
  6313. }
  6314. _this._MSGestureHandler.addPointer(e.pointerId);
  6315. };
  6316. this._onGesture = function (e) {
  6317. _this.radius *= e.scale;
  6318. if (e.preventDefault) {
  6319. if (!noPreventDefault) {
  6320. e.stopPropagation();
  6321. e.preventDefault();
  6322. }
  6323. }
  6324. };
  6325. this._reset = function () {
  6326. _this._keys = [];
  6327. _this.inertialAlphaOffset = 0;
  6328. _this.inertialBetaOffset = 0;
  6329. _this.inertialRadiusOffset = 0;
  6330. previousPosition = null;
  6331. pointerId = null;
  6332. };
  6333. this._touchStart = function (event) {
  6334. if (event.touches.length == 2) {
  6335. pinchStarted = true;
  6336. _this._pinchStart(event);
  6337. }
  6338. };
  6339. this._touchMove = function (event) {
  6340. if (pinchStarted) {
  6341. _this._pinchMove(event);
  6342. }
  6343. };
  6344. this._touchEnd = function (event) {
  6345. if (pinchStarted) {
  6346. _this._pinchEnd(event);
  6347. }
  6348. };
  6349. this._pinchStart = function (event) {
  6350. pinchPointX1 = event.touches[0].clientX;
  6351. pinchPointX2 = event.touches[1].clientX;
  6352. pinchStarted = true;
  6353. };
  6354. this._pinchMove = function (event) {
  6355. var delta = 0;
  6356. var direction = 1;
  6357. var distanceXOrigine, distanceXNow;
  6358. if (event.touches.length != 2)
  6359. return;
  6360. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6361. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6362. if (distanceXNow < distanceXOrigine) {
  6363. direction = -1;
  6364. }
  6365. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6366. _this.inertialRadiusOffset += delta;
  6367. pinchPointX1 = event.touches[0].clientX;
  6368. pinchPointX2 = event.touches[1].clientX;
  6369. };
  6370. this._pinchEnd = function (event) {
  6371. pinchStarted = false;
  6372. };
  6373. }
  6374. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6375. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6376. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6377. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6378. element.addEventListener("mousemove", this._onMouseMove, false);
  6379. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6380. element.addEventListener("MSGestureChange", this._onGesture, false);
  6381. element.addEventListener('mousewheel', this._wheel, false);
  6382. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6383. element.addEventListener('touchstart', this._touchStart, false);
  6384. element.addEventListener('touchmove', this._touchMove, false);
  6385. element.addEventListener('touchend', this._touchEnd, false);
  6386. BABYLON.Tools.RegisterTopRootEvents([
  6387. { name: "keydown", handler: this._onKeyDown },
  6388. { name: "keyup", handler: this._onKeyUp },
  6389. { name: "blur", handler: this._onLostFocus }
  6390. ]);
  6391. };
  6392. ArcRotateCamera.prototype.detachControl = function (element) {
  6393. if (this._attachedElement != element) {
  6394. return;
  6395. }
  6396. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6397. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6398. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6399. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6400. element.removeEventListener("mousemove", this._onMouseMove);
  6401. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6402. element.removeEventListener("MSGestureChange", this._onGesture);
  6403. element.removeEventListener('mousewheel', this._wheel);
  6404. element.removeEventListener('DOMMouseScroll', this._wheel);
  6405. element.removeEventListener('touchstart', this._touchStart);
  6406. element.removeEventListener('touchmove', this._touchMove);
  6407. element.removeEventListener('touchend', this._touchEnd);
  6408. BABYLON.Tools.UnregisterTopRootEvents([
  6409. { name: "keydown", handler: this._onKeyDown },
  6410. { name: "keyup", handler: this._onKeyUp },
  6411. { name: "blur", handler: this._onLostFocus }
  6412. ]);
  6413. this._MSGestureHandler = null;
  6414. this._attachedElement = null;
  6415. if (this._reset) {
  6416. this._reset();
  6417. }
  6418. };
  6419. ArcRotateCamera.prototype._update = function () {
  6420. for (var index = 0; index < this._keys.length; index++) {
  6421. var keyCode = this._keys[index];
  6422. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6423. this.inertialAlphaOffset -= 0.01;
  6424. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6425. this.inertialBetaOffset -= 0.01;
  6426. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6427. this.inertialAlphaOffset += 0.01;
  6428. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6429. this.inertialBetaOffset += 0.01;
  6430. }
  6431. }
  6432. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6433. this.alpha += this.inertialAlphaOffset;
  6434. this.beta += this.inertialBetaOffset;
  6435. this.radius -= this.inertialRadiusOffset;
  6436. this.inertialAlphaOffset *= this.inertia;
  6437. this.inertialBetaOffset *= this.inertia;
  6438. this.inertialRadiusOffset *= this.inertia;
  6439. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6440. this.inertialAlphaOffset = 0;
  6441. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6442. this.inertialBetaOffset = 0;
  6443. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6444. this.inertialRadiusOffset = 0;
  6445. }
  6446. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6447. this.alpha = this.lowerAlphaLimit;
  6448. }
  6449. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6450. this.alpha = this.upperAlphaLimit;
  6451. }
  6452. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6453. this.beta = this.lowerBetaLimit;
  6454. }
  6455. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6456. this.beta = this.upperBetaLimit;
  6457. }
  6458. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6459. this.radius = this.lowerRadiusLimit;
  6460. }
  6461. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6462. this.radius = this.upperRadiusLimit;
  6463. }
  6464. };
  6465. ArcRotateCamera.prototype.setPosition = function (position) {
  6466. var radiusv3 = position.subtract(this._getTargetPosition());
  6467. this.radius = radiusv3.length();
  6468. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6469. if (radiusv3.z < 0) {
  6470. this.alpha = 2 * Math.PI - this.alpha;
  6471. }
  6472. this.beta = Math.acos(radiusv3.y / this.radius);
  6473. };
  6474. ArcRotateCamera.prototype._getViewMatrix = function () {
  6475. var cosa = Math.cos(this.alpha);
  6476. var sina = Math.sin(this.alpha);
  6477. var cosb = Math.cos(this.beta);
  6478. var sinb = Math.sin(this.beta);
  6479. var target = this._getTargetPosition();
  6480. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6481. if (this.checkCollisions) {
  6482. this._collider.radius = this.collisionRadius;
  6483. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6484. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6485. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6486. this.position.copyFrom(this._previousPosition);
  6487. this.alpha = this._previousAlpha;
  6488. this.beta = this._previousBeta;
  6489. this.radius = this._previousRadius;
  6490. if (this.onCollide) {
  6491. this.onCollide(this._collider.collidedMesh);
  6492. }
  6493. }
  6494. }
  6495. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6496. this._previousAlpha = this.alpha;
  6497. this._previousBeta = this.beta;
  6498. this._previousRadius = this.radius;
  6499. this._previousPosition.copyFrom(this.position);
  6500. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6501. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6502. return this._viewMatrix;
  6503. };
  6504. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6505. meshes = meshes || this.getScene().meshes;
  6506. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6507. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6508. this.radius = distance * this.zoomOnFactor;
  6509. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6510. };
  6511. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6512. var meshesOrMinMaxVector;
  6513. var distance;
  6514. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6515. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6516. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6517. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6518. } else {
  6519. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6520. distance = meshesOrMinMaxVectorAndDistance.distance;
  6521. }
  6522. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6523. this.maxZ = distance * 2;
  6524. };
  6525. return ArcRotateCamera;
  6526. })(BABYLON.Camera);
  6527. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6528. })(BABYLON || (BABYLON = {}));
  6529. var BABYLON;
  6530. (function (BABYLON) {
  6531. var Scene = (function () {
  6532. function Scene(engine) {
  6533. this.autoClear = true;
  6534. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6535. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6536. this.forceWireframe = false;
  6537. this.forceShowBoundingBoxes = false;
  6538. this.cameraToUseForPointers = null;
  6539. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  6540. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6541. this.fogDensity = 0.1;
  6542. this.fogStart = 0;
  6543. this.fogEnd = 1000.0;
  6544. this.shadowsEnabled = true;
  6545. this.lightsEnabled = true;
  6546. this.lights = new Array();
  6547. this.cameras = new Array();
  6548. this.activeCameras = new Array();
  6549. this.meshes = new Array();
  6550. this._geometries = new Array();
  6551. this.materials = new Array();
  6552. this.multiMaterials = new Array();
  6553. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6554. this.texturesEnabled = true;
  6555. this.textures = new Array();
  6556. this.particlesEnabled = true;
  6557. this.particleSystems = new Array();
  6558. this.spriteManagers = new Array();
  6559. this.layers = new Array();
  6560. this.skeletons = new Array();
  6561. this.lensFlaresEnabled = true;
  6562. this.lensFlareSystems = new Array();
  6563. this.collisionsEnabled = true;
  6564. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6565. this.postProcessesEnabled = true;
  6566. this.renderTargetsEnabled = true;
  6567. this.customRenderTargets = new Array();
  6568. this.importedMeshesFiles = new Array();
  6569. this._actionManagers = new Array();
  6570. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6571. this.proceduralTexturesEnabled = true;
  6572. this._proceduralTextures = new Array();
  6573. this._totalVertices = 0;
  6574. this._activeVertices = 0;
  6575. this._activeParticles = 0;
  6576. this._lastFrameDuration = 0;
  6577. this._evaluateActiveMeshesDuration = 0;
  6578. this._renderTargetsDuration = 0;
  6579. this._particlesDuration = 0;
  6580. this._renderDuration = 0;
  6581. this._spritesDuration = 0;
  6582. this._animationRatio = 0;
  6583. this._renderId = 0;
  6584. this._executeWhenReadyTimeoutId = -1;
  6585. this._toBeDisposed = new BABYLON.SmartArray(256);
  6586. this._onReadyCallbacks = new Array();
  6587. this._pendingData = [];
  6588. this._onBeforeRenderCallbacks = new Array();
  6589. this._onAfterRenderCallbacks = new Array();
  6590. this._activeMeshes = new BABYLON.SmartArray(256);
  6591. this._processedMaterials = new BABYLON.SmartArray(256);
  6592. this._renderTargets = new BABYLON.SmartArray(256);
  6593. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6594. this._activeSkeletons = new BABYLON.SmartArray(32);
  6595. this._activeAnimatables = new Array();
  6596. this._transformMatrix = BABYLON.Matrix.Zero();
  6597. this._scaledPosition = BABYLON.Vector3.Zero();
  6598. this._scaledVelocity = BABYLON.Vector3.Zero();
  6599. this._engine = engine;
  6600. engine.scenes.push(this);
  6601. this._renderingManager = new BABYLON.RenderingManager(this);
  6602. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6603. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6604. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6605. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6606. this.attachControl();
  6607. this._debugLayer = new BABYLON.DebugLayer(this);
  6608. }
  6609. Object.defineProperty(Scene.prototype, "debugLayer", {
  6610. get: function () {
  6611. return this._debugLayer;
  6612. },
  6613. enumerable: true,
  6614. configurable: true
  6615. });
  6616. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6617. get: function () {
  6618. return this._meshUnderPointer;
  6619. },
  6620. enumerable: true,
  6621. configurable: true
  6622. });
  6623. Object.defineProperty(Scene.prototype, "pointerX", {
  6624. get: function () {
  6625. return this._pointerX;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Object.defineProperty(Scene.prototype, "pointerY", {
  6631. get: function () {
  6632. return this._pointerY;
  6633. },
  6634. enumerable: true,
  6635. configurable: true
  6636. });
  6637. Scene.prototype.getBoundingBoxRenderer = function () {
  6638. return this._boundingBoxRenderer;
  6639. };
  6640. Scene.prototype.getOutlineRenderer = function () {
  6641. return this._outlineRenderer;
  6642. };
  6643. Scene.prototype.getEngine = function () {
  6644. return this._engine;
  6645. };
  6646. Scene.prototype.getTotalVertices = function () {
  6647. return this._totalVertices;
  6648. };
  6649. Scene.prototype.getActiveVertices = function () {
  6650. return this._activeVertices;
  6651. };
  6652. Scene.prototype.getActiveParticles = function () {
  6653. return this._activeParticles;
  6654. };
  6655. Scene.prototype.getLastFrameDuration = function () {
  6656. return this._lastFrameDuration;
  6657. };
  6658. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6659. return this._evaluateActiveMeshesDuration;
  6660. };
  6661. Scene.prototype.getActiveMeshes = function () {
  6662. return this._activeMeshes;
  6663. };
  6664. Scene.prototype.getRenderTargetsDuration = function () {
  6665. return this._renderTargetsDuration;
  6666. };
  6667. Scene.prototype.getRenderDuration = function () {
  6668. return this._renderDuration;
  6669. };
  6670. Scene.prototype.getParticlesDuration = function () {
  6671. return this._particlesDuration;
  6672. };
  6673. Scene.prototype.getSpritesDuration = function () {
  6674. return this._spritesDuration;
  6675. };
  6676. Scene.prototype.getAnimationRatio = function () {
  6677. return this._animationRatio;
  6678. };
  6679. Scene.prototype.getRenderId = function () {
  6680. return this._renderId;
  6681. };
  6682. Scene.prototype._updatePointerPosition = function (evt) {
  6683. var canvasRect = this._engine.getRenderingCanvasClientRect();
  6684. this._pointerX = evt.clientX - canvasRect.left;
  6685. this._pointerY = evt.clientY - canvasRect.top;
  6686. if (this.cameraToUseForPointers) {
  6687. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  6688. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  6689. }
  6690. };
  6691. Scene.prototype.attachControl = function () {
  6692. var _this = this;
  6693. this._onPointerMove = function (evt) {
  6694. var canvas = _this._engine.getRenderingCanvas();
  6695. _this._updatePointerPosition(evt);
  6696. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  6697. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  6698. }, false, _this.cameraToUseForPointers);
  6699. if (pickResult.hit) {
  6700. _this._meshUnderPointer = pickResult.pickedMesh;
  6701. _this.setPointerOverMesh(pickResult.pickedMesh);
  6702. canvas.style.cursor = "pointer";
  6703. } else {
  6704. _this.setPointerOverMesh(null);
  6705. canvas.style.cursor = "";
  6706. _this._meshUnderPointer = null;
  6707. }
  6708. };
  6709. this._onPointerDown = function (evt) {
  6710. var predicate = null;
  6711. if (!_this.onPointerDown) {
  6712. predicate = function (mesh) {
  6713. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  6714. };
  6715. }
  6716. _this._updatePointerPosition(evt);
  6717. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  6718. if (pickResult.hit) {
  6719. if (pickResult.pickedMesh.actionManager) {
  6720. switch (evt.button) {
  6721. case 0:
  6722. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6723. break;
  6724. case 1:
  6725. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6726. break;
  6727. case 2:
  6728. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6729. break;
  6730. }
  6731. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh));
  6732. }
  6733. }
  6734. if (_this.onPointerDown) {
  6735. _this.onPointerDown(evt, pickResult);
  6736. }
  6737. };
  6738. this._onKeyDown = function (evt) {
  6739. if (_this.actionManager) {
  6740. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6741. }
  6742. };
  6743. this._onKeyUp = function (evt) {
  6744. if (_this.actionManager) {
  6745. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  6746. }
  6747. };
  6748. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6749. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6750. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6751. window.addEventListener("keydown", this._onKeyDown, false);
  6752. window.addEventListener("keyup", this._onKeyUp, false);
  6753. };
  6754. Scene.prototype.detachControl = function () {
  6755. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6756. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  6757. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  6758. window.removeEventListener("keydown", this._onKeyDown);
  6759. window.removeEventListener("keyup", this._onKeyUp);
  6760. };
  6761. Scene.prototype.isReady = function () {
  6762. if (this._pendingData.length > 0) {
  6763. return false;
  6764. }
  6765. for (var index = 0; index < this._geometries.length; index++) {
  6766. var geometry = this._geometries[index];
  6767. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  6768. return false;
  6769. }
  6770. }
  6771. for (index = 0; index < this.meshes.length; index++) {
  6772. var mesh = this.meshes[index];
  6773. if (!mesh.isReady()) {
  6774. return false;
  6775. }
  6776. var mat = mesh.material;
  6777. if (mat) {
  6778. if (!mat.isReady(mesh)) {
  6779. return false;
  6780. }
  6781. }
  6782. }
  6783. return true;
  6784. };
  6785. Scene.prototype.registerBeforeRender = function (func) {
  6786. this._onBeforeRenderCallbacks.push(func);
  6787. };
  6788. Scene.prototype.unregisterBeforeRender = function (func) {
  6789. var index = this._onBeforeRenderCallbacks.indexOf(func);
  6790. if (index > -1) {
  6791. this._onBeforeRenderCallbacks.splice(index, 1);
  6792. }
  6793. };
  6794. Scene.prototype.registerAfterRender = function (func) {
  6795. this._onAfterRenderCallbacks.push(func);
  6796. };
  6797. Scene.prototype.unregisterAfterRender = function (func) {
  6798. var index = this._onAfterRenderCallbacks.indexOf(func);
  6799. if (index > -1) {
  6800. this._onAfterRenderCallbacks.splice(index, 1);
  6801. }
  6802. };
  6803. Scene.prototype._addPendingData = function (data) {
  6804. this._pendingData.push(data);
  6805. };
  6806. Scene.prototype._removePendingData = function (data) {
  6807. var index = this._pendingData.indexOf(data);
  6808. if (index !== -1) {
  6809. this._pendingData.splice(index, 1);
  6810. }
  6811. };
  6812. Scene.prototype.getWaitingItemsCount = function () {
  6813. return this._pendingData.length;
  6814. };
  6815. Scene.prototype.executeWhenReady = function (func) {
  6816. var _this = this;
  6817. this._onReadyCallbacks.push(func);
  6818. if (this._executeWhenReadyTimeoutId !== -1) {
  6819. return;
  6820. }
  6821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6822. _this._checkIsReady();
  6823. }, 150);
  6824. };
  6825. Scene.prototype._checkIsReady = function () {
  6826. var _this = this;
  6827. if (this.isReady()) {
  6828. this._onReadyCallbacks.forEach(function (func) {
  6829. func();
  6830. });
  6831. this._onReadyCallbacks = [];
  6832. this._executeWhenReadyTimeoutId = -1;
  6833. return;
  6834. }
  6835. this._executeWhenReadyTimeoutId = setTimeout(function () {
  6836. _this._checkIsReady();
  6837. }, 150);
  6838. };
  6839. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  6840. if (speedRatio === undefined) {
  6841. speedRatio = 1.0;
  6842. }
  6843. this.stopAnimation(target);
  6844. if (!animatable) {
  6845. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  6846. }
  6847. if (target.animations) {
  6848. animatable.appendAnimations(target, target.animations);
  6849. }
  6850. if (target.getAnimatables) {
  6851. var animatables = target.getAnimatables();
  6852. for (var index = 0; index < animatables.length; index++) {
  6853. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  6854. }
  6855. }
  6856. return animatable;
  6857. };
  6858. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  6859. if (speedRatio === undefined) {
  6860. speedRatio = 1.0;
  6861. }
  6862. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  6863. return animatable;
  6864. };
  6865. Scene.prototype.getAnimatableByTarget = function (target) {
  6866. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6867. if (this._activeAnimatables[index].target === target) {
  6868. return this._activeAnimatables[index];
  6869. }
  6870. }
  6871. return null;
  6872. };
  6873. Scene.prototype.stopAnimation = function (target) {
  6874. var animatable = this.getAnimatableByTarget(target);
  6875. if (animatable) {
  6876. animatable.stop();
  6877. }
  6878. };
  6879. Scene.prototype._animate = function () {
  6880. if (!this._animationStartDate) {
  6881. this._animationStartDate = BABYLON.Tools.Now;
  6882. }
  6883. var now = BABYLON.Tools.Now;
  6884. var delay = now - this._animationStartDate;
  6885. for (var index = 0; index < this._activeAnimatables.length; index++) {
  6886. if (!this._activeAnimatables[index]._animate(delay)) {
  6887. this._activeAnimatables.splice(index, 1);
  6888. index--;
  6889. }
  6890. }
  6891. };
  6892. Scene.prototype.getViewMatrix = function () {
  6893. return this._viewMatrix;
  6894. };
  6895. Scene.prototype.getProjectionMatrix = function () {
  6896. return this._projectionMatrix;
  6897. };
  6898. Scene.prototype.getTransformMatrix = function () {
  6899. return this._transformMatrix;
  6900. };
  6901. Scene.prototype.setTransformMatrix = function (view, projection) {
  6902. this._viewMatrix = view;
  6903. this._projectionMatrix = projection;
  6904. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6905. };
  6906. Scene.prototype.setActiveCameraByID = function (id) {
  6907. var camera = this.getCameraByID(id);
  6908. if (camera) {
  6909. this.activeCamera = camera;
  6910. return camera;
  6911. }
  6912. return null;
  6913. };
  6914. Scene.prototype.setActiveCameraByName = function (name) {
  6915. var camera = this.getCameraByName(name);
  6916. if (camera) {
  6917. this.activeCamera = camera;
  6918. return camera;
  6919. }
  6920. return null;
  6921. };
  6922. Scene.prototype.getMaterialByID = function (id) {
  6923. for (var index = 0; index < this.materials.length; index++) {
  6924. if (this.materials[index].id === id) {
  6925. return this.materials[index];
  6926. }
  6927. }
  6928. return null;
  6929. };
  6930. Scene.prototype.getMaterialByName = function (name) {
  6931. for (var index = 0; index < this.materials.length; index++) {
  6932. if (this.materials[index].name === name) {
  6933. return this.materials[index];
  6934. }
  6935. }
  6936. return null;
  6937. };
  6938. Scene.prototype.getCameraByID = function (id) {
  6939. for (var index = 0; index < this.cameras.length; index++) {
  6940. if (this.cameras[index].id === id) {
  6941. return this.cameras[index];
  6942. }
  6943. }
  6944. return null;
  6945. };
  6946. Scene.prototype.getCameraByName = function (name) {
  6947. for (var index = 0; index < this.cameras.length; index++) {
  6948. if (this.cameras[index].name === name) {
  6949. return this.cameras[index];
  6950. }
  6951. }
  6952. return null;
  6953. };
  6954. Scene.prototype.getLightByName = function (name) {
  6955. for (var index = 0; index < this.lights.length; index++) {
  6956. if (this.lights[index].name === name) {
  6957. return this.lights[index];
  6958. }
  6959. }
  6960. return null;
  6961. };
  6962. Scene.prototype.getLightByID = function (id) {
  6963. for (var index = 0; index < this.lights.length; index++) {
  6964. if (this.lights[index].id === id) {
  6965. return this.lights[index];
  6966. }
  6967. }
  6968. return null;
  6969. };
  6970. Scene.prototype.getGeometryByID = function (id) {
  6971. for (var index = 0; index < this._geometries.length; index++) {
  6972. if (this._geometries[index].id === id) {
  6973. return this._geometries[index];
  6974. }
  6975. }
  6976. return null;
  6977. };
  6978. Scene.prototype.pushGeometry = function (geometry, force) {
  6979. if (!force && this.getGeometryByID(geometry.id)) {
  6980. return false;
  6981. }
  6982. this._geometries.push(geometry);
  6983. return true;
  6984. };
  6985. Scene.prototype.getGeometries = function () {
  6986. return this._geometries;
  6987. };
  6988. Scene.prototype.getMeshByID = function (id) {
  6989. for (var index = 0; index < this.meshes.length; index++) {
  6990. if (this.meshes[index].id === id) {
  6991. return this.meshes[index];
  6992. }
  6993. }
  6994. return null;
  6995. };
  6996. Scene.prototype.getLastMeshByID = function (id) {
  6997. for (var index = this.meshes.length - 1; index >= 0; index--) {
  6998. if (this.meshes[index].id === id) {
  6999. return this.meshes[index];
  7000. }
  7001. }
  7002. return null;
  7003. };
  7004. Scene.prototype.getLastEntryByID = function (id) {
  7005. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7006. if (this.meshes[index].id === id) {
  7007. return this.meshes[index];
  7008. }
  7009. }
  7010. for (index = this.cameras.length - 1; index >= 0; index--) {
  7011. if (this.cameras[index].id === id) {
  7012. return this.cameras[index];
  7013. }
  7014. }
  7015. for (index = this.lights.length - 1; index >= 0; index--) {
  7016. if (this.lights[index].id === id) {
  7017. return this.lights[index];
  7018. }
  7019. }
  7020. return null;
  7021. };
  7022. Scene.prototype.getMeshByName = function (name) {
  7023. for (var index = 0; index < this.meshes.length; index++) {
  7024. if (this.meshes[index].name === name) {
  7025. return this.meshes[index];
  7026. }
  7027. }
  7028. return null;
  7029. };
  7030. Scene.prototype.getLastSkeletonByID = function (id) {
  7031. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7032. if (this.skeletons[index].id === id) {
  7033. return this.skeletons[index];
  7034. }
  7035. }
  7036. return null;
  7037. };
  7038. Scene.prototype.getSkeletonById = function (id) {
  7039. for (var index = 0; index < this.skeletons.length; index++) {
  7040. if (this.skeletons[index].id === id) {
  7041. return this.skeletons[index];
  7042. }
  7043. }
  7044. return null;
  7045. };
  7046. Scene.prototype.getSkeletonByName = function (name) {
  7047. for (var index = 0; index < this.skeletons.length; index++) {
  7048. if (this.skeletons[index].name === name) {
  7049. return this.skeletons[index];
  7050. }
  7051. }
  7052. return null;
  7053. };
  7054. Scene.prototype.isActiveMesh = function (mesh) {
  7055. return (this._activeMeshes.indexOf(mesh) !== -1);
  7056. };
  7057. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7058. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7059. var material = subMesh.getMaterial();
  7060. if (mesh.showSubMeshesBoundingBox) {
  7061. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7062. }
  7063. if (material) {
  7064. if (material.getRenderTargetTextures) {
  7065. if (this._processedMaterials.indexOf(material) === -1) {
  7066. this._processedMaterials.push(material);
  7067. this._renderTargets.concat(material.getRenderTargetTextures());
  7068. }
  7069. }
  7070. this._activeVertices += subMesh.verticesCount;
  7071. this._renderingManager.dispatch(subMesh);
  7072. }
  7073. }
  7074. };
  7075. Scene.prototype._evaluateActiveMeshes = function () {
  7076. this._activeMeshes.reset();
  7077. this._renderingManager.reset();
  7078. this._processedMaterials.reset();
  7079. this._activeParticleSystems.reset();
  7080. this._activeSkeletons.reset();
  7081. this._boundingBoxRenderer.reset();
  7082. if (!this._frustumPlanes) {
  7083. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7084. } else {
  7085. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7086. }
  7087. var meshes;
  7088. var len;
  7089. if (this._selectionOctree) {
  7090. var selection = this._selectionOctree.select(this._frustumPlanes);
  7091. meshes = selection.data;
  7092. len = selection.length;
  7093. } else {
  7094. len = this.meshes.length;
  7095. meshes = this.meshes;
  7096. }
  7097. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7098. var mesh = meshes[meshIndex];
  7099. if (mesh.isBlocked) {
  7100. continue;
  7101. }
  7102. this._totalVertices += mesh.getTotalVertices();
  7103. if (!mesh.isReady()) {
  7104. continue;
  7105. }
  7106. mesh.computeWorldMatrix();
  7107. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7108. this._meshesForIntersections.pushNoDuplicate(mesh);
  7109. }
  7110. var meshLOD = mesh.getLOD(this.activeCamera);
  7111. if (!meshLOD) {
  7112. continue;
  7113. }
  7114. mesh._preActivate();
  7115. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) != 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7116. this._activeMeshes.push(mesh);
  7117. mesh._activate(this._renderId);
  7118. this._activeMesh(meshLOD);
  7119. }
  7120. }
  7121. var beforeParticlesDate = BABYLON.Tools.Now;
  7122. if (this.particlesEnabled) {
  7123. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7124. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7125. var particleSystem = this.particleSystems[particleIndex];
  7126. if (!particleSystem.isStarted()) {
  7127. continue;
  7128. }
  7129. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7130. this._activeParticleSystems.push(particleSystem);
  7131. particleSystem.animate();
  7132. }
  7133. }
  7134. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7135. }
  7136. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7137. };
  7138. Scene.prototype._activeMesh = function (mesh) {
  7139. if (mesh.skeleton) {
  7140. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7141. }
  7142. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7143. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7144. }
  7145. if (mesh && mesh.subMeshes) {
  7146. var len;
  7147. var subMeshes;
  7148. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7149. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7150. len = intersections.length;
  7151. subMeshes = intersections.data;
  7152. } else {
  7153. subMeshes = mesh.subMeshes;
  7154. len = subMeshes.length;
  7155. }
  7156. for (var subIndex = 0; subIndex < len; subIndex++) {
  7157. var subMesh = subMeshes[subIndex];
  7158. this._evaluateSubMesh(subMesh, mesh);
  7159. }
  7160. }
  7161. };
  7162. Scene.prototype.updateTransformMatrix = function (force) {
  7163. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7164. };
  7165. Scene.prototype._renderForCamera = function (camera) {
  7166. var engine = this._engine;
  7167. this.activeCamera = camera;
  7168. if (!this.activeCamera)
  7169. throw new Error("Active camera not set");
  7170. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7171. engine.setViewport(this.activeCamera.viewport);
  7172. this._renderId++;
  7173. this.updateTransformMatrix();
  7174. if (this.beforeCameraRender) {
  7175. this.beforeCameraRender(this.activeCamera);
  7176. }
  7177. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7178. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7179. this._evaluateActiveMeshes();
  7180. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7181. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7182. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7183. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7184. skeleton.prepare();
  7185. }
  7186. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7187. if (this.renderTargetsEnabled) {
  7188. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7189. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7190. var renderTarget = this._renderTargets.data[renderIndex];
  7191. if (renderTarget._shouldRender()) {
  7192. this._renderId++;
  7193. renderTarget.render();
  7194. }
  7195. }
  7196. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7197. this._renderId++;
  7198. }
  7199. if (this._renderTargets.length > 0) {
  7200. engine.restoreDefaultFramebuffer();
  7201. }
  7202. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7203. this.postProcessManager._prepareFrame();
  7204. var beforeRenderDate = BABYLON.Tools.Now;
  7205. if (this.layers.length) {
  7206. engine.setDepthBuffer(false);
  7207. var layerIndex;
  7208. var layer;
  7209. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7210. layer = this.layers[layerIndex];
  7211. if (layer.isBackground) {
  7212. layer.render();
  7213. }
  7214. }
  7215. engine.setDepthBuffer(true);
  7216. }
  7217. BABYLON.Tools.StartPerformanceCounter("Main render");
  7218. this._renderingManager.render(null, null, true, true);
  7219. BABYLON.Tools.EndPerformanceCounter("Main render");
  7220. this._boundingBoxRenderer.render();
  7221. if (this.lensFlaresEnabled) {
  7222. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7223. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7224. this.lensFlareSystems[lensFlareSystemIndex].render();
  7225. }
  7226. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7227. }
  7228. if (this.layers.length) {
  7229. engine.setDepthBuffer(false);
  7230. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7231. layer = this.layers[layerIndex];
  7232. if (!layer.isBackground) {
  7233. layer.render();
  7234. }
  7235. }
  7236. engine.setDepthBuffer(true);
  7237. }
  7238. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7239. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7240. this.activeCamera._updateFromScene();
  7241. this._renderTargets.reset();
  7242. if (this.afterCameraRender) {
  7243. this.afterCameraRender(this.activeCamera);
  7244. }
  7245. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7246. };
  7247. Scene.prototype._processSubCameras = function (camera) {
  7248. if (camera.subCameras.length == 0) {
  7249. this._renderForCamera(camera);
  7250. return;
  7251. }
  7252. for (var index = 0; index < camera.subCameras.length; index++) {
  7253. this._renderForCamera(camera.subCameras[index]);
  7254. }
  7255. this.activeCamera = camera;
  7256. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7257. this.activeCamera._updateFromScene();
  7258. };
  7259. Scene.prototype._checkIntersections = function () {
  7260. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7261. var sourceMesh = this._meshesForIntersections.data[index];
  7262. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7263. var action = sourceMesh.actionManager.actions[actionIndex];
  7264. if (action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7265. var otherMesh = action.getTriggerParameter();
  7266. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7267. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7268. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger == BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7269. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7270. sourceMesh._intersectionsInProgress.push(otherMesh);
  7271. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger == BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7272. sourceMesh.actionManager.processTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, BABYLON.ActionEvent.CreateNew(sourceMesh));
  7273. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7274. if (indexOfOther > -1) {
  7275. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7276. }
  7277. }
  7278. }
  7279. }
  7280. }
  7281. };
  7282. Scene.prototype.render = function () {
  7283. var startDate = BABYLON.Tools.Now;
  7284. this._particlesDuration = 0;
  7285. this._spritesDuration = 0;
  7286. this._activeParticles = 0;
  7287. this._renderDuration = 0;
  7288. this._renderTargetsDuration = 0;
  7289. this._evaluateActiveMeshesDuration = 0;
  7290. this._totalVertices = 0;
  7291. this._activeVertices = 0;
  7292. this.getEngine().resetDrawCalls();
  7293. this._meshesForIntersections.reset();
  7294. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7295. if (this.actionManager) {
  7296. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7297. }
  7298. if (this.beforeRender) {
  7299. this.beforeRender();
  7300. }
  7301. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7302. this._onBeforeRenderCallbacks[callbackIndex]();
  7303. }
  7304. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(BABYLON.Tools.GetDeltaTime(), Scene.MaxDeltaTime));
  7305. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7306. this._animate();
  7307. if (this._physicsEngine) {
  7308. BABYLON.Tools.StartPerformanceCounter("Physics");
  7309. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7310. BABYLON.Tools.EndPerformanceCounter("Physics");
  7311. }
  7312. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7313. var engine = this.getEngine();
  7314. if (this.renderTargetsEnabled) {
  7315. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7316. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7317. var renderTarget = this.customRenderTargets[customIndex];
  7318. if (renderTarget._shouldRender()) {
  7319. this._renderId++;
  7320. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7321. if (!this.activeCamera)
  7322. throw new Error("Active camera not set");
  7323. engine.setViewport(this.activeCamera.viewport);
  7324. this.updateTransformMatrix();
  7325. renderTarget.render();
  7326. }
  7327. }
  7328. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7329. this._renderId++;
  7330. }
  7331. if (this.customRenderTargets.length > 0) {
  7332. engine.restoreDefaultFramebuffer();
  7333. }
  7334. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7335. if (this.proceduralTexturesEnabled) {
  7336. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7337. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7338. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7339. if (proceduralTexture._shouldRender()) {
  7340. proceduralTexture.render();
  7341. }
  7342. }
  7343. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7344. }
  7345. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  7346. if (this.shadowsEnabled) {
  7347. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7348. var light = this.lights[lightIndex];
  7349. var shadowGenerator = light.getShadowGenerator();
  7350. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7351. this._renderTargets.push(shadowGenerator.getShadowMap());
  7352. }
  7353. }
  7354. }
  7355. this.postProcessRenderPipelineManager.update();
  7356. if (this.activeCameras.length > 0) {
  7357. var currentRenderId = this._renderId;
  7358. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7359. this._renderId = currentRenderId;
  7360. this._processSubCameras(this.activeCameras[cameraIndex]);
  7361. }
  7362. } else {
  7363. if (!this.activeCamera) {
  7364. throw new Error("No camera defined");
  7365. }
  7366. this._processSubCameras(this.activeCamera);
  7367. }
  7368. this._checkIntersections();
  7369. this._updateAudioParameters();
  7370. if (this.afterRender) {
  7371. this.afterRender();
  7372. }
  7373. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7374. this._onAfterRenderCallbacks[callbackIndex]();
  7375. }
  7376. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7377. this._toBeDisposed.data[index].dispose();
  7378. this._toBeDisposed[index] = null;
  7379. }
  7380. this._toBeDisposed.reset();
  7381. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7382. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7383. };
  7384. Scene.prototype._updateAudioParameters = function () {
  7385. var listeningCamera;
  7386. var audioEngine = this._engine.getAudioEngine();
  7387. if (this.activeCameras.length > 0) {
  7388. listeningCamera = this.activeCameras[0];
  7389. } else {
  7390. listeningCamera = this.activeCamera;
  7391. }
  7392. if (listeningCamera && audioEngine.canUseWebAudio) {
  7393. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7394. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7395. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7396. cameraDirection.normalize();
  7397. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7398. }
  7399. };
  7400. Scene.prototype.dispose = function () {
  7401. this.beforeRender = null;
  7402. this.afterRender = null;
  7403. this.skeletons = [];
  7404. this._boundingBoxRenderer.dispose();
  7405. this.debugLayer.enabled = false;
  7406. if (this.onDispose) {
  7407. this.onDispose();
  7408. }
  7409. this._onBeforeRenderCallbacks = [];
  7410. this._onAfterRenderCallbacks = [];
  7411. this.detachControl();
  7412. var canvas = this._engine.getRenderingCanvas();
  7413. var index;
  7414. for (index = 0; index < this.cameras.length; index++) {
  7415. this.cameras[index].detachControl(canvas);
  7416. }
  7417. while (this.lights.length) {
  7418. this.lights[0].dispose();
  7419. }
  7420. while (this.meshes.length) {
  7421. this.meshes[0].dispose(true);
  7422. }
  7423. while (this.cameras.length) {
  7424. this.cameras[0].dispose();
  7425. }
  7426. while (this.materials.length) {
  7427. this.materials[0].dispose();
  7428. }
  7429. while (this.particleSystems.length) {
  7430. this.particleSystems[0].dispose();
  7431. }
  7432. while (this.spriteManagers.length) {
  7433. this.spriteManagers[0].dispose();
  7434. }
  7435. while (this.layers.length) {
  7436. this.layers[0].dispose();
  7437. }
  7438. while (this.textures.length) {
  7439. this.textures[0].dispose();
  7440. }
  7441. this.postProcessManager.dispose();
  7442. if (this._physicsEngine) {
  7443. this.disablePhysicsEngine();
  7444. }
  7445. index = this._engine.scenes.indexOf(this);
  7446. if (index > -1) {
  7447. this._engine.scenes.splice(index, 1);
  7448. }
  7449. this._engine.wipeCaches();
  7450. };
  7451. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7452. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7453. position.divideToRef(collider.radius, this._scaledPosition);
  7454. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7455. collider.retry = 0;
  7456. collider.initialVelocity = this._scaledVelocity;
  7457. collider.initialPosition = this._scaledPosition;
  7458. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7459. finalPosition.multiplyInPlace(collider.radius);
  7460. };
  7461. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7462. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7463. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7464. if (collider.retry >= maximumRetry) {
  7465. finalPosition.copyFrom(position);
  7466. return;
  7467. }
  7468. collider._initialize(position, velocity, closeDistance);
  7469. for (var index = 0; index < this.meshes.length; index++) {
  7470. var mesh = this.meshes[index];
  7471. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7472. mesh._checkCollision(collider);
  7473. }
  7474. }
  7475. if (!collider.collisionFound) {
  7476. position.addToRef(velocity, finalPosition);
  7477. return;
  7478. }
  7479. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  7480. collider._getResponse(position, velocity);
  7481. }
  7482. if (velocity.length() <= closeDistance) {
  7483. finalPosition.copyFrom(position);
  7484. return;
  7485. }
  7486. collider.retry++;
  7487. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7488. };
  7489. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7490. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7491. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7492. if (!this._selectionOctree) {
  7493. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7494. }
  7495. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7496. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7497. for (var index = 0; index < this.meshes.length; index++) {
  7498. var mesh = this.meshes[index];
  7499. mesh.computeWorldMatrix(true);
  7500. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7501. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7502. BABYLON.Tools.CheckExtends(minBox, min, max);
  7503. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7504. }
  7505. this._selectionOctree.update(min, max, this.meshes);
  7506. return this._selectionOctree;
  7507. };
  7508. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7509. var engine = this._engine;
  7510. if (!camera) {
  7511. if (!this.activeCamera)
  7512. throw new Error("Active camera not set");
  7513. camera = this.activeCamera;
  7514. }
  7515. var cameraViewport = camera.viewport;
  7516. var viewport = cameraViewport.toGlobal(engine);
  7517. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7518. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7519. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7520. };
  7521. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7522. var pickingInfo = null;
  7523. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7524. var mesh = this.meshes[meshIndex];
  7525. if (predicate) {
  7526. if (!predicate(mesh)) {
  7527. continue;
  7528. }
  7529. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7530. continue;
  7531. }
  7532. var world = mesh.getWorldMatrix();
  7533. var ray = rayFunction(world);
  7534. var result = mesh.intersects(ray, fastCheck);
  7535. if (!result || !result.hit)
  7536. continue;
  7537. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7538. continue;
  7539. pickingInfo = result;
  7540. if (fastCheck) {
  7541. break;
  7542. }
  7543. }
  7544. return pickingInfo || new BABYLON.PickingInfo();
  7545. };
  7546. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7547. var _this = this;
  7548. return this._internalPick(function (world) {
  7549. return _this.createPickingRay(x, y, world, camera);
  7550. }, predicate, fastCheck);
  7551. };
  7552. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7553. var _this = this;
  7554. return this._internalPick(function (world) {
  7555. if (!_this._pickWithRayInverseMatrix) {
  7556. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7557. }
  7558. world.invertToRef(_this._pickWithRayInverseMatrix);
  7559. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7560. }, predicate, fastCheck);
  7561. };
  7562. Scene.prototype.setPointerOverMesh = function (mesh) {
  7563. if (this._pointerOverMesh === mesh) {
  7564. return;
  7565. }
  7566. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7567. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7568. }
  7569. this._pointerOverMesh = mesh;
  7570. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7571. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7572. }
  7573. };
  7574. Scene.prototype.getPointerOverMesh = function () {
  7575. return this._pointerOverMesh;
  7576. };
  7577. Scene.prototype.getPhysicsEngine = function () {
  7578. return this._physicsEngine;
  7579. };
  7580. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7581. if (this._physicsEngine) {
  7582. return true;
  7583. }
  7584. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7585. if (!this._physicsEngine.isSupported()) {
  7586. this._physicsEngine = null;
  7587. return false;
  7588. }
  7589. this._physicsEngine._initialize(gravity);
  7590. return true;
  7591. };
  7592. Scene.prototype.disablePhysicsEngine = function () {
  7593. if (!this._physicsEngine) {
  7594. return;
  7595. }
  7596. this._physicsEngine.dispose();
  7597. this._physicsEngine = undefined;
  7598. };
  7599. Scene.prototype.isPhysicsEnabled = function () {
  7600. return this._physicsEngine !== undefined;
  7601. };
  7602. Scene.prototype.setGravity = function (gravity) {
  7603. if (!this._physicsEngine) {
  7604. return;
  7605. }
  7606. this._physicsEngine._setGravity(gravity);
  7607. };
  7608. Scene.prototype.createCompoundImpostor = function (parts, options) {
  7609. if (parts.parts) {
  7610. options = parts;
  7611. parts = parts.parts;
  7612. }
  7613. if (!this._physicsEngine) {
  7614. return null;
  7615. }
  7616. for (var index = 0; index < parts.length; index++) {
  7617. var mesh = parts[index].mesh;
  7618. mesh._physicImpostor = parts[index].impostor;
  7619. mesh._physicsMass = options.mass / parts.length;
  7620. mesh._physicsFriction = options.friction;
  7621. mesh._physicRestitution = options.restitution;
  7622. }
  7623. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  7624. };
  7625. Scene.prototype.deleteCompoundImpostor = function (compound) {
  7626. for (var index = 0; index < compound.parts.length; index++) {
  7627. var mesh = compound.parts[index].mesh;
  7628. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7629. this._physicsEngine._unregisterMesh(mesh);
  7630. }
  7631. };
  7632. Scene.prototype._getByTags = function (list, tagsQuery) {
  7633. if (tagsQuery === undefined) {
  7634. return list;
  7635. }
  7636. var listByTags = [];
  7637. for (var i in list) {
  7638. var item = list[i];
  7639. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  7640. listByTags.push(item);
  7641. }
  7642. }
  7643. return listByTags;
  7644. };
  7645. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  7646. return this._getByTags(this.meshes, tagsQuery);
  7647. };
  7648. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  7649. return this._getByTags(this.cameras, tagsQuery);
  7650. };
  7651. Scene.prototype.getLightsByTags = function (tagsQuery) {
  7652. return this._getByTags(this.lights, tagsQuery);
  7653. };
  7654. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  7655. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  7656. };
  7657. Scene.FOGMODE_NONE = 0;
  7658. Scene.FOGMODE_EXP = 1;
  7659. Scene.FOGMODE_EXP2 = 2;
  7660. Scene.FOGMODE_LINEAR = 3;
  7661. Scene.MinDeltaTime = 1.0;
  7662. Scene.MaxDeltaTime = 1000.0;
  7663. return Scene;
  7664. })();
  7665. BABYLON.Scene = Scene;
  7666. })(BABYLON || (BABYLON = {}));
  7667. var BABYLON;
  7668. (function (BABYLON) {
  7669. var VertexBuffer = (function () {
  7670. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  7671. if (engine instanceof BABYLON.Mesh) {
  7672. this._engine = engine.getScene().getEngine();
  7673. } else {
  7674. this._engine = engine;
  7675. }
  7676. this._updatable = updatable;
  7677. this._data = data;
  7678. if (!postponeInternalCreation) {
  7679. this.create();
  7680. }
  7681. this._kind = kind;
  7682. if (stride) {
  7683. this._strideSize = stride;
  7684. return;
  7685. }
  7686. switch (kind) {
  7687. case VertexBuffer.PositionKind:
  7688. this._strideSize = 3;
  7689. break;
  7690. case VertexBuffer.NormalKind:
  7691. this._strideSize = 3;
  7692. break;
  7693. case VertexBuffer.UVKind:
  7694. this._strideSize = 2;
  7695. break;
  7696. case VertexBuffer.UV2Kind:
  7697. this._strideSize = 2;
  7698. break;
  7699. case VertexBuffer.ColorKind:
  7700. this._strideSize = 4;
  7701. break;
  7702. case VertexBuffer.MatricesIndicesKind:
  7703. this._strideSize = 4;
  7704. break;
  7705. case VertexBuffer.MatricesWeightsKind:
  7706. this._strideSize = 4;
  7707. break;
  7708. }
  7709. }
  7710. VertexBuffer.prototype.isUpdatable = function () {
  7711. return this._updatable;
  7712. };
  7713. VertexBuffer.prototype.getData = function () {
  7714. return this._data;
  7715. };
  7716. VertexBuffer.prototype.getBuffer = function () {
  7717. return this._buffer;
  7718. };
  7719. VertexBuffer.prototype.getStrideSize = function () {
  7720. return this._strideSize;
  7721. };
  7722. VertexBuffer.prototype.create = function (data) {
  7723. if (!data && this._buffer) {
  7724. return;
  7725. }
  7726. data = data || this._data;
  7727. if (!this._buffer) {
  7728. if (this._updatable) {
  7729. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  7730. } else {
  7731. this._buffer = this._engine.createVertexBuffer(data);
  7732. }
  7733. }
  7734. if (this._updatable) {
  7735. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7736. this._data = data;
  7737. }
  7738. };
  7739. VertexBuffer.prototype.update = function (data) {
  7740. this.create(data);
  7741. };
  7742. VertexBuffer.prototype.updateDirectly = function (data) {
  7743. if (!this._buffer) {
  7744. return;
  7745. }
  7746. if (this._updatable) {
  7747. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  7748. this._data = null;
  7749. }
  7750. };
  7751. VertexBuffer.prototype.dispose = function () {
  7752. if (!this._buffer) {
  7753. return;
  7754. }
  7755. if (this._engine._releaseBuffer(this._buffer)) {
  7756. this._buffer = null;
  7757. }
  7758. };
  7759. Object.defineProperty(VertexBuffer, "PositionKind", {
  7760. get: function () {
  7761. return VertexBuffer._PositionKind;
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. Object.defineProperty(VertexBuffer, "NormalKind", {
  7767. get: function () {
  7768. return VertexBuffer._NormalKind;
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. Object.defineProperty(VertexBuffer, "UVKind", {
  7774. get: function () {
  7775. return VertexBuffer._UVKind;
  7776. },
  7777. enumerable: true,
  7778. configurable: true
  7779. });
  7780. Object.defineProperty(VertexBuffer, "UV2Kind", {
  7781. get: function () {
  7782. return VertexBuffer._UV2Kind;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(VertexBuffer, "ColorKind", {
  7788. get: function () {
  7789. return VertexBuffer._ColorKind;
  7790. },
  7791. enumerable: true,
  7792. configurable: true
  7793. });
  7794. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  7795. get: function () {
  7796. return VertexBuffer._MatricesIndicesKind;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  7802. get: function () {
  7803. return VertexBuffer._MatricesWeightsKind;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. VertexBuffer._PositionKind = "position";
  7809. VertexBuffer._NormalKind = "normal";
  7810. VertexBuffer._UVKind = "uv";
  7811. VertexBuffer._UV2Kind = "uv2";
  7812. VertexBuffer._ColorKind = "color";
  7813. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  7814. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  7815. return VertexBuffer;
  7816. })();
  7817. BABYLON.VertexBuffer = VertexBuffer;
  7818. })(BABYLON || (BABYLON = {}));
  7819. var __extends = this.__extends || function (d, b) {
  7820. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7821. function __() { this.constructor = d; }
  7822. __.prototype = b.prototype;
  7823. d.prototype = new __();
  7824. };
  7825. var BABYLON;
  7826. (function (BABYLON) {
  7827. var AbstractMesh = (function (_super) {
  7828. __extends(AbstractMesh, _super);
  7829. function AbstractMesh(name, scene) {
  7830. _super.call(this, name, scene);
  7831. this.position = new BABYLON.Vector3(0, 0, 0);
  7832. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7833. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7834. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  7835. this.visibility = 1.0;
  7836. this.infiniteDistance = false;
  7837. this.isVisible = true;
  7838. this.isPickable = true;
  7839. this.showBoundingBox = false;
  7840. this.showSubMeshesBoundingBox = false;
  7841. this.onDispose = null;
  7842. this.checkCollisions = false;
  7843. this.isBlocker = false;
  7844. this.renderingGroupId = 0;
  7845. this.receiveShadows = false;
  7846. this.renderOutline = false;
  7847. this.outlineColor = BABYLON.Color3.Red();
  7848. this.outlineWidth = 0.02;
  7849. this.renderOverlay = false;
  7850. this.overlayColor = BABYLON.Color3.Red();
  7851. this.overlayAlpha = 0.5;
  7852. this.hasVertexAlpha = false;
  7853. this.useVertexColors = true;
  7854. this.useOctreeForRenderingSelection = true;
  7855. this.useOctreeForPicking = true;
  7856. this.useOctreeForCollisions = true;
  7857. this.layerMask = 0xFFFFFFFF;
  7858. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7859. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7860. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7861. this._collider = new BABYLON.Collider();
  7862. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7863. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7864. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7865. this._localScaling = BABYLON.Matrix.Zero();
  7866. this._localRotation = BABYLON.Matrix.Zero();
  7867. this._localTranslation = BABYLON.Matrix.Zero();
  7868. this._localBillboard = BABYLON.Matrix.Zero();
  7869. this._localPivotScaling = BABYLON.Matrix.Zero();
  7870. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7871. this._localWorld = BABYLON.Matrix.Zero();
  7872. this._worldMatrix = BABYLON.Matrix.Zero();
  7873. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7874. this._absolutePosition = BABYLON.Vector3.Zero();
  7875. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7876. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7877. this._isDirty = false;
  7878. this._pivotMatrix = BABYLON.Matrix.Identity();
  7879. this._isDisposed = false;
  7880. this._renderId = 0;
  7881. this._intersectionsInProgress = new Array();
  7882. this._onAfterWorldMatrixUpdate = new Array();
  7883. scene.meshes.push(this);
  7884. }
  7885. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7886. get: function () {
  7887. return AbstractMesh._BILLBOARDMODE_NONE;
  7888. },
  7889. enumerable: true,
  7890. configurable: true
  7891. });
  7892. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7893. get: function () {
  7894. return AbstractMesh._BILLBOARDMODE_X;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7900. get: function () {
  7901. return AbstractMesh._BILLBOARDMODE_Y;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7907. get: function () {
  7908. return AbstractMesh._BILLBOARDMODE_Z;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7914. get: function () {
  7915. return AbstractMesh._BILLBOARDMODE_ALL;
  7916. },
  7917. enumerable: true,
  7918. configurable: true
  7919. });
  7920. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7921. get: function () {
  7922. return false;
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. AbstractMesh.prototype.getLOD = function (camera) {
  7928. return this;
  7929. };
  7930. AbstractMesh.prototype.getTotalVertices = function () {
  7931. return 0;
  7932. };
  7933. AbstractMesh.prototype.getIndices = function () {
  7934. return null;
  7935. };
  7936. AbstractMesh.prototype.getVerticesData = function (kind) {
  7937. return null;
  7938. };
  7939. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7940. return false;
  7941. };
  7942. AbstractMesh.prototype.getBoundingInfo = function () {
  7943. if (this._masterMesh) {
  7944. return this._masterMesh.getBoundingInfo();
  7945. }
  7946. if (!this._boundingInfo) {
  7947. this._updateBoundingInfo();
  7948. }
  7949. return this._boundingInfo;
  7950. };
  7951. AbstractMesh.prototype._preActivate = function () {
  7952. };
  7953. AbstractMesh.prototype._activate = function (renderId) {
  7954. this._renderId = renderId;
  7955. };
  7956. AbstractMesh.prototype.getWorldMatrix = function () {
  7957. if (this._masterMesh) {
  7958. return this._masterMesh.getWorldMatrix();
  7959. }
  7960. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7961. this.computeWorldMatrix();
  7962. }
  7963. return this._worldMatrix;
  7964. };
  7965. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7966. get: function () {
  7967. return this._worldMatrix;
  7968. },
  7969. enumerable: true,
  7970. configurable: true
  7971. });
  7972. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7973. get: function () {
  7974. return this._absolutePosition;
  7975. },
  7976. enumerable: true,
  7977. configurable: true
  7978. });
  7979. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7980. if (!this.rotationQuaternion) {
  7981. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7982. this.rotation = BABYLON.Vector3.Zero();
  7983. }
  7984. if (!space || space == 0 /* LOCAL */) {
  7985. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7986. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7987. } else {
  7988. if (this.parent) {
  7989. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7990. invertParentWorldMatrix.invert();
  7991. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7992. }
  7993. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7994. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7995. }
  7996. };
  7997. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7998. var displacementVector = axis.scale(distance);
  7999. if (!space || space == 0 /* LOCAL */) {
  8000. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8001. this.setPositionWithLocalVector(tempV3);
  8002. } else {
  8003. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8004. }
  8005. };
  8006. AbstractMesh.prototype.getAbsolutePosition = function () {
  8007. this.computeWorldMatrix();
  8008. return this._absolutePosition;
  8009. };
  8010. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8011. if (!absolutePosition) {
  8012. return;
  8013. }
  8014. var absolutePositionX;
  8015. var absolutePositionY;
  8016. var absolutePositionZ;
  8017. if (absolutePosition.x === undefined) {
  8018. if (arguments.length < 3) {
  8019. return;
  8020. }
  8021. absolutePositionX = arguments[0];
  8022. absolutePositionY = arguments[1];
  8023. absolutePositionZ = arguments[2];
  8024. } else {
  8025. absolutePositionX = absolutePosition.x;
  8026. absolutePositionY = absolutePosition.y;
  8027. absolutePositionZ = absolutePosition.z;
  8028. }
  8029. if (this.parent) {
  8030. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8031. invertParentWorldMatrix.invert();
  8032. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8033. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8034. } else {
  8035. this.position.x = absolutePositionX;
  8036. this.position.y = absolutePositionY;
  8037. this.position.z = absolutePositionZ;
  8038. }
  8039. };
  8040. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8041. this._pivotMatrix = matrix;
  8042. this._cache.pivotMatrixUpdated = true;
  8043. };
  8044. AbstractMesh.prototype.getPivotMatrix = function () {
  8045. return this._pivotMatrix;
  8046. };
  8047. AbstractMesh.prototype._isSynchronized = function () {
  8048. if (this._isDirty) {
  8049. return false;
  8050. }
  8051. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8052. return false;
  8053. if (this._cache.pivotMatrixUpdated) {
  8054. return false;
  8055. }
  8056. if (this.infiniteDistance) {
  8057. return false;
  8058. }
  8059. if (!this._cache.position.equals(this.position))
  8060. return false;
  8061. if (this.rotationQuaternion) {
  8062. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8063. return false;
  8064. } else {
  8065. if (!this._cache.rotation.equals(this.rotation))
  8066. return false;
  8067. }
  8068. if (!this._cache.scaling.equals(this.scaling))
  8069. return false;
  8070. return true;
  8071. };
  8072. AbstractMesh.prototype._initCache = function () {
  8073. _super.prototype._initCache.call(this);
  8074. this._cache.localMatrixUpdated = false;
  8075. this._cache.position = BABYLON.Vector3.Zero();
  8076. this._cache.scaling = BABYLON.Vector3.Zero();
  8077. this._cache.rotation = BABYLON.Vector3.Zero();
  8078. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8079. };
  8080. AbstractMesh.prototype.markAsDirty = function (property) {
  8081. if (property === "rotation") {
  8082. this.rotationQuaternion = null;
  8083. }
  8084. this._currentRenderId = Number.MAX_VALUE;
  8085. this._isDirty = true;
  8086. };
  8087. AbstractMesh.prototype._updateBoundingInfo = function () {
  8088. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8089. this._boundingInfo._update(this.worldMatrixFromCache);
  8090. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8091. };
  8092. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8093. if (!this.subMeshes) {
  8094. return;
  8095. }
  8096. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8097. var subMesh = this.subMeshes[subIndex];
  8098. subMesh.updateBoundingInfo(matrix);
  8099. }
  8100. };
  8101. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8102. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8103. return this._worldMatrix;
  8104. }
  8105. this._cache.position.copyFrom(this.position);
  8106. this._cache.scaling.copyFrom(this.scaling);
  8107. this._cache.pivotMatrixUpdated = false;
  8108. this._currentRenderId = this.getScene().getRenderId();
  8109. this._isDirty = false;
  8110. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8111. if (this.rotationQuaternion) {
  8112. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8113. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8114. } else {
  8115. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8116. this._cache.rotation.copyFrom(this.rotation);
  8117. }
  8118. if (this.infiniteDistance && !this.parent) {
  8119. var camera = this.getScene().activeCamera;
  8120. var cameraWorldMatrix = camera.getWorldMatrix();
  8121. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8122. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8123. } else {
  8124. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8125. }
  8126. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8127. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8128. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8129. var localPosition = this.position.clone();
  8130. var zero = this.getScene().activeCamera.position.clone();
  8131. if (this.parent && this.parent.position) {
  8132. localPosition.addInPlace(this.parent.position);
  8133. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8134. }
  8135. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8136. zero = this.getScene().activeCamera.position;
  8137. } else {
  8138. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8139. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8140. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8141. zero.y = localPosition.y + 0.001;
  8142. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8143. zero.z = localPosition.z + 0.001;
  8144. }
  8145. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8146. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8147. this._localBillboard.invert();
  8148. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8149. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8150. }
  8151. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8152. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8153. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8154. } else {
  8155. this._worldMatrix.copyFrom(this._localWorld);
  8156. }
  8157. this._updateBoundingInfo();
  8158. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8159. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8160. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8161. }
  8162. return this._worldMatrix;
  8163. };
  8164. /**
  8165. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8166. * @param func: callback function to add
  8167. */
  8168. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8169. this._onAfterWorldMatrixUpdate.push(func);
  8170. };
  8171. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8172. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8173. if (index > -1) {
  8174. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8175. }
  8176. };
  8177. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8178. this.computeWorldMatrix();
  8179. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8180. };
  8181. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8182. this.computeWorldMatrix();
  8183. var invLocalWorldMatrix = this._localWorld.clone();
  8184. invLocalWorldMatrix.invert();
  8185. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8186. };
  8187. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8188. this.computeWorldMatrix();
  8189. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8190. };
  8191. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8192. yawCor = yawCor || 0;
  8193. pitchCor = pitchCor || 0;
  8194. rollCor = rollCor || 0;
  8195. var dv = targetPoint.subtract(this.position);
  8196. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8197. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8198. var pitch = Math.atan2(dv.y, len);
  8199. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8200. };
  8201. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8202. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8203. return false;
  8204. }
  8205. return true;
  8206. };
  8207. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8208. if (!camera) {
  8209. camera = this.getScene().activeCamera;
  8210. }
  8211. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8212. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8213. return false;
  8214. }
  8215. return true;
  8216. };
  8217. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8218. if (!this._boundingInfo || !mesh._boundingInfo) {
  8219. return false;
  8220. }
  8221. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8222. };
  8223. AbstractMesh.prototype.intersectsPoint = function (point) {
  8224. if (!this._boundingInfo) {
  8225. return false;
  8226. }
  8227. return this._boundingInfo.intersectsPoint(point);
  8228. };
  8229. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8230. var physicsEngine = this.getScene().getPhysicsEngine();
  8231. if (!physicsEngine) {
  8232. return;
  8233. }
  8234. if (impostor.impostor) {
  8235. options = impostor;
  8236. impostor = impostor.impostor;
  8237. }
  8238. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8239. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8240. physicsEngine._unregisterMesh(this);
  8241. return;
  8242. }
  8243. options.mass = options.mass || 0;
  8244. options.friction = options.friction || 0.2;
  8245. options.restitution = options.restitution || 0.2;
  8246. this._physicImpostor = impostor;
  8247. this._physicsMass = options.mass;
  8248. this._physicsFriction = options.friction;
  8249. this._physicRestitution = options.restitution;
  8250. physicsEngine._registerMesh(this, impostor, options);
  8251. };
  8252. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8253. if (!this._physicImpostor) {
  8254. return BABYLON.PhysicsEngine.NoImpostor;
  8255. }
  8256. return this._physicImpostor;
  8257. };
  8258. AbstractMesh.prototype.getPhysicsMass = function () {
  8259. if (!this._physicsMass) {
  8260. return 0;
  8261. }
  8262. return this._physicsMass;
  8263. };
  8264. AbstractMesh.prototype.getPhysicsFriction = function () {
  8265. if (!this._physicsFriction) {
  8266. return 0;
  8267. }
  8268. return this._physicsFriction;
  8269. };
  8270. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8271. if (!this._physicRestitution) {
  8272. return 0;
  8273. }
  8274. return this._physicRestitution;
  8275. };
  8276. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8277. if (!camera) {
  8278. camera = this.getScene().activeCamera;
  8279. }
  8280. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8281. };
  8282. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8283. if (!camera) {
  8284. camera = this.getScene().activeCamera;
  8285. }
  8286. return this.absolutePosition.subtract(camera.position);
  8287. };
  8288. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8289. if (!this._physicImpostor) {
  8290. return;
  8291. }
  8292. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8293. };
  8294. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8295. if (!this._physicImpostor) {
  8296. return;
  8297. }
  8298. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8299. };
  8300. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8301. if (!this._physicImpostor) {
  8302. return;
  8303. }
  8304. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8305. };
  8306. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8307. var globalPosition = this.getAbsolutePosition();
  8308. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8309. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8310. this._collider.radius = this.ellipsoid;
  8311. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8312. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8313. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8314. this.position.addInPlace(this._diffPositionForCollisions);
  8315. }
  8316. };
  8317. /**
  8318. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8319. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8320. */
  8321. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8322. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8323. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8324. if (!this._submeshesOctree) {
  8325. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8326. }
  8327. this.computeWorldMatrix(true);
  8328. var bbox = this.getBoundingInfo().boundingBox;
  8329. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8330. return this._submeshesOctree;
  8331. };
  8332. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8333. this._generatePointsArray();
  8334. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8335. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8336. subMesh._lastColliderWorldVertices = [];
  8337. subMesh._trianglePlanes = [];
  8338. var start = subMesh.verticesStart;
  8339. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8340. for (var i = start; i < end; i++) {
  8341. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8342. }
  8343. }
  8344. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8345. };
  8346. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8347. var subMeshes;
  8348. var len;
  8349. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8350. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8351. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8352. len = intersections.length;
  8353. subMeshes = intersections.data;
  8354. } else {
  8355. subMeshes = this.subMeshes;
  8356. len = subMeshes.length;
  8357. }
  8358. for (var index = 0; index < len; index++) {
  8359. var subMesh = subMeshes[index];
  8360. if (len > 1 && !subMesh._checkCollision(collider))
  8361. continue;
  8362. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8363. }
  8364. };
  8365. AbstractMesh.prototype._checkCollision = function (collider) {
  8366. if (!this._boundingInfo._checkCollision(collider))
  8367. return;
  8368. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8369. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8370. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8371. };
  8372. AbstractMesh.prototype._generatePointsArray = function () {
  8373. return false;
  8374. };
  8375. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8376. var pickingInfo = new BABYLON.PickingInfo();
  8377. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8378. return pickingInfo;
  8379. }
  8380. if (!this._generatePointsArray()) {
  8381. return pickingInfo;
  8382. }
  8383. var intersectInfo = null;
  8384. var subMeshes;
  8385. var len;
  8386. if (this._submeshesOctree && this.useOctreeForPicking) {
  8387. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8388. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8389. len = intersections.length;
  8390. subMeshes = intersections.data;
  8391. } else {
  8392. subMeshes = this.subMeshes;
  8393. len = subMeshes.length;
  8394. }
  8395. for (var index = 0; index < len; index++) {
  8396. var subMesh = subMeshes[index];
  8397. if (len > 1 && !subMesh.canIntersects(ray))
  8398. continue;
  8399. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8400. if (currentIntersectInfo) {
  8401. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8402. intersectInfo = currentIntersectInfo;
  8403. if (fastCheck) {
  8404. break;
  8405. }
  8406. }
  8407. }
  8408. }
  8409. if (intersectInfo) {
  8410. var world = this.getWorldMatrix();
  8411. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8412. var direction = ray.direction.clone();
  8413. direction.normalize();
  8414. direction = direction.scale(intersectInfo.distance);
  8415. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8416. var pickedPoint = worldOrigin.add(worldDirection);
  8417. pickingInfo.hit = true;
  8418. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8419. pickingInfo.pickedPoint = pickedPoint;
  8420. pickingInfo.pickedMesh = this;
  8421. pickingInfo.bu = intersectInfo.bu;
  8422. pickingInfo.bv = intersectInfo.bv;
  8423. pickingInfo.faceId = intersectInfo.faceId;
  8424. return pickingInfo;
  8425. }
  8426. return pickingInfo;
  8427. };
  8428. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8429. return null;
  8430. };
  8431. AbstractMesh.prototype.releaseSubMeshes = function () {
  8432. if (this.subMeshes) {
  8433. while (this.subMeshes.length) {
  8434. this.subMeshes[0].dispose();
  8435. }
  8436. } else {
  8437. this.subMeshes = new Array();
  8438. }
  8439. };
  8440. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8441. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8442. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8443. }
  8444. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8445. var other = this._intersectionsInProgress[index];
  8446. var pos = other._intersectionsInProgress.indexOf(this);
  8447. other._intersectionsInProgress.splice(pos, 1);
  8448. }
  8449. this._intersectionsInProgress = [];
  8450. this.releaseSubMeshes();
  8451. var index = this.getScene().meshes.indexOf(this);
  8452. if (index != -1) {
  8453. this.getScene().meshes.splice(index, 1);
  8454. }
  8455. if (!doNotRecurse) {
  8456. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8457. if (this.getScene().particleSystems[index].emitter == this) {
  8458. this.getScene().particleSystems[index].dispose();
  8459. index--;
  8460. }
  8461. }
  8462. var objects = this.getScene().meshes.slice(0);
  8463. for (index = 0; index < objects.length; index++) {
  8464. if (objects[index].parent == this) {
  8465. objects[index].dispose();
  8466. }
  8467. }
  8468. } else {
  8469. for (index = 0; index < this.getScene().meshes.length; index++) {
  8470. var obj = this.getScene().meshes[index];
  8471. if (obj.parent === this) {
  8472. obj.parent = null;
  8473. obj.computeWorldMatrix(true);
  8474. }
  8475. }
  8476. }
  8477. this._onAfterWorldMatrixUpdate = [];
  8478. this._isDisposed = true;
  8479. if (this.onDispose) {
  8480. this.onDispose();
  8481. }
  8482. };
  8483. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8484. AbstractMesh._BILLBOARDMODE_X = 1;
  8485. AbstractMesh._BILLBOARDMODE_Y = 2;
  8486. AbstractMesh._BILLBOARDMODE_Z = 4;
  8487. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8488. return AbstractMesh;
  8489. })(BABYLON.Node);
  8490. BABYLON.AbstractMesh = AbstractMesh;
  8491. })(BABYLON || (BABYLON = {}));
  8492. var __extends = this.__extends || function (d, b) {
  8493. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8494. function __() { this.constructor = d; }
  8495. __.prototype = b.prototype;
  8496. d.prototype = new __();
  8497. };
  8498. var BABYLON;
  8499. (function (BABYLON) {
  8500. var _InstancesBatch = (function () {
  8501. function _InstancesBatch() {
  8502. this.mustReturn = false;
  8503. this.visibleInstances = new Array();
  8504. this.renderSelf = new Array();
  8505. }
  8506. return _InstancesBatch;
  8507. })();
  8508. BABYLON._InstancesBatch = _InstancesBatch;
  8509. var Mesh = (function (_super) {
  8510. __extends(Mesh, _super);
  8511. function Mesh(name, scene) {
  8512. _super.call(this, name, scene);
  8513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8514. this.instances = new Array();
  8515. this._LODLevels = new Array();
  8516. this._onBeforeRenderCallbacks = new Array();
  8517. this._onAfterRenderCallbacks = new Array();
  8518. this._visibleInstances = {};
  8519. this._renderIdForInstances = new Array();
  8520. this._batchCache = new _InstancesBatch();
  8521. this._instancesBufferSize = 32 * 16 * 4;
  8522. }
  8523. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  8524. get: function () {
  8525. return this._LODLevels.length > 0;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Mesh.prototype._sortLODLevels = function () {
  8531. this._LODLevels.sort(function (a, b) {
  8532. if (a.distance < b.distance) {
  8533. return 1;
  8534. }
  8535. if (a.distance > b.distance) {
  8536. return -1;
  8537. }
  8538. return 0;
  8539. });
  8540. };
  8541. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8542. if (mesh && mesh._masterMesh) {
  8543. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  8544. return this;
  8545. }
  8546. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8547. this._LODLevels.push(level);
  8548. if (mesh) {
  8549. mesh._masterMesh = this;
  8550. }
  8551. this._sortLODLevels();
  8552. return this;
  8553. };
  8554. Mesh.prototype.removeLODLevel = function (mesh) {
  8555. for (var index = 0; index < this._LODLevels.length; index++) {
  8556. if (this._LODLevels[index].mesh === mesh) {
  8557. this._LODLevels.splice(index, 1);
  8558. if (mesh) {
  8559. mesh._masterMesh = null;
  8560. }
  8561. }
  8562. }
  8563. this._sortLODLevels();
  8564. return this;
  8565. };
  8566. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  8567. if (!this._LODLevels || this._LODLevels.length === 0) {
  8568. return this;
  8569. }
  8570. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  8571. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  8572. return this;
  8573. }
  8574. for (var index = 0; index < this._LODLevels.length; index++) {
  8575. var level = this._LODLevels[index];
  8576. if (level.distance < distanceToCamera) {
  8577. if (level.mesh) {
  8578. level.mesh._preActivate();
  8579. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8580. }
  8581. return level.mesh;
  8582. }
  8583. }
  8584. return this;
  8585. };
  8586. Object.defineProperty(Mesh.prototype, "geometry", {
  8587. get: function () {
  8588. return this._geometry;
  8589. },
  8590. enumerable: true,
  8591. configurable: true
  8592. });
  8593. Mesh.prototype.getTotalVertices = function () {
  8594. if (!this._geometry) {
  8595. return 0;
  8596. }
  8597. return this._geometry.getTotalVertices();
  8598. };
  8599. Mesh.prototype.getVerticesData = function (kind) {
  8600. if (!this._geometry) {
  8601. return null;
  8602. }
  8603. return this._geometry.getVerticesData(kind);
  8604. };
  8605. Mesh.prototype.getVertexBuffer = function (kind) {
  8606. if (!this._geometry) {
  8607. return undefined;
  8608. }
  8609. return this._geometry.getVertexBuffer(kind);
  8610. };
  8611. Mesh.prototype.isVerticesDataPresent = function (kind) {
  8612. if (!this._geometry) {
  8613. if (this._delayInfo) {
  8614. return this._delayInfo.indexOf(kind) !== -1;
  8615. }
  8616. return false;
  8617. }
  8618. return this._geometry.isVerticesDataPresent(kind);
  8619. };
  8620. Mesh.prototype.getVerticesDataKinds = function () {
  8621. if (!this._geometry) {
  8622. var result = [];
  8623. if (this._delayInfo) {
  8624. for (var kind in this._delayInfo) {
  8625. result.push(kind);
  8626. }
  8627. }
  8628. return result;
  8629. }
  8630. return this._geometry.getVerticesDataKinds();
  8631. };
  8632. Mesh.prototype.getTotalIndices = function () {
  8633. if (!this._geometry) {
  8634. return 0;
  8635. }
  8636. return this._geometry.getTotalIndices();
  8637. };
  8638. Mesh.prototype.getIndices = function () {
  8639. if (!this._geometry) {
  8640. return [];
  8641. }
  8642. return this._geometry.getIndices();
  8643. };
  8644. Object.defineProperty(Mesh.prototype, "isBlocked", {
  8645. get: function () {
  8646. return this._masterMesh !== null && this._masterMesh !== undefined;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Mesh.prototype.isReady = function () {
  8652. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8653. return false;
  8654. }
  8655. return _super.prototype.isReady.call(this);
  8656. };
  8657. Mesh.prototype.isDisposed = function () {
  8658. return this._isDisposed;
  8659. };
  8660. Mesh.prototype._preActivate = function () {
  8661. var sceneRenderId = this.getScene().getRenderId();
  8662. if (this._preActivateId == sceneRenderId) {
  8663. return;
  8664. }
  8665. this._preActivateId = sceneRenderId;
  8666. this._visibleInstances = null;
  8667. };
  8668. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  8669. if (!this._visibleInstances) {
  8670. this._visibleInstances = {};
  8671. this._visibleInstances.defaultRenderId = renderId;
  8672. this._visibleInstances.selfDefaultRenderId = this._renderId;
  8673. }
  8674. if (!this._visibleInstances[renderId]) {
  8675. this._visibleInstances[renderId] = new Array();
  8676. }
  8677. this._visibleInstances[renderId].push(instance);
  8678. };
  8679. Mesh.prototype.refreshBoundingInfo = function () {
  8680. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8681. if (data) {
  8682. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  8683. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  8684. }
  8685. if (this.subMeshes) {
  8686. for (var index = 0; index < this.subMeshes.length; index++) {
  8687. this.subMeshes[index].refreshBoundingInfo();
  8688. }
  8689. }
  8690. this._updateBoundingInfo();
  8691. };
  8692. Mesh.prototype._createGlobalSubMesh = function () {
  8693. var totalVertices = this.getTotalVertices();
  8694. if (!totalVertices || !this.getIndices()) {
  8695. return null;
  8696. }
  8697. this.releaseSubMeshes();
  8698. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  8699. };
  8700. Mesh.prototype.subdivide = function (count) {
  8701. if (count < 1) {
  8702. return;
  8703. }
  8704. var totalIndices = this.getTotalIndices();
  8705. var subdivisionSize = (totalIndices / count) | 0;
  8706. var offset = 0;
  8707. while (subdivisionSize % 3 != 0) {
  8708. subdivisionSize++;
  8709. }
  8710. this.releaseSubMeshes();
  8711. for (var index = 0; index < count; index++) {
  8712. if (offset >= totalIndices) {
  8713. break;
  8714. }
  8715. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  8716. offset += subdivisionSize;
  8717. }
  8718. this.synchronizeInstances();
  8719. };
  8720. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  8721. if (kind instanceof Array) {
  8722. var temp = data;
  8723. data = kind;
  8724. kind = temp;
  8725. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  8726. }
  8727. if (!this._geometry) {
  8728. var vertexData = new BABYLON.VertexData();
  8729. vertexData.set(data, kind);
  8730. var scene = this.getScene();
  8731. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  8732. } else {
  8733. this._geometry.setVerticesData(kind, data, updatable, stride);
  8734. }
  8735. };
  8736. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  8737. if (!this._geometry) {
  8738. return;
  8739. }
  8740. if (!makeItUnique) {
  8741. this._geometry.updateVerticesData(kind, data, updateExtends);
  8742. } else {
  8743. this.makeGeometryUnique();
  8744. this.updateVerticesData(kind, data, updateExtends, false);
  8745. }
  8746. };
  8747. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
  8748. if (!this._geometry) {
  8749. return;
  8750. }
  8751. if (!makeItUnique) {
  8752. this._geometry.updateVerticesDataDirectly(kind, data);
  8753. } else {
  8754. this.makeGeometryUnique();
  8755. this.updateVerticesDataDirectly(kind, data, false);
  8756. }
  8757. };
  8758. Mesh.prototype.makeGeometryUnique = function () {
  8759. if (!this._geometry) {
  8760. return;
  8761. }
  8762. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  8763. geometry.applyToMesh(this);
  8764. };
  8765. Mesh.prototype.setIndices = function (indices) {
  8766. if (!this._geometry) {
  8767. var vertexData = new BABYLON.VertexData();
  8768. vertexData.indices = indices;
  8769. var scene = this.getScene();
  8770. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  8771. } else {
  8772. this._geometry.setIndices(indices);
  8773. }
  8774. };
  8775. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  8776. var engine = this.getScene().getEngine();
  8777. var indexToBind;
  8778. switch (fillMode) {
  8779. case BABYLON.Material.PointFillMode:
  8780. indexToBind = null;
  8781. break;
  8782. case BABYLON.Material.WireFrameFillMode:
  8783. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  8784. break;
  8785. default:
  8786. case BABYLON.Material.TriangleFillMode:
  8787. indexToBind = this._geometry.getIndexBuffer();
  8788. break;
  8789. }
  8790. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  8791. };
  8792. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  8793. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8794. return;
  8795. }
  8796. var engine = this.getScene().getEngine();
  8797. switch (fillMode) {
  8798. case BABYLON.Material.PointFillMode:
  8799. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  8800. break;
  8801. case BABYLON.Material.WireFrameFillMode:
  8802. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  8803. break;
  8804. default:
  8805. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  8806. }
  8807. };
  8808. Mesh.prototype.registerBeforeRender = function (func) {
  8809. this._onBeforeRenderCallbacks.push(func);
  8810. };
  8811. Mesh.prototype.unregisterBeforeRender = function (func) {
  8812. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8813. if (index > -1) {
  8814. this._onBeforeRenderCallbacks.splice(index, 1);
  8815. }
  8816. };
  8817. Mesh.prototype.registerAfterRender = function (func) {
  8818. this._onAfterRenderCallbacks.push(func);
  8819. };
  8820. Mesh.prototype.unregisterAfterRender = function (func) {
  8821. var index = this._onAfterRenderCallbacks.indexOf(func);
  8822. if (index > -1) {
  8823. this._onAfterRenderCallbacks.splice(index, 1);
  8824. }
  8825. };
  8826. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  8827. var scene = this.getScene();
  8828. this._batchCache.mustReturn = false;
  8829. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  8830. this._batchCache.visibleInstances[subMeshId] = null;
  8831. if (this._visibleInstances) {
  8832. var currentRenderId = scene.getRenderId();
  8833. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  8834. var selfRenderId = this._renderId;
  8835. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  8836. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  8837. currentRenderId = this._visibleInstances.defaultRenderId;
  8838. selfRenderId = this._visibleInstances.selfDefaultRenderId;
  8839. }
  8840. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  8841. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  8842. this._batchCache.mustReturn = true;
  8843. return this._batchCache;
  8844. }
  8845. if (currentRenderId !== selfRenderId) {
  8846. this._batchCache.renderSelf[subMeshId] = false;
  8847. }
  8848. }
  8849. this._renderIdForInstances[subMeshId] = currentRenderId;
  8850. }
  8851. return this._batchCache;
  8852. };
  8853. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  8854. var visibleInstances = batch.visibleInstances[subMesh._id];
  8855. var matricesCount = visibleInstances.length + 1;
  8856. var bufferSize = matricesCount * 16 * 4;
  8857. while (this._instancesBufferSize < bufferSize) {
  8858. this._instancesBufferSize *= 2;
  8859. }
  8860. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  8861. if (this._worldMatricesInstancesBuffer) {
  8862. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  8863. }
  8864. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  8865. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  8866. }
  8867. var offset = 0;
  8868. var instancesCount = 0;
  8869. var world = this.getWorldMatrix();
  8870. if (batch.renderSelf[subMesh._id]) {
  8871. world.copyToArray(this._worldMatricesInstancesArray, offset);
  8872. offset += 16;
  8873. instancesCount++;
  8874. }
  8875. if (visibleInstances) {
  8876. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  8877. var instance = visibleInstances[instanceIndex];
  8878. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  8879. offset += 16;
  8880. instancesCount++;
  8881. }
  8882. }
  8883. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  8884. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  8885. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  8886. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  8887. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  8888. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  8889. this._draw(subMesh, fillMode, instancesCount);
  8890. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  8891. };
  8892. Mesh.prototype.render = function (subMesh) {
  8893. var scene = this.getScene();
  8894. var batch = this._getInstancesRenderList(subMesh._id);
  8895. if (batch.mustReturn) {
  8896. return;
  8897. }
  8898. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  8899. return;
  8900. }
  8901. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8902. this._onBeforeRenderCallbacks[callbackIndex]();
  8903. }
  8904. var engine = scene.getEngine();
  8905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  8906. var effectiveMaterial = subMesh.getMaterial();
  8907. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  8908. return;
  8909. }
  8910. var savedDepthWrite = engine.getDepthWrite();
  8911. if (this.renderOutline) {
  8912. engine.setDepthWrite(false);
  8913. scene.getOutlineRenderer().render(subMesh, batch);
  8914. engine.setDepthWrite(savedDepthWrite);
  8915. }
  8916. effectiveMaterial._preBind();
  8917. var effect = effectiveMaterial.getEffect();
  8918. var fillMode = scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode;
  8919. this._bind(subMesh, effect, fillMode);
  8920. var world = this.getWorldMatrix();
  8921. effectiveMaterial.bind(world, this);
  8922. if (hardwareInstancedRendering) {
  8923. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  8924. } else {
  8925. if (batch.renderSelf[subMesh._id]) {
  8926. this._draw(subMesh, fillMode);
  8927. }
  8928. if (batch.visibleInstances[subMesh._id]) {
  8929. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  8930. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  8931. world = instance.getWorldMatrix();
  8932. effectiveMaterial.bindOnlyWorldMatrix(world);
  8933. this._draw(subMesh, fillMode);
  8934. }
  8935. }
  8936. }
  8937. effectiveMaterial.unbind();
  8938. if (this.renderOutline && savedDepthWrite) {
  8939. engine.setDepthWrite(true);
  8940. engine.setColorWrite(false);
  8941. scene.getOutlineRenderer().render(subMesh, batch);
  8942. engine.setColorWrite(true);
  8943. }
  8944. if (this.renderOverlay) {
  8945. var currentMode = engine.getAlphaMode();
  8946. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  8947. scene.getOutlineRenderer().render(subMesh, batch, true);
  8948. engine.setAlphaMode(currentMode);
  8949. }
  8950. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8951. this._onAfterRenderCallbacks[callbackIndex]();
  8952. }
  8953. };
  8954. Mesh.prototype.getEmittedParticleSystems = function () {
  8955. var results = new Array();
  8956. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8957. var particleSystem = this.getScene().particleSystems[index];
  8958. if (particleSystem.emitter === this) {
  8959. results.push(particleSystem);
  8960. }
  8961. }
  8962. return results;
  8963. };
  8964. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  8965. var results = new Array();
  8966. var descendants = this.getDescendants();
  8967. descendants.push(this);
  8968. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  8969. var particleSystem = this.getScene().particleSystems[index];
  8970. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  8971. results.push(particleSystem);
  8972. }
  8973. }
  8974. return results;
  8975. };
  8976. Mesh.prototype.getChildren = function () {
  8977. var results = [];
  8978. for (var index = 0; index < this.getScene().meshes.length; index++) {
  8979. var mesh = this.getScene().meshes[index];
  8980. if (mesh.parent == this) {
  8981. results.push(mesh);
  8982. }
  8983. }
  8984. return results;
  8985. };
  8986. Mesh.prototype._checkDelayState = function () {
  8987. var _this = this;
  8988. var that = this;
  8989. var scene = this.getScene();
  8990. if (this._geometry) {
  8991. this._geometry.load(scene);
  8992. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  8993. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  8994. scene._addPendingData(that);
  8995. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  8996. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  8997. if (data instanceof ArrayBuffer) {
  8998. _this._delayLoadingFunction(data, _this);
  8999. } else {
  9000. _this._delayLoadingFunction(JSON.parse(data), _this);
  9001. }
  9002. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9003. scene._removePendingData(_this);
  9004. }, function () {
  9005. }, scene.database, getBinaryData);
  9006. }
  9007. };
  9008. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9009. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9010. return false;
  9011. }
  9012. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9013. return false;
  9014. }
  9015. this._checkDelayState();
  9016. return true;
  9017. };
  9018. Mesh.prototype.setMaterialByID = function (id) {
  9019. var materials = this.getScene().materials;
  9020. for (var index = 0; index < materials.length; index++) {
  9021. if (materials[index].id == id) {
  9022. this.material = materials[index];
  9023. return;
  9024. }
  9025. }
  9026. var multiMaterials = this.getScene().multiMaterials;
  9027. for (index = 0; index < multiMaterials.length; index++) {
  9028. if (multiMaterials[index].id == id) {
  9029. this.material = multiMaterials[index];
  9030. return;
  9031. }
  9032. }
  9033. };
  9034. Mesh.prototype.getAnimatables = function () {
  9035. var results = [];
  9036. if (this.material) {
  9037. results.push(this.material);
  9038. }
  9039. if (this.skeleton) {
  9040. results.push(this.skeleton);
  9041. }
  9042. return results;
  9043. };
  9044. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9045. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9046. return;
  9047. }
  9048. this._resetPointsArrayCache();
  9049. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9050. var temp = [];
  9051. for (var index = 0; index < data.length; index += 3) {
  9052. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9053. }
  9054. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9055. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9056. return;
  9057. }
  9058. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9059. for (index = 0; index < data.length; index += 3) {
  9060. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9061. }
  9062. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9063. };
  9064. Mesh.prototype._resetPointsArrayCache = function () {
  9065. this._positions = null;
  9066. };
  9067. Mesh.prototype._generatePointsArray = function () {
  9068. if (this._positions)
  9069. return true;
  9070. this._positions = [];
  9071. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9072. if (!data) {
  9073. return false;
  9074. }
  9075. for (var index = 0; index < data.length; index += 3) {
  9076. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9077. }
  9078. return true;
  9079. };
  9080. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9081. var result = new BABYLON.Mesh(name, this.getScene());
  9082. this._geometry.applyToMesh(result);
  9083. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  9084. result.material = this.material;
  9085. if (newParent) {
  9086. result.parent = newParent;
  9087. }
  9088. if (!doNotCloneChildren) {
  9089. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9090. var mesh = this.getScene().meshes[index];
  9091. if (mesh.parent == this) {
  9092. mesh.clone(mesh.name, result);
  9093. }
  9094. }
  9095. }
  9096. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9097. var system = this.getScene().particleSystems[index];
  9098. if (system.emitter == this) {
  9099. system.clone(system.name, result);
  9100. }
  9101. }
  9102. result.computeWorldMatrix(true);
  9103. return result;
  9104. };
  9105. Mesh.prototype.dispose = function (doNotRecurse) {
  9106. if (this._geometry) {
  9107. this._geometry.releaseForMesh(this, true);
  9108. }
  9109. if (this._worldMatricesInstancesBuffer) {
  9110. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9111. this._worldMatricesInstancesBuffer = null;
  9112. }
  9113. while (this.instances.length) {
  9114. this.instances[0].dispose();
  9115. }
  9116. _super.prototype.dispose.call(this, doNotRecurse);
  9117. };
  9118. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9119. var _this = this;
  9120. var scene = this.getScene();
  9121. var onload = function (img) {
  9122. var canvas = document.createElement("canvas");
  9123. var context = canvas.getContext("2d");
  9124. var heightMapWidth = img.width;
  9125. var heightMapHeight = img.height;
  9126. canvas.width = heightMapWidth;
  9127. canvas.height = heightMapHeight;
  9128. context.drawImage(img, 0, 0);
  9129. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9130. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9131. };
  9132. BABYLON.Tools.LoadImage(url, onload, function () {
  9133. }, scene.database);
  9134. };
  9135. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9137. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9138. return;
  9139. }
  9140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9141. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9142. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9143. var position = BABYLON.Vector3.Zero();
  9144. var normal = BABYLON.Vector3.Zero();
  9145. var uv = BABYLON.Vector2.Zero();
  9146. for (var index = 0; index < positions.length; index += 3) {
  9147. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9148. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9149. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9150. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9151. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9152. var pos = (u + v * heightMapWidth) * 4;
  9153. var r = buffer[pos] / 255.0;
  9154. var g = buffer[pos + 1] / 255.0;
  9155. var b = buffer[pos + 2] / 255.0;
  9156. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9157. normal.normalize();
  9158. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9159. position = position.add(normal);
  9160. position.toArray(positions, index);
  9161. }
  9162. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9163. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9164. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9165. };
  9166. Mesh.prototype.convertToFlatShadedMesh = function () {
  9167. var kinds = this.getVerticesDataKinds();
  9168. var vbs = [];
  9169. var data = [];
  9170. var newdata = [];
  9171. var updatableNormals = false;
  9172. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9173. var kind = kinds[kindIndex];
  9174. var vertexBuffer = this.getVertexBuffer(kind);
  9175. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9176. updatableNormals = vertexBuffer.isUpdatable();
  9177. kinds.splice(kindIndex, 1);
  9178. kindIndex--;
  9179. continue;
  9180. }
  9181. vbs[kind] = vertexBuffer;
  9182. data[kind] = vbs[kind].getData();
  9183. newdata[kind] = [];
  9184. }
  9185. var previousSubmeshes = this.subMeshes.slice(0);
  9186. var indices = this.getIndices();
  9187. var totalIndices = this.getTotalIndices();
  9188. for (index = 0; index < totalIndices; index++) {
  9189. var vertexIndex = indices[index];
  9190. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9191. kind = kinds[kindIndex];
  9192. var stride = vbs[kind].getStrideSize();
  9193. for (var offset = 0; offset < stride; offset++) {
  9194. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9195. }
  9196. }
  9197. }
  9198. var normals = [];
  9199. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9200. for (var index = 0; index < totalIndices; index += 3) {
  9201. indices[index] = index;
  9202. indices[index + 1] = index + 1;
  9203. indices[index + 2] = index + 2;
  9204. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9205. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9206. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9207. var p1p2 = p1.subtract(p2);
  9208. var p3p2 = p3.subtract(p2);
  9209. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9210. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9211. normals.push(normal.x);
  9212. normals.push(normal.y);
  9213. normals.push(normal.z);
  9214. }
  9215. }
  9216. this.setIndices(indices);
  9217. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9218. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9219. kind = kinds[kindIndex];
  9220. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9221. }
  9222. this.releaseSubMeshes();
  9223. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9224. var previousOne = previousSubmeshes[submeshIndex];
  9225. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9226. }
  9227. this.synchronizeInstances();
  9228. };
  9229. Mesh.prototype.createInstance = function (name) {
  9230. return new BABYLON.InstancedMesh(name, this);
  9231. };
  9232. Mesh.prototype.synchronizeInstances = function () {
  9233. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9234. var instance = this.instances[instanceIndex];
  9235. instance._syncSubMeshes();
  9236. }
  9237. };
  9238. Mesh.CreateBox = function (name, size, scene, updatable) {
  9239. var box = new BABYLON.Mesh(name, scene);
  9240. var vertexData = BABYLON.VertexData.CreateBox(size);
  9241. vertexData.applyToMesh(box, updatable);
  9242. return box;
  9243. };
  9244. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9245. var sphere = new BABYLON.Mesh(name, scene);
  9246. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9247. vertexData.applyToMesh(sphere, updatable);
  9248. return sphere;
  9249. };
  9250. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9251. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9252. if (scene !== undefined) {
  9253. updatable = scene;
  9254. }
  9255. scene = subdivisions;
  9256. subdivisions = 1;
  9257. }
  9258. var cylinder = new BABYLON.Mesh(name, scene);
  9259. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9260. vertexData.applyToMesh(cylinder, updatable);
  9261. return cylinder;
  9262. };
  9263. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9264. var torus = new BABYLON.Mesh(name, scene);
  9265. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9266. vertexData.applyToMesh(torus, updatable);
  9267. return torus;
  9268. };
  9269. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9270. var torusKnot = new BABYLON.Mesh(name, scene);
  9271. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9272. vertexData.applyToMesh(torusKnot, updatable);
  9273. return torusKnot;
  9274. };
  9275. Mesh.CreateLines = function (name, points, scene, updatable) {
  9276. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9277. var vertexData = BABYLON.VertexData.CreateLines(points);
  9278. vertexData.applyToMesh(lines, updatable);
  9279. return lines;
  9280. };
  9281. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9282. var plane = new BABYLON.Mesh(name, scene);
  9283. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9284. vertexData.applyToMesh(plane, updatable);
  9285. return plane;
  9286. };
  9287. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9288. var ground = new BABYLON.GroundMesh(name, scene);
  9289. ground._setReady(false);
  9290. ground._subdivisions = subdivisions;
  9291. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9292. vertexData.applyToMesh(ground, updatable);
  9293. ground._setReady(true);
  9294. return ground;
  9295. };
  9296. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9297. var tiledGround = new BABYLON.Mesh(name, scene);
  9298. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9299. vertexData.applyToMesh(tiledGround, updatable);
  9300. return tiledGround;
  9301. };
  9302. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9303. var ground = new BABYLON.GroundMesh(name, scene);
  9304. ground._subdivisions = subdivisions;
  9305. ground._setReady(false);
  9306. var onload = function (img) {
  9307. var canvas = document.createElement("canvas");
  9308. var context = canvas.getContext("2d");
  9309. var heightMapWidth = img.width;
  9310. var heightMapHeight = img.height;
  9311. canvas.width = heightMapWidth;
  9312. canvas.height = heightMapHeight;
  9313. context.drawImage(img, 0, 0);
  9314. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9315. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9316. vertexData.applyToMesh(ground, updatable);
  9317. ground._setReady(true);
  9318. };
  9319. BABYLON.Tools.LoadImage(url, onload, function () {
  9320. }, scene.database);
  9321. return ground;
  9322. };
  9323. Mesh.MinMax = function (meshes) {
  9324. var minVector = null;
  9325. var maxVector = null;
  9326. for (var i in meshes) {
  9327. var mesh = meshes[i];
  9328. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9329. if (!minVector) {
  9330. minVector = boundingBox.minimumWorld;
  9331. maxVector = boundingBox.maximumWorld;
  9332. continue;
  9333. }
  9334. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9335. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9336. }
  9337. return {
  9338. min: minVector,
  9339. max: maxVector
  9340. };
  9341. };
  9342. Mesh.Center = function (meshesOrMinMaxVector) {
  9343. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9344. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9345. };
  9346. return Mesh;
  9347. })(BABYLON.AbstractMesh);
  9348. BABYLON.Mesh = Mesh;
  9349. })(BABYLON || (BABYLON = {}));
  9350. var __extends = this.__extends || function (d, b) {
  9351. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9352. function __() { this.constructor = d; }
  9353. __.prototype = b.prototype;
  9354. d.prototype = new __();
  9355. };
  9356. var BABYLON;
  9357. (function (BABYLON) {
  9358. var GroundMesh = (function (_super) {
  9359. __extends(GroundMesh, _super);
  9360. function GroundMesh(name, scene) {
  9361. _super.call(this, name, scene);
  9362. this.generateOctree = false;
  9363. this._worldInverse = new BABYLON.Matrix();
  9364. }
  9365. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9366. get: function () {
  9367. return this._subdivisions;
  9368. },
  9369. enumerable: true,
  9370. configurable: true
  9371. });
  9372. GroundMesh.prototype.optimize = function (chunksCount) {
  9373. this.subdivide(this._subdivisions);
  9374. this.createOrUpdateSubmeshesOctree(32);
  9375. };
  9376. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9377. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9378. this.getWorldMatrix().invertToRef(this._worldInverse);
  9379. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9380. var pickInfo = this.intersects(ray);
  9381. if (pickInfo.hit) {
  9382. return pickInfo.pickedPoint.y;
  9383. }
  9384. return 0;
  9385. };
  9386. return GroundMesh;
  9387. })(BABYLON.Mesh);
  9388. BABYLON.GroundMesh = GroundMesh;
  9389. })(BABYLON || (BABYLON = {}));
  9390. var __extends = this.__extends || function (d, b) {
  9391. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9392. function __() { this.constructor = d; }
  9393. __.prototype = b.prototype;
  9394. d.prototype = new __();
  9395. };
  9396. var BABYLON;
  9397. (function (BABYLON) {
  9398. var InstancedMesh = (function (_super) {
  9399. __extends(InstancedMesh, _super);
  9400. function InstancedMesh(name, source) {
  9401. _super.call(this, name, source.getScene());
  9402. source.instances.push(this);
  9403. this._sourceMesh = source;
  9404. this.position.copyFrom(source.position);
  9405. this.rotation.copyFrom(source.rotation);
  9406. this.scaling.copyFrom(source.scaling);
  9407. if (source.rotationQuaternion) {
  9408. this.rotationQuaternion = source.rotationQuaternion.clone();
  9409. }
  9410. this.infiniteDistance = source.infiniteDistance;
  9411. this.setPivotMatrix(source.getPivotMatrix());
  9412. this.refreshBoundingInfo();
  9413. this._syncSubMeshes();
  9414. }
  9415. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9416. get: function () {
  9417. return this._sourceMesh.receiveShadows;
  9418. },
  9419. enumerable: true,
  9420. configurable: true
  9421. });
  9422. Object.defineProperty(InstancedMesh.prototype, "material", {
  9423. get: function () {
  9424. return this._sourceMesh.material;
  9425. },
  9426. enumerable: true,
  9427. configurable: true
  9428. });
  9429. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9430. get: function () {
  9431. return this._sourceMesh.visibility;
  9432. },
  9433. enumerable: true,
  9434. configurable: true
  9435. });
  9436. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9437. get: function () {
  9438. return this._sourceMesh.skeleton;
  9439. },
  9440. enumerable: true,
  9441. configurable: true
  9442. });
  9443. InstancedMesh.prototype.getTotalVertices = function () {
  9444. return this._sourceMesh.getTotalVertices();
  9445. };
  9446. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9447. get: function () {
  9448. return this._sourceMesh;
  9449. },
  9450. enumerable: true,
  9451. configurable: true
  9452. });
  9453. InstancedMesh.prototype.getVerticesData = function (kind) {
  9454. return this._sourceMesh.getVerticesData(kind);
  9455. };
  9456. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9457. return this._sourceMesh.isVerticesDataPresent(kind);
  9458. };
  9459. InstancedMesh.prototype.getIndices = function () {
  9460. return this._sourceMesh.getIndices();
  9461. };
  9462. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9463. get: function () {
  9464. return this._sourceMesh._positions;
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9470. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9471. if (data) {
  9472. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9473. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9474. }
  9475. this._updateBoundingInfo();
  9476. };
  9477. InstancedMesh.prototype._preActivate = function () {
  9478. if (this._currentLOD) {
  9479. this._currentLOD._preActivate();
  9480. }
  9481. };
  9482. InstancedMesh.prototype._activate = function (renderId) {
  9483. if (this._currentLOD) {
  9484. this._currentLOD._registerInstanceForRenderId(this, renderId);
  9485. }
  9486. };
  9487. InstancedMesh.prototype.getLOD = function (camera) {
  9488. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  9489. return this._currentLOD;
  9490. };
  9491. InstancedMesh.prototype._syncSubMeshes = function () {
  9492. this.releaseSubMeshes();
  9493. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  9494. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  9495. }
  9496. };
  9497. InstancedMesh.prototype._generatePointsArray = function () {
  9498. return this._sourceMesh._generatePointsArray();
  9499. };
  9500. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9501. var result = this._sourceMesh.createInstance(name);
  9502. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  9503. this.refreshBoundingInfo();
  9504. if (newParent) {
  9505. result.parent = newParent;
  9506. }
  9507. if (!doNotCloneChildren) {
  9508. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9509. var mesh = this.getScene().meshes[index];
  9510. if (mesh.parent == this) {
  9511. mesh.clone(mesh.name, result);
  9512. }
  9513. }
  9514. }
  9515. result.computeWorldMatrix(true);
  9516. return result;
  9517. };
  9518. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  9519. var index = this._sourceMesh.instances.indexOf(this);
  9520. this._sourceMesh.instances.splice(index, 1);
  9521. _super.prototype.dispose.call(this, doNotRecurse);
  9522. };
  9523. return InstancedMesh;
  9524. })(BABYLON.AbstractMesh);
  9525. BABYLON.InstancedMesh = InstancedMesh;
  9526. })(BABYLON || (BABYLON = {}));
  9527. var BABYLON;
  9528. (function (BABYLON) {
  9529. var SubMesh = (function () {
  9530. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  9531. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  9532. this.materialIndex = materialIndex;
  9533. this.verticesStart = verticesStart;
  9534. this.verticesCount = verticesCount;
  9535. this.indexStart = indexStart;
  9536. this.indexCount = indexCount;
  9537. this._renderId = 0;
  9538. this._mesh = mesh;
  9539. this._renderingMesh = renderingMesh || mesh;
  9540. mesh.subMeshes.push(this);
  9541. this._id = mesh.subMeshes.length - 1;
  9542. if (createBoundingBox) {
  9543. this.refreshBoundingInfo();
  9544. }
  9545. }
  9546. SubMesh.prototype.getBoundingInfo = function () {
  9547. return this._boundingInfo;
  9548. };
  9549. SubMesh.prototype.getMesh = function () {
  9550. return this._mesh;
  9551. };
  9552. SubMesh.prototype.getRenderingMesh = function () {
  9553. return this._renderingMesh;
  9554. };
  9555. SubMesh.prototype.getMaterial = function () {
  9556. var rootMaterial = this._renderingMesh.material;
  9557. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  9558. var multiMaterial = rootMaterial;
  9559. return multiMaterial.getSubMaterial(this.materialIndex);
  9560. }
  9561. if (!rootMaterial) {
  9562. return this._mesh.getScene().defaultMaterial;
  9563. }
  9564. return rootMaterial;
  9565. };
  9566. SubMesh.prototype.refreshBoundingInfo = function () {
  9567. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9568. if (!data) {
  9569. this._boundingInfo = this._mesh._boundingInfo;
  9570. return;
  9571. }
  9572. var indices = this._renderingMesh.getIndices();
  9573. var extend;
  9574. if (this.indexStart === 0 && this.indexCount === indices.length) {
  9575. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  9576. } else {
  9577. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  9578. }
  9579. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9580. };
  9581. SubMesh.prototype._checkCollision = function (collider) {
  9582. return this._boundingInfo._checkCollision(collider);
  9583. };
  9584. SubMesh.prototype.updateBoundingInfo = function (world) {
  9585. if (!this._boundingInfo) {
  9586. this.refreshBoundingInfo();
  9587. }
  9588. this._boundingInfo._update(world);
  9589. };
  9590. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  9591. return this._boundingInfo.isInFrustum(frustumPlanes);
  9592. };
  9593. SubMesh.prototype.render = function () {
  9594. this._renderingMesh.render(this);
  9595. };
  9596. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  9597. if (!this._linesIndexBuffer) {
  9598. var linesIndices = [];
  9599. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9600. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  9601. }
  9602. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  9603. this.linesIndexCount = linesIndices.length;
  9604. }
  9605. return this._linesIndexBuffer;
  9606. };
  9607. SubMesh.prototype.canIntersects = function (ray) {
  9608. return ray.intersectsBox(this._boundingInfo.boundingBox);
  9609. };
  9610. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  9611. var intersectInfo = null;
  9612. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  9613. var p0 = positions[indices[index]];
  9614. var p1 = positions[indices[index + 1]];
  9615. var p2 = positions[indices[index + 2]];
  9616. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  9617. if (currentIntersectInfo) {
  9618. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9619. intersectInfo = currentIntersectInfo;
  9620. intersectInfo.faceId = index / 3;
  9621. if (fastCheck) {
  9622. break;
  9623. }
  9624. }
  9625. }
  9626. }
  9627. return intersectInfo;
  9628. };
  9629. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  9630. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  9631. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  9632. return result;
  9633. };
  9634. SubMesh.prototype.dispose = function () {
  9635. if (this._linesIndexBuffer) {
  9636. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  9637. this._linesIndexBuffer = null;
  9638. }
  9639. var index = this._mesh.subMeshes.indexOf(this);
  9640. this._mesh.subMeshes.splice(index, 1);
  9641. };
  9642. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  9643. var minVertexIndex = Number.MAX_VALUE;
  9644. var maxVertexIndex = -Number.MAX_VALUE;
  9645. renderingMesh = renderingMesh || mesh;
  9646. var indices = renderingMesh.getIndices();
  9647. for (var index = startIndex; index < startIndex + indexCount; index++) {
  9648. var vertexIndex = indices[index];
  9649. if (vertexIndex < minVertexIndex)
  9650. minVertexIndex = vertexIndex;
  9651. if (vertexIndex > maxVertexIndex)
  9652. maxVertexIndex = vertexIndex;
  9653. }
  9654. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  9655. };
  9656. return SubMesh;
  9657. })();
  9658. BABYLON.SubMesh = SubMesh;
  9659. })(BABYLON || (BABYLON = {}));
  9660. var BABYLON;
  9661. (function (BABYLON) {
  9662. var BaseTexture = (function () {
  9663. function BaseTexture(scene) {
  9664. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9665. this.hasAlpha = false;
  9666. this.getAlphaFromRGB = false;
  9667. this.level = 1;
  9668. this.isCube = false;
  9669. this.isRenderTarget = false;
  9670. this.animations = new Array();
  9671. this.coordinatesIndex = 0;
  9672. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  9673. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  9674. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  9675. this.anisotropicFilteringLevel = 4;
  9676. this._scene = scene;
  9677. this._scene.textures.push(this);
  9678. }
  9679. BaseTexture.prototype.getScene = function () {
  9680. return this._scene;
  9681. };
  9682. BaseTexture.prototype.getTextureMatrix = function () {
  9683. return null;
  9684. };
  9685. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  9686. return null;
  9687. };
  9688. BaseTexture.prototype.getInternalTexture = function () {
  9689. return this._texture;
  9690. };
  9691. BaseTexture.prototype.isReady = function () {
  9692. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9693. return true;
  9694. }
  9695. if (this._texture) {
  9696. return this._texture.isReady;
  9697. }
  9698. return false;
  9699. };
  9700. BaseTexture.prototype.getSize = function () {
  9701. if (this._texture._width) {
  9702. return { width: this._texture._width, height: this._texture._height };
  9703. }
  9704. if (this._texture._size) {
  9705. return { width: this._texture._size, height: this._texture._size };
  9706. }
  9707. return { width: 0, height: 0 };
  9708. };
  9709. BaseTexture.prototype.getBaseSize = function () {
  9710. if (!this.isReady())
  9711. return { width: 0, height: 0 };
  9712. if (this._texture._size) {
  9713. return { width: this._texture._size, height: this._texture._size };
  9714. }
  9715. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  9716. };
  9717. BaseTexture.prototype.scale = function (ratio) {
  9718. };
  9719. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  9720. get: function () {
  9721. return false;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  9727. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9728. for (var index = 0; index < texturesCache.length; index++) {
  9729. var texturesCacheEntry = texturesCache[index];
  9730. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9731. texturesCache.splice(index, 1);
  9732. return;
  9733. }
  9734. }
  9735. };
  9736. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  9737. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9738. for (var index = 0; index < texturesCache.length; index++) {
  9739. var texturesCacheEntry = texturesCache[index];
  9740. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  9741. texturesCacheEntry.references++;
  9742. return texturesCacheEntry;
  9743. }
  9744. }
  9745. return null;
  9746. };
  9747. BaseTexture.prototype.delayLoad = function () {
  9748. };
  9749. BaseTexture.prototype.releaseInternalTexture = function () {
  9750. if (!this._texture) {
  9751. return;
  9752. }
  9753. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  9754. this._texture.references--;
  9755. if (this._texture.references == 0) {
  9756. var index = texturesCache.indexOf(this._texture);
  9757. texturesCache.splice(index, 1);
  9758. this._scene.getEngine()._releaseTexture(this._texture);
  9759. delete this._texture;
  9760. }
  9761. };
  9762. BaseTexture.prototype.clone = function () {
  9763. return null;
  9764. };
  9765. BaseTexture.prototype.dispose = function () {
  9766. var index = this._scene.textures.indexOf(this);
  9767. if (index >= 0) {
  9768. this._scene.textures.splice(index, 1);
  9769. }
  9770. if (this._texture === undefined) {
  9771. return;
  9772. }
  9773. this.releaseInternalTexture();
  9774. if (this.onDispose) {
  9775. this.onDispose();
  9776. }
  9777. };
  9778. return BaseTexture;
  9779. })();
  9780. BABYLON.BaseTexture = BaseTexture;
  9781. })(BABYLON || (BABYLON = {}));
  9782. var BABYLON;
  9783. (function (BABYLON) {
  9784. var RenderingGroup = (function () {
  9785. function RenderingGroup(index, scene) {
  9786. this.index = index;
  9787. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  9788. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  9789. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  9790. this._scene = scene;
  9791. }
  9792. RenderingGroup.prototype.render = function (customRenderFunction, beforeTransparents) {
  9793. if (customRenderFunction) {
  9794. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, beforeTransparents);
  9795. return true;
  9796. }
  9797. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  9798. return false;
  9799. }
  9800. var engine = this._scene.getEngine();
  9801. var subIndex;
  9802. var submesh;
  9803. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  9804. submesh = this._opaqueSubMeshes.data[subIndex];
  9805. this._activeVertices += submesh.verticesCount;
  9806. submesh.render();
  9807. }
  9808. engine.setAlphaTesting(true);
  9809. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  9810. submesh = this._alphaTestSubMeshes.data[subIndex];
  9811. this._activeVertices += submesh.verticesCount;
  9812. submesh.render();
  9813. }
  9814. engine.setAlphaTesting(false);
  9815. if (beforeTransparents) {
  9816. beforeTransparents();
  9817. }
  9818. if (this._transparentSubMeshes.length) {
  9819. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  9820. submesh = this._transparentSubMeshes.data[subIndex];
  9821. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  9822. }
  9823. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  9824. sortedArray.sort(function (a, b) {
  9825. if (a._distanceToCamera < b._distanceToCamera) {
  9826. return 1;
  9827. }
  9828. if (a._distanceToCamera > b._distanceToCamera) {
  9829. return -1;
  9830. }
  9831. return 0;
  9832. });
  9833. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9834. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  9835. submesh = sortedArray[subIndex];
  9836. this._activeVertices += submesh.verticesCount;
  9837. submesh.render();
  9838. }
  9839. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  9840. }
  9841. return true;
  9842. };
  9843. RenderingGroup.prototype.prepare = function () {
  9844. this._opaqueSubMeshes.reset();
  9845. this._transparentSubMeshes.reset();
  9846. this._alphaTestSubMeshes.reset();
  9847. };
  9848. RenderingGroup.prototype.dispatch = function (subMesh) {
  9849. var material = subMesh.getMaterial();
  9850. var mesh = subMesh.getMesh();
  9851. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  9852. if (material.alpha > 0 || mesh.visibility < 1.0) {
  9853. this._transparentSubMeshes.push(subMesh);
  9854. }
  9855. } else if (material.needAlphaTesting()) {
  9856. this._alphaTestSubMeshes.push(subMesh);
  9857. } else {
  9858. this._opaqueSubMeshes.push(subMesh);
  9859. }
  9860. };
  9861. return RenderingGroup;
  9862. })();
  9863. BABYLON.RenderingGroup = RenderingGroup;
  9864. })(BABYLON || (BABYLON = {}));
  9865. var BABYLON;
  9866. (function (BABYLON) {
  9867. var RenderingManager = (function () {
  9868. function RenderingManager(scene) {
  9869. this._renderingGroups = new Array();
  9870. this._scene = scene;
  9871. }
  9872. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  9873. if (this._scene._activeParticleSystems.length === 0) {
  9874. return;
  9875. }
  9876. var beforeParticlesDate = BABYLON.Tools.Now;
  9877. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  9878. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  9879. if (particleSystem.renderingGroupId !== index) {
  9880. continue;
  9881. }
  9882. this._clearDepthBuffer();
  9883. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  9884. this._scene._activeParticles += particleSystem.render();
  9885. }
  9886. }
  9887. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9888. };
  9889. RenderingManager.prototype._renderSprites = function (index) {
  9890. if (this._scene.spriteManagers.length === 0) {
  9891. return;
  9892. }
  9893. var beforeSpritessDate = BABYLON.Tools.Now;
  9894. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  9895. var spriteManager = this._scene.spriteManagers[id];
  9896. if (spriteManager.renderingGroupId === index) {
  9897. this._clearDepthBuffer();
  9898. spriteManager.render();
  9899. }
  9900. }
  9901. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  9902. };
  9903. RenderingManager.prototype._clearDepthBuffer = function () {
  9904. if (this._depthBufferAlreadyCleaned) {
  9905. return;
  9906. }
  9907. this._scene.getEngine().clear(0, false, true);
  9908. this._depthBufferAlreadyCleaned = true;
  9909. };
  9910. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  9911. var _this = this;
  9912. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  9913. this._depthBufferAlreadyCleaned = false;
  9914. var renderingGroup = this._renderingGroups[index];
  9915. if (renderingGroup) {
  9916. this._clearDepthBuffer();
  9917. if (!renderingGroup.render(customRenderFunction, function () {
  9918. if (renderSprites) {
  9919. _this._renderSprites(index);
  9920. }
  9921. })) {
  9922. this._renderingGroups.splice(index, 1);
  9923. } else if (renderSprites) {
  9924. this._renderSprites(index);
  9925. }
  9926. }
  9927. if (renderParticles) {
  9928. this._renderParticles(index, activeMeshes);
  9929. }
  9930. }
  9931. };
  9932. RenderingManager.prototype.reset = function () {
  9933. for (var index in this._renderingGroups) {
  9934. var renderingGroup = this._renderingGroups[index];
  9935. renderingGroup.prepare();
  9936. }
  9937. };
  9938. RenderingManager.prototype.dispatch = function (subMesh) {
  9939. var mesh = subMesh.getMesh();
  9940. var renderingGroupId = mesh.renderingGroupId || 0;
  9941. if (!this._renderingGroups[renderingGroupId]) {
  9942. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  9943. }
  9944. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  9945. };
  9946. RenderingManager.MAX_RENDERINGGROUPS = 4;
  9947. return RenderingManager;
  9948. })();
  9949. BABYLON.RenderingManager = RenderingManager;
  9950. })(BABYLON || (BABYLON = {}));
  9951. var __extends = this.__extends || function (d, b) {
  9952. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9953. function __() { this.constructor = d; }
  9954. __.prototype = b.prototype;
  9955. d.prototype = new __();
  9956. };
  9957. var BABYLON;
  9958. (function (BABYLON) {
  9959. var Texture = (function (_super) {
  9960. __extends(Texture, _super);
  9961. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  9962. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  9963. if (typeof onLoad === "undefined") { onLoad = null; }
  9964. if (typeof onError === "undefined") { onError = null; }
  9965. if (typeof buffer === "undefined") { buffer = null; }
  9966. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  9967. _super.call(this, scene);
  9968. this.uOffset = 0;
  9969. this.vOffset = 0;
  9970. this.uScale = 1.0;
  9971. this.vScale = 1.0;
  9972. this.uAng = 0;
  9973. this.vAng = 0;
  9974. this.wAng = 0;
  9975. this.name = url;
  9976. this.url = url;
  9977. this._noMipmap = noMipmap;
  9978. this._invertY = invertY;
  9979. this._samplingMode = samplingMode;
  9980. this._buffer = buffer;
  9981. this._deleteBuffer = deleteBuffer;
  9982. if (!url) {
  9983. return;
  9984. }
  9985. this._texture = this._getFromCache(url, noMipmap);
  9986. if (!this._texture) {
  9987. if (!scene.useDelayedTextureLoading) {
  9988. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  9989. if (deleteBuffer) {
  9990. delete this._buffer;
  9991. }
  9992. } else {
  9993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  9994. }
  9995. }
  9996. }
  9997. Texture.prototype.delayLoad = function () {
  9998. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9999. return;
  10000. }
  10001. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10002. this._texture = this._getFromCache(this.url, this._noMipmap);
  10003. if (!this._texture) {
  10004. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10005. if (this._deleteBuffer) {
  10006. delete this._buffer;
  10007. }
  10008. }
  10009. };
  10010. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10011. x -= this.uOffset + 0.5;
  10012. y -= this.vOffset + 0.5;
  10013. z -= 0.5;
  10014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10015. t.x *= this.uScale;
  10016. t.y *= this.vScale;
  10017. t.x += 0.5;
  10018. t.y += 0.5;
  10019. t.z += 0.5;
  10020. };
  10021. Texture.prototype.getTextureMatrix = function () {
  10022. 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) {
  10023. return this._cachedTextureMatrix;
  10024. }
  10025. this._cachedUOffset = this.uOffset;
  10026. this._cachedVOffset = this.vOffset;
  10027. this._cachedUScale = this.uScale;
  10028. this._cachedVScale = this.vScale;
  10029. this._cachedUAng = this.uAng;
  10030. this._cachedVAng = this.vAng;
  10031. this._cachedWAng = this.wAng;
  10032. if (!this._cachedTextureMatrix) {
  10033. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10034. this._rowGenerationMatrix = new BABYLON.Matrix();
  10035. this._t0 = BABYLON.Vector3.Zero();
  10036. this._t1 = BABYLON.Vector3.Zero();
  10037. this._t2 = BABYLON.Vector3.Zero();
  10038. }
  10039. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10040. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10041. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10042. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10043. this._t1.subtractInPlace(this._t0);
  10044. this._t2.subtractInPlace(this._t0);
  10045. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10046. this._cachedTextureMatrix.m[0] = this._t1.x;
  10047. this._cachedTextureMatrix.m[1] = this._t1.y;
  10048. this._cachedTextureMatrix.m[2] = this._t1.z;
  10049. this._cachedTextureMatrix.m[4] = this._t2.x;
  10050. this._cachedTextureMatrix.m[5] = this._t2.y;
  10051. this._cachedTextureMatrix.m[6] = this._t2.z;
  10052. this._cachedTextureMatrix.m[8] = this._t0.x;
  10053. this._cachedTextureMatrix.m[9] = this._t0.y;
  10054. this._cachedTextureMatrix.m[10] = this._t0.z;
  10055. return this._cachedTextureMatrix;
  10056. };
  10057. Texture.prototype.getReflectionTextureMatrix = function () {
  10058. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10059. return this._cachedTextureMatrix;
  10060. }
  10061. if (!this._cachedTextureMatrix) {
  10062. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10063. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10064. }
  10065. switch (this.coordinatesMode) {
  10066. case BABYLON.Texture.SPHERICAL_MODE:
  10067. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10068. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10069. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10070. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10071. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10072. break;
  10073. case BABYLON.Texture.PLANAR_MODE:
  10074. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10075. this._cachedTextureMatrix[0] = this.uScale;
  10076. this._cachedTextureMatrix[5] = this.vScale;
  10077. this._cachedTextureMatrix[12] = this.uOffset;
  10078. this._cachedTextureMatrix[13] = this.vOffset;
  10079. break;
  10080. case BABYLON.Texture.PROJECTION_MODE:
  10081. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10082. this._projectionModeMatrix.m[0] = 0.5;
  10083. this._projectionModeMatrix.m[5] = -0.5;
  10084. this._projectionModeMatrix.m[10] = 0.0;
  10085. this._projectionModeMatrix.m[12] = 0.5;
  10086. this._projectionModeMatrix.m[13] = 0.5;
  10087. this._projectionModeMatrix.m[14] = 1.0;
  10088. this._projectionModeMatrix.m[15] = 1.0;
  10089. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10090. break;
  10091. default:
  10092. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10093. break;
  10094. }
  10095. return this._cachedTextureMatrix;
  10096. };
  10097. Texture.prototype.clone = function () {
  10098. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10099. newTexture.hasAlpha = this.hasAlpha;
  10100. newTexture.level = this.level;
  10101. newTexture.wrapU = this.wrapU;
  10102. newTexture.wrapV = this.wrapV;
  10103. newTexture.coordinatesIndex = this.coordinatesIndex;
  10104. newTexture.coordinatesMode = this.coordinatesMode;
  10105. newTexture.uOffset = this.uOffset;
  10106. newTexture.vOffset = this.vOffset;
  10107. newTexture.uScale = this.uScale;
  10108. newTexture.vScale = this.vScale;
  10109. newTexture.uAng = this.uAng;
  10110. newTexture.vAng = this.vAng;
  10111. newTexture.wAng = this.wAng;
  10112. return newTexture;
  10113. };
  10114. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10115. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10116. if (typeof onLoad === "undefined") { onLoad = null; }
  10117. if (typeof onError === "undefined") { onError = null; }
  10118. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10119. };
  10120. Texture.NEAREST_SAMPLINGMODE = 1;
  10121. Texture.BILINEAR_SAMPLINGMODE = 2;
  10122. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10123. Texture.EXPLICIT_MODE = 0;
  10124. Texture.SPHERICAL_MODE = 1;
  10125. Texture.PLANAR_MODE = 2;
  10126. Texture.CUBIC_MODE = 3;
  10127. Texture.PROJECTION_MODE = 4;
  10128. Texture.SKYBOX_MODE = 5;
  10129. Texture.CLAMP_ADDRESSMODE = 0;
  10130. Texture.WRAP_ADDRESSMODE = 1;
  10131. Texture.MIRROR_ADDRESSMODE = 2;
  10132. return Texture;
  10133. })(BABYLON.BaseTexture);
  10134. BABYLON.Texture = Texture;
  10135. })(BABYLON || (BABYLON = {}));
  10136. var __extends = this.__extends || function (d, b) {
  10137. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10138. function __() { this.constructor = d; }
  10139. __.prototype = b.prototype;
  10140. d.prototype = new __();
  10141. };
  10142. var BABYLON;
  10143. (function (BABYLON) {
  10144. var CubeTexture = (function (_super) {
  10145. __extends(CubeTexture, _super);
  10146. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10147. _super.call(this, scene);
  10148. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10149. this.name = rootUrl;
  10150. this.url = rootUrl;
  10151. this._noMipmap = noMipmap;
  10152. this.hasAlpha = false;
  10153. this._texture = this._getFromCache(rootUrl, noMipmap);
  10154. if (!extensions) {
  10155. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10156. }
  10157. this._extensions = extensions;
  10158. if (!this._texture) {
  10159. if (!scene.useDelayedTextureLoading) {
  10160. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10161. } else {
  10162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10163. }
  10164. }
  10165. this.isCube = true;
  10166. this._textureMatrix = BABYLON.Matrix.Identity();
  10167. }
  10168. CubeTexture.prototype.clone = function () {
  10169. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10170. newTexture.level = this.level;
  10171. newTexture.wrapU = this.wrapU;
  10172. newTexture.wrapV = this.wrapV;
  10173. newTexture.coordinatesIndex = this.coordinatesIndex;
  10174. newTexture.coordinatesMode = this.coordinatesMode;
  10175. return newTexture;
  10176. };
  10177. CubeTexture.prototype.delayLoad = function () {
  10178. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10179. return;
  10180. }
  10181. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10182. this._texture = this._getFromCache(this.url, this._noMipmap);
  10183. if (!this._texture) {
  10184. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10185. }
  10186. };
  10187. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10188. return this._textureMatrix;
  10189. };
  10190. return CubeTexture;
  10191. })(BABYLON.BaseTexture);
  10192. BABYLON.CubeTexture = CubeTexture;
  10193. })(BABYLON || (BABYLON = {}));
  10194. var __extends = this.__extends || function (d, b) {
  10195. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10196. function __() { this.constructor = d; }
  10197. __.prototype = b.prototype;
  10198. d.prototype = new __();
  10199. };
  10200. var BABYLON;
  10201. (function (BABYLON) {
  10202. var RenderTargetTexture = (function (_super) {
  10203. __extends(RenderTargetTexture, _super);
  10204. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10205. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10206. _super.call(this, null, scene, !generateMipMaps);
  10207. this.renderList = new Array();
  10208. this.renderParticles = true;
  10209. this.renderSprites = false;
  10210. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10211. this._currentRefreshId = -1;
  10212. this._refreshRate = 1;
  10213. this.name = name;
  10214. this.isRenderTarget = true;
  10215. this._size = size;
  10216. this._generateMipMaps = generateMipMaps;
  10217. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10218. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10219. this._renderingManager = new BABYLON.RenderingManager(scene);
  10220. }
  10221. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10222. this._currentRefreshId = -1;
  10223. };
  10224. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10225. get: function () {
  10226. return this._refreshRate;
  10227. },
  10228. set: function (value) {
  10229. this._refreshRate = value;
  10230. this.resetRefreshCounter();
  10231. },
  10232. enumerable: true,
  10233. configurable: true
  10234. });
  10235. RenderTargetTexture.prototype._shouldRender = function () {
  10236. if (this._currentRefreshId === -1) {
  10237. this._currentRefreshId = 1;
  10238. return true;
  10239. }
  10240. if (this.refreshRate == this._currentRefreshId) {
  10241. this._currentRefreshId = 1;
  10242. return true;
  10243. }
  10244. this._currentRefreshId++;
  10245. return false;
  10246. };
  10247. RenderTargetTexture.prototype.isReady = function () {
  10248. if (!this.getScene().renderTargetsEnabled) {
  10249. return false;
  10250. }
  10251. return _super.prototype.isReady.call(this);
  10252. };
  10253. RenderTargetTexture.prototype.getRenderSize = function () {
  10254. return this._size;
  10255. };
  10256. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10257. get: function () {
  10258. return true;
  10259. },
  10260. enumerable: true,
  10261. configurable: true
  10262. });
  10263. RenderTargetTexture.prototype.scale = function (ratio) {
  10264. var newSize = this._size * ratio;
  10265. this.resize(newSize, this._generateMipMaps);
  10266. };
  10267. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10268. this.releaseInternalTexture();
  10269. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10270. };
  10271. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10272. var scene = this.getScene();
  10273. var engine = scene.getEngine();
  10274. if (this._waitingRenderList) {
  10275. this.renderList = [];
  10276. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10277. var id = this._waitingRenderList[index];
  10278. this.renderList.push(scene.getMeshByID(id));
  10279. }
  10280. delete this._waitingRenderList;
  10281. }
  10282. if (!this.renderList) {
  10283. return;
  10284. }
  10285. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10286. engine.bindFramebuffer(this._texture);
  10287. }
  10288. engine.clear(scene.clearColor, true, true);
  10289. this._renderingManager.reset();
  10290. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10291. var mesh = this.renderList[meshIndex];
  10292. if (mesh) {
  10293. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10294. this.resetRefreshCounter();
  10295. continue;
  10296. }
  10297. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10298. mesh._activate(scene.getRenderId());
  10299. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10300. var subMesh = mesh.subMeshes[subIndex];
  10301. scene._activeVertices += subMesh.verticesCount;
  10302. this._renderingManager.dispatch(subMesh);
  10303. }
  10304. }
  10305. }
  10306. }
  10307. if (!this._doNotChangeAspectRatio) {
  10308. scene.updateTransformMatrix(true);
  10309. }
  10310. if (this.onBeforeRender) {
  10311. this.onBeforeRender();
  10312. }
  10313. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10314. if (useCameraPostProcess) {
  10315. scene.postProcessManager._finalizeFrame(false, this._texture);
  10316. }
  10317. if (this.onAfterRender) {
  10318. this.onAfterRender();
  10319. }
  10320. engine.unBindFramebuffer(this._texture);
  10321. if (!this._doNotChangeAspectRatio) {
  10322. scene.updateTransformMatrix(true);
  10323. }
  10324. };
  10325. RenderTargetTexture.prototype.clone = function () {
  10326. var textureSize = this.getSize();
  10327. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10328. newTexture.hasAlpha = this.hasAlpha;
  10329. newTexture.level = this.level;
  10330. newTexture.coordinatesMode = this.coordinatesMode;
  10331. newTexture.renderList = this.renderList.slice(0);
  10332. return newTexture;
  10333. };
  10334. return RenderTargetTexture;
  10335. })(BABYLON.Texture);
  10336. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10337. })(BABYLON || (BABYLON = {}));
  10338. var __extends = this.__extends || function (d, b) {
  10339. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10340. function __() { this.constructor = d; }
  10341. __.prototype = b.prototype;
  10342. d.prototype = new __();
  10343. };
  10344. var BABYLON;
  10345. (function (BABYLON) {
  10346. var ProceduralTexture = (function (_super) {
  10347. __extends(ProceduralTexture, _super);
  10348. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10349. _super.call(this, null, scene, !generateMipMaps);
  10350. this._currentRefreshId = -1;
  10351. this._refreshRate = 1;
  10352. this._vertexDeclaration = [2];
  10353. this._vertexStrideSize = 2 * 4;
  10354. this._uniforms = new Array();
  10355. this._samplers = new Array();
  10356. this._textures = new Array();
  10357. this._floats = new Array();
  10358. this._floatsArrays = {};
  10359. this._colors3 = new Array();
  10360. this._colors4 = new Array();
  10361. this._vectors2 = new Array();
  10362. this._vectors3 = new Array();
  10363. this._matrices = new Array();
  10364. scene._proceduralTextures.push(this);
  10365. this.name = name;
  10366. this.isRenderTarget = true;
  10367. this._size = size;
  10368. this._generateMipMaps = generateMipMaps;
  10369. this._fragment = fragment;
  10370. this._fallbackTexture = fallbackTexture;
  10371. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10372. var vertices = [];
  10373. vertices.push(1, 1);
  10374. vertices.push(-1, 1);
  10375. vertices.push(-1, -1);
  10376. vertices.push(1, -1);
  10377. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10378. var indices = [];
  10379. indices.push(0);
  10380. indices.push(1);
  10381. indices.push(2);
  10382. indices.push(0);
  10383. indices.push(2);
  10384. indices.push(3);
  10385. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10386. }
  10387. ProceduralTexture.prototype.reset = function () {
  10388. var engine = this.getScene().getEngine();
  10389. engine._releaseEffect(this._effect);
  10390. };
  10391. ProceduralTexture.prototype.isReady = function () {
  10392. var _this = this;
  10393. var engine = this.getScene().getEngine();
  10394. this._effect = engine.createEffect({ vertex: "procedural", fragment: this._fragment }, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10395. _this.releaseInternalTexture();
  10396. _this._texture = _this._fallbackTexture._texture;
  10397. _this._texture.references++;
  10398. });
  10399. return this._effect.isReady();
  10400. };
  10401. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10402. this._currentRefreshId = -1;
  10403. };
  10404. ProceduralTexture.prototype.setFragment = function (fragment) {
  10405. this._fragment = fragment;
  10406. };
  10407. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10408. get: function () {
  10409. return this._refreshRate;
  10410. },
  10411. set: function (value) {
  10412. this._refreshRate = value;
  10413. this.resetRefreshCounter();
  10414. },
  10415. enumerable: true,
  10416. configurable: true
  10417. });
  10418. ProceduralTexture.prototype._shouldRender = function () {
  10419. if (!this.isReady() || !this._texture) {
  10420. return false;
  10421. }
  10422. if (this._currentRefreshId === -1) {
  10423. this._currentRefreshId = 1;
  10424. return true;
  10425. }
  10426. if (this.refreshRate == this._currentRefreshId) {
  10427. this._currentRefreshId = 1;
  10428. return true;
  10429. }
  10430. this._currentRefreshId++;
  10431. return false;
  10432. };
  10433. ProceduralTexture.prototype.getRenderSize = function () {
  10434. return this._size;
  10435. };
  10436. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  10437. this.releaseInternalTexture();
  10438. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10439. };
  10440. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  10441. if (this._uniforms.indexOf(uniformName) === -1) {
  10442. this._uniforms.push(uniformName);
  10443. }
  10444. };
  10445. ProceduralTexture.prototype.setTexture = function (name, texture) {
  10446. if (this._samplers.indexOf(name) === -1) {
  10447. this._samplers.push(name);
  10448. }
  10449. this._textures[name] = texture;
  10450. return this;
  10451. };
  10452. ProceduralTexture.prototype.setFloat = function (name, value) {
  10453. this._checkUniform(name);
  10454. this._floats[name] = value;
  10455. return this;
  10456. };
  10457. ProceduralTexture.prototype.setFloats = function (name, value) {
  10458. this._checkUniform(name);
  10459. this._floatsArrays[name] = value;
  10460. return this;
  10461. };
  10462. ProceduralTexture.prototype.setColor3 = function (name, value) {
  10463. this._checkUniform(name);
  10464. this._colors3[name] = value;
  10465. return this;
  10466. };
  10467. ProceduralTexture.prototype.setColor4 = function (name, value) {
  10468. this._checkUniform(name);
  10469. this._colors4[name] = value;
  10470. return this;
  10471. };
  10472. ProceduralTexture.prototype.setVector2 = function (name, value) {
  10473. this._checkUniform(name);
  10474. this._vectors2[name] = value;
  10475. return this;
  10476. };
  10477. ProceduralTexture.prototype.setVector3 = function (name, value) {
  10478. this._checkUniform(name);
  10479. this._vectors3[name] = value;
  10480. return this;
  10481. };
  10482. ProceduralTexture.prototype.setMatrix = function (name, value) {
  10483. this._checkUniform(name);
  10484. this._matrices[name] = value;
  10485. return this;
  10486. };
  10487. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10488. var scene = this.getScene();
  10489. var engine = scene.getEngine();
  10490. engine.bindFramebuffer(this._texture);
  10491. engine.clear(scene.clearColor, true, true);
  10492. engine.enableEffect(this._effect);
  10493. engine.setState(false);
  10494. for (var name in this._textures) {
  10495. this._effect.setTexture(name, this._textures[name]);
  10496. }
  10497. for (name in this._floats) {
  10498. this._effect.setFloat(name, this._floats[name]);
  10499. }
  10500. for (name in this._floatsArrays) {
  10501. this._effect.setArray(name, this._floatsArrays[name]);
  10502. }
  10503. for (name in this._colors3) {
  10504. this._effect.setColor3(name, this._colors3[name]);
  10505. }
  10506. for (name in this._colors4) {
  10507. var color = this._colors4[name];
  10508. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  10509. }
  10510. for (name in this._vectors2) {
  10511. this._effect.setVector2(name, this._vectors2[name]);
  10512. }
  10513. for (name in this._vectors3) {
  10514. this._effect.setVector3(name, this._vectors3[name]);
  10515. }
  10516. for (name in this._matrices) {
  10517. this._effect.setMatrix(name, this._matrices[name]);
  10518. }
  10519. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  10520. engine.draw(true, 0, 6);
  10521. engine.unBindFramebuffer(this._texture);
  10522. };
  10523. ProceduralTexture.prototype.clone = function () {
  10524. var textureSize = this.getSize();
  10525. var newTexture = new BABYLON.ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  10526. newTexture.hasAlpha = this.hasAlpha;
  10527. newTexture.level = this.level;
  10528. newTexture.coordinatesMode = this.coordinatesMode;
  10529. return newTexture;
  10530. };
  10531. ProceduralTexture.prototype.dispose = function () {
  10532. var index = this.getScene()._proceduralTextures.indexOf(this);
  10533. if (index >= 0) {
  10534. this.getScene()._proceduralTextures.splice(index, 1);
  10535. }
  10536. _super.prototype.dispose.call(this);
  10537. };
  10538. return ProceduralTexture;
  10539. })(BABYLON.Texture);
  10540. BABYLON.ProceduralTexture = ProceduralTexture;
  10541. })(BABYLON || (BABYLON = {}));
  10542. var __extends = this.__extends || function (d, b) {
  10543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10544. function __() { this.constructor = d; }
  10545. __.prototype = b.prototype;
  10546. d.prototype = new __();
  10547. };
  10548. var BABYLON;
  10549. (function (BABYLON) {
  10550. var WoodProceduralTexture = (function (_super) {
  10551. __extends(WoodProceduralTexture, _super);
  10552. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10553. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  10554. this._ampScale = 100.0;
  10555. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  10556. this.updateShaderUniforms();
  10557. this.refreshRate = 0;
  10558. }
  10559. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  10560. this.setFloat("ampScale", this._ampScale);
  10561. this.setColor3("woodColor", this._woodColor);
  10562. };
  10563. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  10564. get: function () {
  10565. return this._ampScale;
  10566. },
  10567. set: function (value) {
  10568. this._ampScale = value;
  10569. this.updateShaderUniforms();
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  10575. get: function () {
  10576. return this._woodColor;
  10577. },
  10578. set: function (value) {
  10579. this._woodColor = value;
  10580. this.updateShaderUniforms();
  10581. },
  10582. enumerable: true,
  10583. configurable: true
  10584. });
  10585. return WoodProceduralTexture;
  10586. })(BABYLON.ProceduralTexture);
  10587. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  10588. var FireProceduralTexture = (function (_super) {
  10589. __extends(FireProceduralTexture, _super);
  10590. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10591. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  10592. this._time = 0.0;
  10593. this._speed = new BABYLON.Vector2(0.5, 0.3);
  10594. this._shift = 1.6;
  10595. this._alpha = 0.0;
  10596. this._autoGenerateTime = true;
  10597. this._alphaThreshold = 0.5;
  10598. this._fireColors = FireProceduralTexture.RedFireColors;
  10599. this.updateShaderUniforms();
  10600. this.refreshRate = 1;
  10601. }
  10602. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  10603. this.setFloat("iGlobalTime", this._time);
  10604. this.setVector2("speed", this._speed);
  10605. this.setFloat("shift", this._shift);
  10606. this.setFloat("alpha", this._alpha);
  10607. this.setColor3("c1", this._fireColors[0]);
  10608. this.setColor3("c2", this._fireColors[1]);
  10609. this.setColor3("c3", this._fireColors[2]);
  10610. this.setColor3("c4", this._fireColors[3]);
  10611. this.setColor3("c5", this._fireColors[4]);
  10612. this.setColor3("c6", this._fireColors[5]);
  10613. this.setFloat("alphaThreshold", this._alphaThreshold);
  10614. };
  10615. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  10616. if (this._autoGenerateTime) {
  10617. this._time += this.getScene().getAnimationRatio() * 0.03;
  10618. this.updateShaderUniforms();
  10619. }
  10620. _super.prototype.render.call(this, useCameraPostProcess);
  10621. };
  10622. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  10623. get: function () {
  10624. return [
  10625. new BABYLON.Color3(0.5, 0.0, 1.0),
  10626. new BABYLON.Color3(0.9, 0.0, 1.0),
  10627. new BABYLON.Color3(0.2, 0.0, 1.0),
  10628. new BABYLON.Color3(1.0, 0.9, 1.0),
  10629. new BABYLON.Color3(0.1, 0.1, 1.0),
  10630. new BABYLON.Color3(0.9, 0.9, 1.0)
  10631. ];
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  10637. get: function () {
  10638. return [
  10639. new BABYLON.Color3(0.5, 1.0, 0.0),
  10640. new BABYLON.Color3(0.5, 1.0, 0.0),
  10641. new BABYLON.Color3(0.3, 0.4, 0.0),
  10642. new BABYLON.Color3(0.5, 1.0, 0.0),
  10643. new BABYLON.Color3(0.2, 0.0, 0.0),
  10644. new BABYLON.Color3(0.5, 1.0, 0.0)
  10645. ];
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  10651. get: function () {
  10652. return [
  10653. new BABYLON.Color3(0.5, 0.0, 0.1),
  10654. new BABYLON.Color3(0.9, 0.0, 0.0),
  10655. new BABYLON.Color3(0.2, 0.0, 0.0),
  10656. new BABYLON.Color3(1.0, 0.9, 0.0),
  10657. new BABYLON.Color3(0.1, 0.1, 0.1),
  10658. new BABYLON.Color3(0.9, 0.9, 0.9)
  10659. ];
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  10665. get: function () {
  10666. return [
  10667. new BABYLON.Color3(0.1, 0.0, 0.5),
  10668. new BABYLON.Color3(0.0, 0.0, 0.5),
  10669. new BABYLON.Color3(0.1, 0.0, 0.2),
  10670. new BABYLON.Color3(0.0, 0.0, 1.0),
  10671. new BABYLON.Color3(0.1, 0.2, 0.3),
  10672. new BABYLON.Color3(0.0, 0.2, 0.9)
  10673. ];
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  10679. get: function () {
  10680. return this._fireColors;
  10681. },
  10682. set: function (value) {
  10683. this._fireColors = value;
  10684. this.updateShaderUniforms();
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  10690. get: function () {
  10691. return this._time;
  10692. },
  10693. set: function (value) {
  10694. this._time = value;
  10695. this.updateShaderUniforms();
  10696. },
  10697. enumerable: true,
  10698. configurable: true
  10699. });
  10700. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  10701. get: function () {
  10702. return this._speed;
  10703. },
  10704. set: function (value) {
  10705. this._speed = value;
  10706. this.updateShaderUniforms();
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  10712. get: function () {
  10713. return this._shift;
  10714. },
  10715. set: function (value) {
  10716. this._shift = value;
  10717. this.updateShaderUniforms();
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(FireProceduralTexture.prototype, "alpha", {
  10723. get: function () {
  10724. return this._alpha;
  10725. },
  10726. set: function (value) {
  10727. this._alpha = value;
  10728. this.updateShaderUniforms();
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. return FireProceduralTexture;
  10734. })(BABYLON.ProceduralTexture);
  10735. BABYLON.FireProceduralTexture = FireProceduralTexture;
  10736. var CloudProceduralTexture = (function (_super) {
  10737. __extends(CloudProceduralTexture, _super);
  10738. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10739. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  10740. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  10741. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  10742. this.updateShaderUniforms();
  10743. this.refreshRate = 0;
  10744. }
  10745. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  10746. this.setColor3("skyColor", this._skyColor);
  10747. this.setColor3("cloudColor", this._cloudColor);
  10748. };
  10749. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  10750. get: function () {
  10751. return this._skyColor;
  10752. },
  10753. set: function (value) {
  10754. this._skyColor = value;
  10755. this.updateShaderUniforms();
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  10761. get: function () {
  10762. return this._cloudColor;
  10763. },
  10764. set: function (value) {
  10765. this._cloudColor = value;
  10766. this.updateShaderUniforms();
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. return CloudProceduralTexture;
  10772. })(BABYLON.ProceduralTexture);
  10773. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  10774. var GrassProceduralTexture = (function (_super) {
  10775. __extends(GrassProceduralTexture, _super);
  10776. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10777. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  10778. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  10779. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  10780. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  10781. this._dirtColor = new BABYLON.Color3(0.6, 0.46, 0.13);
  10782. this._groundColor = new BABYLON.Color3(1, 1, 1);
  10783. this._grassColors = [
  10784. new BABYLON.Color3(0.29, 0.38, 0.02),
  10785. new BABYLON.Color3(0.36, 0.49, 0.09),
  10786. new BABYLON.Color3(0.51, 0.6, 0.28)
  10787. ];
  10788. this.updateShaderUniforms();
  10789. this.refreshRate = 0;
  10790. }
  10791. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  10792. this.setColor3("herb1", this._grassColors[0]);
  10793. this.setColor3("herb2", this._grassColors[1]);
  10794. this.setColor3("herb3", this._grassColors[2]);
  10795. this.setColor3("dirt", this._dirtColor);
  10796. this.setColor3("ground", this._groundColor);
  10797. };
  10798. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  10799. get: function () {
  10800. return this._grassColors;
  10801. },
  10802. set: function (value) {
  10803. this._grassColors = value;
  10804. this.updateShaderUniforms();
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(GrassProceduralTexture.prototype, "dirtColor", {
  10810. get: function () {
  10811. return this._dirtColor;
  10812. },
  10813. set: function (value) {
  10814. this._dirtColor = value;
  10815. this.updateShaderUniforms();
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  10821. get: function () {
  10822. return this._groundColor;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(GrassProceduralTexture.prototype, "ground", {
  10828. set: function (value) {
  10829. this.groundColor = value;
  10830. this.updateShaderUniforms();
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. return GrassProceduralTexture;
  10836. })(BABYLON.ProceduralTexture);
  10837. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  10838. var RoadProceduralTexture = (function (_super) {
  10839. __extends(RoadProceduralTexture, _super);
  10840. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10841. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  10842. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  10843. this.updateShaderUniforms();
  10844. this.refreshRate = 0;
  10845. }
  10846. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  10847. this.setColor3("roadColor", this._roadColor);
  10848. };
  10849. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  10850. get: function () {
  10851. return this._roadColor;
  10852. },
  10853. set: function (value) {
  10854. this._roadColor = value;
  10855. this.updateShaderUniforms();
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. return RoadProceduralTexture;
  10861. })(BABYLON.ProceduralTexture);
  10862. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  10863. var BrickProceduralTexture = (function (_super) {
  10864. __extends(BrickProceduralTexture, _super);
  10865. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10866. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  10867. this._numberOfBricksHeight = 15;
  10868. this._numberOfBricksWidth = 5;
  10869. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  10870. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  10871. this.updateShaderUniforms();
  10872. this.refreshRate = 0;
  10873. }
  10874. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  10875. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  10876. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  10877. this.setColor3("brick", this._brickColor);
  10878. this.setColor3("joint", this._jointColor);
  10879. };
  10880. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  10881. get: function () {
  10882. return this._numberOfBricksHeight;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  10888. set: function (value) {
  10889. this._numberOfBricksHeight = value;
  10890. this.updateShaderUniforms();
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  10896. get: function () {
  10897. return this._numberOfBricksWidth;
  10898. },
  10899. set: function (value) {
  10900. this._numberOfBricksHeight = value;
  10901. this.updateShaderUniforms();
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  10907. get: function () {
  10908. return this._jointColor;
  10909. },
  10910. set: function (value) {
  10911. this._jointColor = value;
  10912. this.updateShaderUniforms();
  10913. },
  10914. enumerable: true,
  10915. configurable: true
  10916. });
  10917. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  10918. get: function () {
  10919. return this._brickColor;
  10920. },
  10921. set: function (value) {
  10922. this._brickColor = value;
  10923. this.updateShaderUniforms();
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. return BrickProceduralTexture;
  10929. })(BABYLON.ProceduralTexture);
  10930. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  10931. var MarbleProceduralTexture = (function (_super) {
  10932. __extends(MarbleProceduralTexture, _super);
  10933. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  10934. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  10935. this._numberOfTilesHeight = 3;
  10936. this._numberOfTilesWidth = 3;
  10937. this._amplitude = 9.0;
  10938. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  10939. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  10940. this.updateShaderUniforms();
  10941. this.refreshRate = 0;
  10942. }
  10943. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  10944. this.setFloat("numberOfBricksHeight", this._numberOfTilesHeight);
  10945. this.setFloat("numberOfBricksWidth", this._numberOfTilesWidth);
  10946. this.setFloat("amplitude", this._amplitude);
  10947. this.setColor3("brick", this._marbleColor);
  10948. this.setColor3("joint", this._jointColor);
  10949. };
  10950. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  10951. get: function () {
  10952. return this._numberOfTilesHeight;
  10953. },
  10954. set: function (value) {
  10955. this._numberOfTilesHeight = value;
  10956. this.updateShaderUniforms();
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  10962. get: function () {
  10963. return this._numberOfTilesWidth;
  10964. },
  10965. set: function (value) {
  10966. this._numberOfTilesWidth = value;
  10967. this.updateShaderUniforms();
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  10973. get: function () {
  10974. return this._jointColor;
  10975. },
  10976. set: function (value) {
  10977. this._jointColor = value;
  10978. this.updateShaderUniforms();
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  10984. get: function () {
  10985. return this._marbleColor;
  10986. },
  10987. set: function (value) {
  10988. this._marbleColor = value;
  10989. this.updateShaderUniforms();
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. return MarbleProceduralTexture;
  10995. })(BABYLON.ProceduralTexture);
  10996. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  10997. })(BABYLON || (BABYLON = {}));
  10998. var __extends = this.__extends || function (d, b) {
  10999. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11000. function __() { this.constructor = d; }
  11001. __.prototype = b.prototype;
  11002. d.prototype = new __();
  11003. };
  11004. var BABYLON;
  11005. (function (BABYLON) {
  11006. var CustomProceduralTexture = (function (_super) {
  11007. __extends(CustomProceduralTexture, _super);
  11008. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11009. _super.call(this, name, size, "empty", scene, fallbackTexture, generateMipMaps);
  11010. this._animate = true;
  11011. this._time = 0;
  11012. this._shaderLoaded = false;
  11013. this._updateTexture = false;
  11014. this._texturePath = texturePath;
  11015. this.loadJson(texturePath);
  11016. this.refreshRate = 1;
  11017. }
  11018. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11019. function noConfigFile() {
  11020. BABYLON.Tools.Log("No config file found in " + jsonUrl);
  11021. }
  11022. var that = this;
  11023. var configFileUrl = jsonUrl + "/config.json";
  11024. var xhr = new XMLHttpRequest();
  11025. xhr.open("GET", configFileUrl, true);
  11026. xhr.addEventListener("load", function () {
  11027. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11028. try {
  11029. that._config = JSON.parse(xhr.response);
  11030. that._updateTexture = true;
  11031. that._shaderLoaded = true;
  11032. } catch (ex) {
  11033. noConfigFile();
  11034. }
  11035. } else {
  11036. noConfigFile();
  11037. }
  11038. }, false);
  11039. xhr.addEventListener("error", function (event) {
  11040. noConfigFile();
  11041. }, false);
  11042. try {
  11043. xhr.send();
  11044. } catch (ex) {
  11045. BABYLON.Tools.Error("Error on XHR send request.");
  11046. }
  11047. };
  11048. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11049. if (!this._shaderLoaded)
  11050. return;
  11051. if (this._updateTexture) {
  11052. this.reset();
  11053. this.setFragment(this._texturePath + "/custom");
  11054. this.updateTextures();
  11055. this.updateShaderUniforms();
  11056. this._shaderLoaded = true;
  11057. this._animate = this._config.animate;
  11058. this.refreshRate = this._config.refreshrate;
  11059. this.isReady();
  11060. this._updateTexture = false;
  11061. return;
  11062. }
  11063. if (this._animate) {
  11064. this._time += this.getScene().getAnimationRatio() * 0.03;
  11065. this.updateShaderUniforms();
  11066. }
  11067. _super.prototype.render.call(this, useCameraPostProcess);
  11068. };
  11069. CustomProceduralTexture.prototype.updateTextures = function () {
  11070. for (var i = 0; i < this._config.texture2Ds.length; i++) {
  11071. this.setTexture(this._config.texture2Ds[i].textureName, new BABYLON.Texture(this._texturePath + "/" + this._config.texture2Ds[i].textureRelativeUrl, this.getScene(), false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, null, null, null, true));
  11072. }
  11073. };
  11074. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11075. for (var j = 0; j < this._config.uniforms.length; j++) {
  11076. var uniform = this._config.uniforms[j];
  11077. switch (uniform.type) {
  11078. case "float":
  11079. this.setFloat(uniform.name, uniform.value);
  11080. break;
  11081. case "color3":
  11082. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11083. break;
  11084. case "color4":
  11085. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11086. break;
  11087. case "vector2":
  11088. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11089. break;
  11090. case "vector3":
  11091. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11092. break;
  11093. }
  11094. }
  11095. this.setFloat("time", this._time);
  11096. };
  11097. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11098. get: function () {
  11099. return this._animate;
  11100. },
  11101. set: function (value) {
  11102. this._animate = value;
  11103. this.updateShaderUniforms();
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. return CustomProceduralTexture;
  11109. })(BABYLON.ProceduralTexture);
  11110. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11111. })(BABYLON || (BABYLON = {}));
  11112. var __extends = this.__extends || function (d, b) {
  11113. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11114. function __() { this.constructor = d; }
  11115. __.prototype = b.prototype;
  11116. d.prototype = new __();
  11117. };
  11118. var BABYLON;
  11119. (function (BABYLON) {
  11120. var MirrorTexture = (function (_super) {
  11121. __extends(MirrorTexture, _super);
  11122. function MirrorTexture(name, size, scene, generateMipMaps) {
  11123. var _this = this;
  11124. _super.call(this, name, size, scene, generateMipMaps, true);
  11125. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11126. this._transformMatrix = BABYLON.Matrix.Zero();
  11127. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11128. this.onBeforeRender = function () {
  11129. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11130. _this._savedViewMatrix = scene.getViewMatrix();
  11131. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11132. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11133. scene.clipPlane = _this.mirrorPlane;
  11134. scene.getEngine().cullBackFaces = false;
  11135. };
  11136. this.onAfterRender = function () {
  11137. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11138. scene.getEngine().cullBackFaces = true;
  11139. delete scene.clipPlane;
  11140. };
  11141. }
  11142. MirrorTexture.prototype.clone = function () {
  11143. var textureSize = this.getSize();
  11144. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11145. newTexture.hasAlpha = this.hasAlpha;
  11146. newTexture.level = this.level;
  11147. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11148. newTexture.renderList = this.renderList.slice(0);
  11149. return newTexture;
  11150. };
  11151. return MirrorTexture;
  11152. })(BABYLON.RenderTargetTexture);
  11153. BABYLON.MirrorTexture = MirrorTexture;
  11154. })(BABYLON || (BABYLON = {}));
  11155. var __extends = this.__extends || function (d, b) {
  11156. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11157. function __() { this.constructor = d; }
  11158. __.prototype = b.prototype;
  11159. d.prototype = new __();
  11160. };
  11161. var BABYLON;
  11162. (function (BABYLON) {
  11163. var DynamicTexture = (function (_super) {
  11164. __extends(DynamicTexture, _super);
  11165. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11166. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11167. _super.call(this, null, scene, !generateMipMaps);
  11168. this.name = name;
  11169. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11170. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11171. this._generateMipMaps = generateMipMaps;
  11172. if (options.getContext) {
  11173. this._canvas = options;
  11174. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11175. } else {
  11176. this._canvas = document.createElement("canvas");
  11177. if (options.width) {
  11178. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11179. } else {
  11180. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11181. }
  11182. }
  11183. var textureSize = this.getSize();
  11184. this._canvas.width = textureSize.width;
  11185. this._canvas.height = textureSize.height;
  11186. this._context = this._canvas.getContext("2d");
  11187. }
  11188. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11189. get: function () {
  11190. return true;
  11191. },
  11192. enumerable: true,
  11193. configurable: true
  11194. });
  11195. DynamicTexture.prototype.scale = function (ratio) {
  11196. var textureSize = this.getSize();
  11197. textureSize.width *= ratio;
  11198. textureSize.height *= ratio;
  11199. this._canvas.width = textureSize.width;
  11200. this._canvas.height = textureSize.height;
  11201. this.releaseInternalTexture();
  11202. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11203. };
  11204. DynamicTexture.prototype.getContext = function () {
  11205. return this._context;
  11206. };
  11207. DynamicTexture.prototype.update = function (invertY) {
  11208. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11209. };
  11210. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11211. var size = this.getSize();
  11212. if (clearColor) {
  11213. this._context.fillStyle = clearColor;
  11214. this._context.fillRect(0, 0, size.width, size.height);
  11215. }
  11216. this._context.font = font;
  11217. if (x === null) {
  11218. var textSize = this._context.measureText(text);
  11219. x = (size.width - textSize.width) / 2;
  11220. }
  11221. this._context.fillStyle = color;
  11222. this._context.fillText(text, x, y);
  11223. this.update(invertY);
  11224. };
  11225. DynamicTexture.prototype.clone = function () {
  11226. var textureSize = this.getSize();
  11227. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11228. newTexture.hasAlpha = this.hasAlpha;
  11229. newTexture.level = this.level;
  11230. newTexture.wrapU = this.wrapU;
  11231. newTexture.wrapV = this.wrapV;
  11232. return newTexture;
  11233. };
  11234. return DynamicTexture;
  11235. })(BABYLON.Texture);
  11236. BABYLON.DynamicTexture = DynamicTexture;
  11237. })(BABYLON || (BABYLON = {}));
  11238. var __extends = this.__extends || function (d, b) {
  11239. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11240. function __() { this.constructor = d; }
  11241. __.prototype = b.prototype;
  11242. d.prototype = new __();
  11243. };
  11244. var BABYLON;
  11245. (function (BABYLON) {
  11246. var VideoTexture = (function (_super) {
  11247. __extends(VideoTexture, _super);
  11248. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11249. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11250. var _this = this;
  11251. _super.call(this, null, scene, !generateMipMaps, invertY);
  11252. this._autoLaunch = true;
  11253. this.name = name;
  11254. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11255. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11256. var requiredWidth = size.width || size;
  11257. var requiredHeight = size.height || size;
  11258. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11259. var textureSize = this.getSize();
  11260. this.video = document.createElement("video");
  11261. this.video.width = textureSize.width;
  11262. this.video.height = textureSize.height;
  11263. this.video.autoplay = false;
  11264. this.video.loop = true;
  11265. this.video.addEventListener("canplaythrough", function () {
  11266. if (_this._texture) {
  11267. _this._texture.isReady = true;
  11268. }
  11269. });
  11270. urls.forEach(function (url) {
  11271. var source = document.createElement("source");
  11272. source.src = url;
  11273. _this.video.appendChild(source);
  11274. });
  11275. this._lastUpdate = BABYLON.Tools.Now;
  11276. }
  11277. VideoTexture.prototype.update = function () {
  11278. if (this._autoLaunch) {
  11279. this._autoLaunch = false;
  11280. this.video.play();
  11281. }
  11282. var now = BABYLON.Tools.Now;
  11283. if (now - this._lastUpdate < 15) {
  11284. return false;
  11285. }
  11286. this._lastUpdate = now;
  11287. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11288. return true;
  11289. };
  11290. return VideoTexture;
  11291. })(BABYLON.Texture);
  11292. BABYLON.VideoTexture = VideoTexture;
  11293. })(BABYLON || (BABYLON = {}));
  11294. var BABYLON;
  11295. (function (BABYLON) {
  11296. var EffectFallbacks = (function () {
  11297. function EffectFallbacks() {
  11298. this._defines = {};
  11299. this._currentRank = 32;
  11300. this._maxRank = -1;
  11301. }
  11302. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11303. if (!this._defines[rank]) {
  11304. if (rank < this._currentRank) {
  11305. this._currentRank = rank;
  11306. }
  11307. if (rank > this._maxRank) {
  11308. this._maxRank = rank;
  11309. }
  11310. this._defines[rank] = new Array();
  11311. }
  11312. this._defines[rank].push(define);
  11313. };
  11314. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11315. get: function () {
  11316. return this._currentRank <= this._maxRank;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11322. var currentFallbacks = this._defines[this._currentRank];
  11323. for (var index = 0; index < currentFallbacks.length; index++) {
  11324. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11325. }
  11326. this._currentRank++;
  11327. return currentDefines;
  11328. };
  11329. return EffectFallbacks;
  11330. })();
  11331. BABYLON.EffectFallbacks = EffectFallbacks;
  11332. var Effect = (function () {
  11333. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11334. var _this = this;
  11335. this._isReady = false;
  11336. this._compilationError = "";
  11337. this._valueCache = [];
  11338. this._engine = engine;
  11339. this.name = baseName;
  11340. this.defines = defines;
  11341. this._uniformsNames = uniformsNames.concat(samplers);
  11342. this._samplers = samplers;
  11343. this._attributesNames = attributesNames;
  11344. this.onError = onError;
  11345. this.onCompiled = onCompiled;
  11346. var vertexSource;
  11347. var fragmentSource;
  11348. if (baseName.vertexElement) {
  11349. vertexSource = document.getElementById(baseName.vertexElement);
  11350. if (!vertexSource) {
  11351. vertexSource = baseName.vertexElement;
  11352. }
  11353. } else {
  11354. vertexSource = baseName.vertex || baseName;
  11355. }
  11356. if (baseName.fragmentElement) {
  11357. fragmentSource = document.getElementById(baseName.fragmentElement);
  11358. if (!fragmentSource) {
  11359. fragmentSource = baseName.fragmentElement;
  11360. }
  11361. } else {
  11362. fragmentSource = baseName.fragment || baseName;
  11363. }
  11364. this._loadVertexShader(vertexSource, function (vertexCode) {
  11365. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11366. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11367. });
  11368. });
  11369. }
  11370. Effect.prototype.isReady = function () {
  11371. return this._isReady;
  11372. };
  11373. Effect.prototype.getProgram = function () {
  11374. return this._program;
  11375. };
  11376. Effect.prototype.getAttributesNames = function () {
  11377. return this._attributesNames;
  11378. };
  11379. Effect.prototype.getAttributeLocation = function (index) {
  11380. return this._attributes[index];
  11381. };
  11382. Effect.prototype.getAttributeLocationByName = function (name) {
  11383. var index = this._attributesNames.indexOf(name);
  11384. return this._attributes[index];
  11385. };
  11386. Effect.prototype.getAttributesCount = function () {
  11387. return this._attributes.length;
  11388. };
  11389. Effect.prototype.getUniformIndex = function (uniformName) {
  11390. return this._uniformsNames.indexOf(uniformName);
  11391. };
  11392. Effect.prototype.getUniform = function (uniformName) {
  11393. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11394. };
  11395. Effect.prototype.getSamplers = function () {
  11396. return this._samplers;
  11397. };
  11398. Effect.prototype.getCompilationError = function () {
  11399. return this._compilationError;
  11400. };
  11401. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11402. if (vertex instanceof HTMLElement) {
  11403. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11404. callback(vertexCode);
  11405. return;
  11406. }
  11407. if (BABYLON.Effect.ShadersStore[vertex + "VertexShader"]) {
  11408. callback(BABYLON.Effect.ShadersStore[vertex + "VertexShader"]);
  11409. return;
  11410. }
  11411. var vertexShaderUrl;
  11412. if (vertex[0] === ".") {
  11413. vertexShaderUrl = vertex;
  11414. } else {
  11415. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11416. }
  11417. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11418. };
  11419. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11420. if (fragment instanceof HTMLElement) {
  11421. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11422. callback(fragmentCode);
  11423. return;
  11424. }
  11425. if (BABYLON.Effect.ShadersStore[fragment + "PixelShader"]) {
  11426. callback(BABYLON.Effect.ShadersStore[fragment + "PixelShader"]);
  11427. return;
  11428. }
  11429. if (BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]) {
  11430. callback(BABYLON.Effect.ShadersStore[fragment + "FragmentShader"]);
  11431. return;
  11432. }
  11433. var fragmentShaderUrl;
  11434. if (fragment[0] === ".") {
  11435. fragmentShaderUrl = fragment;
  11436. } else {
  11437. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11438. }
  11439. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11440. };
  11441. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11442. try {
  11443. var engine = this._engine;
  11444. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11445. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11446. this._attributes = engine.getAttributes(this._program, attributesNames);
  11447. for (var index = 0; index < this._samplers.length; index++) {
  11448. var sampler = this.getUniform(this._samplers[index]);
  11449. if (sampler == null) {
  11450. this._samplers.splice(index, 1);
  11451. index--;
  11452. }
  11453. }
  11454. engine.bindSamplers(this);
  11455. this._isReady = true;
  11456. if (this.onCompiled) {
  11457. this.onCompiled(this);
  11458. }
  11459. } catch (e) {
  11460. if (e.message.indexOf("highp") !== -1) {
  11461. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  11462. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  11463. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11464. return;
  11465. }
  11466. if (fallbacks && fallbacks.isMoreFallbacks) {
  11467. defines = fallbacks.reduce(defines);
  11468. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  11469. } else {
  11470. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  11471. BABYLON.Tools.Error("Defines: " + defines);
  11472. BABYLON.Tools.Error("Error: " + e.message);
  11473. this._compilationError = e.message;
  11474. if (this.onError) {
  11475. this.onError(this, this._compilationError);
  11476. }
  11477. }
  11478. }
  11479. };
  11480. Effect.prototype._bindTexture = function (channel, texture) {
  11481. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  11482. };
  11483. Effect.prototype.setTexture = function (channel, texture) {
  11484. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  11485. };
  11486. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11487. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  11488. };
  11489. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  11490. if (!this._valueCache[uniformName]) {
  11491. this._valueCache[uniformName] = [x, y];
  11492. return;
  11493. }
  11494. this._valueCache[uniformName][0] = x;
  11495. this._valueCache[uniformName][1] = y;
  11496. };
  11497. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  11498. if (!this._valueCache[uniformName]) {
  11499. this._valueCache[uniformName] = [x, y, z];
  11500. return;
  11501. }
  11502. this._valueCache[uniformName][0] = x;
  11503. this._valueCache[uniformName][1] = y;
  11504. this._valueCache[uniformName][2] = z;
  11505. };
  11506. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  11507. if (!this._valueCache[uniformName]) {
  11508. this._valueCache[uniformName] = [x, y, z, w];
  11509. return;
  11510. }
  11511. this._valueCache[uniformName][0] = x;
  11512. this._valueCache[uniformName][1] = y;
  11513. this._valueCache[uniformName][2] = z;
  11514. this._valueCache[uniformName][3] = w;
  11515. };
  11516. Effect.prototype.setArray = function (uniformName, array) {
  11517. this._engine.setArray(this.getUniform(uniformName), array);
  11518. return this;
  11519. };
  11520. Effect.prototype.setMatrices = function (uniformName, matrices) {
  11521. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  11522. return this;
  11523. };
  11524. Effect.prototype.setMatrix = function (uniformName, matrix) {
  11525. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  11526. return this;
  11527. };
  11528. Effect.prototype.setFloat = function (uniformName, value) {
  11529. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  11530. return this;
  11531. this._valueCache[uniformName] = value;
  11532. this._engine.setFloat(this.getUniform(uniformName), value);
  11533. return this;
  11534. };
  11535. Effect.prototype.setBool = function (uniformName, bool) {
  11536. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  11537. return this;
  11538. this._valueCache[uniformName] = bool;
  11539. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  11540. return this;
  11541. };
  11542. Effect.prototype.setVector2 = function (uniformName, vector2) {
  11543. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector2.x && this._valueCache[uniformName][1] == vector2.y)
  11544. return this;
  11545. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  11546. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  11547. return this;
  11548. };
  11549. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  11550. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y)
  11551. return this;
  11552. this._cacheFloat2(uniformName, x, y);
  11553. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  11554. return this;
  11555. };
  11556. Effect.prototype.setVector3 = function (uniformName, vector3) {
  11557. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == vector3.x && this._valueCache[uniformName][1] == vector3.y && this._valueCache[uniformName][2] == vector3.z)
  11558. return this;
  11559. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  11560. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  11561. return this;
  11562. };
  11563. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  11564. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z)
  11565. return this;
  11566. this._cacheFloat3(uniformName, x, y, z);
  11567. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  11568. return this;
  11569. };
  11570. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  11571. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == x && this._valueCache[uniformName][1] == y && this._valueCache[uniformName][2] == z && this._valueCache[uniformName][3] == w)
  11572. return this;
  11573. this._cacheFloat4(uniformName, x, y, z, w);
  11574. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  11575. return this;
  11576. };
  11577. Effect.prototype.setColor3 = function (uniformName, color3) {
  11578. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] == color3.r && this._valueCache[uniformName][1] == color3.g && this._valueCache[uniformName][2] == color3.b)
  11579. return this;
  11580. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  11581. this._engine.setColor3(this.getUniform(uniformName), color3);
  11582. return this;
  11583. };
  11584. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  11585. 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)
  11586. return this;
  11587. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  11588. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  11589. return this;
  11590. };
  11591. 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}",
  11592. 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}",
  11593. 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}",
  11594. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brick;\nuniform vec3 joint;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brick;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(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 brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  11595. 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}",
  11596. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  11597. 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}",
  11598. 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}",
  11599. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11600. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  11601. 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}",
  11602. emptyPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvoid main(void)\n{\n \n}",
  11603. 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}",
  11604. 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 alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - 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 vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  11605. 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}",
  11606. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1;\nuniform vec3 herb2;\nuniform vec3 herb3;\nuniform vec3 dirt;\nuniform vec3 ground;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(ground, herb1, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3, rand(gl_FragCoord.xy));\n color = mix(color, herb1, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  11607. 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}",
  11608. 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}",
  11609. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  11610. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  11611. 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}",
  11612. 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}",
  11613. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth ;\nuniform float amplitude;\nuniform vec3 brick;\nuniform vec3 joint;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brick;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(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 t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  11614. 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}",
  11615. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  11616. 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}",
  11617. 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}",
  11618. 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}",
  11619. 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}",
  11620. 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}",
  11621. 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}",
  11622. 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}",
  11623. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  11624. 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}",
  11625. 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}",
  11626. 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}",
  11627. 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}",
  11628. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  11629. };
  11630. return Effect;
  11631. })();
  11632. BABYLON.Effect = Effect;
  11633. })(BABYLON || (BABYLON = {}));
  11634. var BABYLON;
  11635. (function (BABYLON) {
  11636. var Material = (function () {
  11637. function Material(name, scene, doNotAdd) {
  11638. this.name = name;
  11639. this.checkReadyOnEveryCall = true;
  11640. this.checkReadyOnlyOnce = false;
  11641. this.state = "";
  11642. this.alpha = 1.0;
  11643. this.backFaceCulling = true;
  11644. this._wasPreviouslyReady = false;
  11645. this._fillMode = Material.TriangleFillMode;
  11646. this.pointSize = 1.0;
  11647. this.id = name;
  11648. this._scene = scene;
  11649. if (!doNotAdd) {
  11650. scene.materials.push(this);
  11651. }
  11652. }
  11653. Object.defineProperty(Material, "TriangleFillMode", {
  11654. get: function () {
  11655. return Material._TriangleFillMode;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Material, "WireFrameFillMode", {
  11661. get: function () {
  11662. return Material._WireFrameFillMode;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Material, "PointFillMode", {
  11668. get: function () {
  11669. return Material._PointFillMode;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Material.prototype, "wireframe", {
  11675. get: function () {
  11676. return this._fillMode === Material.WireFrameFillMode;
  11677. },
  11678. set: function (value) {
  11679. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Material.prototype, "pointsCloud", {
  11685. get: function () {
  11686. return this._fillMode === Material.PointFillMode;
  11687. },
  11688. set: function (value) {
  11689. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Material.prototype, "fillMode", {
  11695. get: function () {
  11696. return this._fillMode;
  11697. },
  11698. set: function (value) {
  11699. this._fillMode = value;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Material.prototype.isReady = function (mesh, useInstances) {
  11705. return true;
  11706. };
  11707. Material.prototype.getEffect = function () {
  11708. return this._effect;
  11709. };
  11710. Material.prototype.getScene = function () {
  11711. return this._scene;
  11712. };
  11713. Material.prototype.needAlphaBlending = function () {
  11714. return (this.alpha < 1.0);
  11715. };
  11716. Material.prototype.needAlphaTesting = function () {
  11717. return false;
  11718. };
  11719. Material.prototype.getAlphaTestTexture = function () {
  11720. return null;
  11721. };
  11722. Material.prototype.trackCreation = function (onCompiled, onError) {
  11723. };
  11724. Material.prototype._preBind = function () {
  11725. var engine = this._scene.getEngine();
  11726. engine.enableEffect(this._effect);
  11727. engine.setState(this.backFaceCulling);
  11728. };
  11729. Material.prototype.bind = function (world, mesh) {
  11730. };
  11731. Material.prototype.bindOnlyWorldMatrix = function (world) {
  11732. };
  11733. Material.prototype.unbind = function () {
  11734. };
  11735. Material.prototype.dispose = function (forceDisposeEffect) {
  11736. var index = this._scene.materials.indexOf(this);
  11737. this._scene.materials.splice(index, 1);
  11738. if (forceDisposeEffect && this._effect) {
  11739. this._scene.getEngine()._releaseEffect(this._effect);
  11740. this._effect = null;
  11741. }
  11742. if (this.onDispose) {
  11743. this.onDispose();
  11744. }
  11745. };
  11746. Material._TriangleFillMode = 0;
  11747. Material._WireFrameFillMode = 1;
  11748. Material._PointFillMode = 2;
  11749. return Material;
  11750. })();
  11751. BABYLON.Material = Material;
  11752. })(BABYLON || (BABYLON = {}));
  11753. var __extends = this.__extends || function (d, b) {
  11754. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11755. function __() { this.constructor = d; }
  11756. __.prototype = b.prototype;
  11757. d.prototype = new __();
  11758. };
  11759. var BABYLON;
  11760. (function (BABYLON) {
  11761. var maxSimultaneousLights = 4;
  11762. var FresnelParameters = (function () {
  11763. function FresnelParameters() {
  11764. this.isEnabled = true;
  11765. this.leftColor = BABYLON.Color3.White();
  11766. this.rightColor = BABYLON.Color3.Black();
  11767. this.bias = 0;
  11768. this.power = 1;
  11769. }
  11770. return FresnelParameters;
  11771. })();
  11772. BABYLON.FresnelParameters = FresnelParameters;
  11773. var StandardMaterial = (function (_super) {
  11774. __extends(StandardMaterial, _super);
  11775. function StandardMaterial(name, scene) {
  11776. var _this = this;
  11777. _super.call(this, name, scene);
  11778. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11779. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  11780. this.specularColor = new BABYLON.Color3(1, 1, 1);
  11781. this.specularPower = 64;
  11782. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  11783. this.useAlphaFromDiffuseTexture = false;
  11784. this.useSpecularOverAlpha = true;
  11785. this.fogEnabled = true;
  11786. this._cachedDefines = null;
  11787. this._renderTargets = new BABYLON.SmartArray(16);
  11788. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  11789. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  11790. this._scaledDiffuse = new BABYLON.Color3();
  11791. this._scaledSpecular = new BABYLON.Color3();
  11792. this.getRenderTargetTextures = function () {
  11793. _this._renderTargets.reset();
  11794. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  11795. _this._renderTargets.push(_this.reflectionTexture);
  11796. }
  11797. return _this._renderTargets;
  11798. };
  11799. }
  11800. StandardMaterial.prototype.needAlphaBlending = function () {
  11801. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  11802. };
  11803. StandardMaterial.prototype.needAlphaTesting = function () {
  11804. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  11805. };
  11806. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  11807. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  11808. };
  11809. StandardMaterial.prototype.getAlphaTestTexture = function () {
  11810. return this.diffuseTexture;
  11811. };
  11812. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  11813. if (this.checkReadyOnlyOnce) {
  11814. if (this._wasPreviouslyReady) {
  11815. return true;
  11816. }
  11817. }
  11818. var scene = this.getScene();
  11819. if (!this.checkReadyOnEveryCall) {
  11820. if (this._renderId === scene.getRenderId()) {
  11821. return true;
  11822. }
  11823. }
  11824. var engine = scene.getEngine();
  11825. var defines = [];
  11826. var fallbacks = new BABYLON.EffectFallbacks();
  11827. if (scene.texturesEnabled) {
  11828. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  11829. if (!this.diffuseTexture.isReady()) {
  11830. return false;
  11831. } else {
  11832. defines.push("#define DIFFUSE");
  11833. }
  11834. }
  11835. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  11836. if (!this.ambientTexture.isReady()) {
  11837. return false;
  11838. } else {
  11839. defines.push("#define AMBIENT");
  11840. }
  11841. }
  11842. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  11843. if (!this.opacityTexture.isReady()) {
  11844. return false;
  11845. } else {
  11846. defines.push("#define OPACITY");
  11847. if (this.opacityTexture.getAlphaFromRGB) {
  11848. defines.push("#define OPACITYRGB");
  11849. }
  11850. }
  11851. }
  11852. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  11853. if (!this.reflectionTexture.isReady()) {
  11854. return false;
  11855. } else {
  11856. defines.push("#define REFLECTION");
  11857. fallbacks.addFallback(0, "REFLECTION");
  11858. }
  11859. }
  11860. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  11861. if (!this.emissiveTexture.isReady()) {
  11862. return false;
  11863. } else {
  11864. defines.push("#define EMISSIVE");
  11865. }
  11866. }
  11867. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  11868. if (!this.specularTexture.isReady()) {
  11869. return false;
  11870. } else {
  11871. defines.push("#define SPECULAR");
  11872. fallbacks.addFallback(0, "SPECULAR");
  11873. }
  11874. }
  11875. }
  11876. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled) {
  11877. if (!this.bumpTexture.isReady()) {
  11878. return false;
  11879. } else {
  11880. defines.push("#define BUMP");
  11881. fallbacks.addFallback(0, "BUMP");
  11882. }
  11883. }
  11884. if (this.useSpecularOverAlpha) {
  11885. defines.push("#define SPECULAROVERALPHA");
  11886. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  11887. }
  11888. if (scene.clipPlane) {
  11889. defines.push("#define CLIPPLANE");
  11890. }
  11891. if (engine.getAlphaTesting()) {
  11892. defines.push("#define ALPHATEST");
  11893. }
  11894. if (this._shouldUseAlphaFromDiffuseTexture()) {
  11895. defines.push("#define ALPHAFROMDIFFUSE");
  11896. }
  11897. if (this.pointsCloud) {
  11898. defines.push("#define POINTSIZE");
  11899. }
  11900. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  11901. defines.push("#define FOG");
  11902. fallbacks.addFallback(1, "FOG");
  11903. }
  11904. var shadowsActivated = false;
  11905. var lightIndex = 0;
  11906. if (scene.lightsEnabled) {
  11907. for (var index = 0; index < scene.lights.length; index++) {
  11908. var light = scene.lights[index];
  11909. if (!light.isEnabled()) {
  11910. continue;
  11911. }
  11912. if (light._excludedMeshesIds.length > 0) {
  11913. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  11914. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  11915. if (excludedMesh) {
  11916. light.excludedMeshes.push(excludedMesh);
  11917. }
  11918. }
  11919. light._excludedMeshesIds = [];
  11920. }
  11921. if (light._includedOnlyMeshesIds.length > 0) {
  11922. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  11923. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  11924. if (includedOnlyMesh) {
  11925. light.includedOnlyMeshes.push(includedOnlyMesh);
  11926. }
  11927. }
  11928. light._includedOnlyMeshesIds = [];
  11929. }
  11930. if (!light.canAffectMesh(mesh)) {
  11931. continue;
  11932. }
  11933. defines.push("#define LIGHT" + lightIndex);
  11934. if (lightIndex > 0) {
  11935. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  11936. }
  11937. var type;
  11938. if (light instanceof BABYLON.SpotLight) {
  11939. type = "#define SPOTLIGHT" + lightIndex;
  11940. } else if (light instanceof BABYLON.HemisphericLight) {
  11941. type = "#define HEMILIGHT" + lightIndex;
  11942. } else {
  11943. type = "#define POINTDIRLIGHT" + lightIndex;
  11944. }
  11945. defines.push(type);
  11946. if (lightIndex > 0) {
  11947. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  11948. }
  11949. if (scene.shadowsEnabled) {
  11950. var shadowGenerator = light.getShadowGenerator();
  11951. if (mesh && mesh.receiveShadows && shadowGenerator) {
  11952. defines.push("#define SHADOW" + lightIndex);
  11953. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  11954. if (!shadowsActivated) {
  11955. defines.push("#define SHADOWS");
  11956. shadowsActivated = true;
  11957. }
  11958. if (shadowGenerator.useVarianceShadowMap) {
  11959. defines.push("#define SHADOWVSM" + lightIndex);
  11960. if (lightIndex > 0) {
  11961. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  11962. }
  11963. }
  11964. if (shadowGenerator.usePoissonSampling) {
  11965. defines.push("#define SHADOWPCF" + lightIndex);
  11966. if (lightIndex > 0) {
  11967. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  11968. }
  11969. }
  11970. }
  11971. }
  11972. lightIndex++;
  11973. if (lightIndex == maxSimultaneousLights)
  11974. break;
  11975. }
  11976. }
  11977. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11978. var fresnelRank = 1;
  11979. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  11980. defines.push("#define DIFFUSEFRESNEL");
  11981. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  11982. fresnelRank++;
  11983. }
  11984. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  11985. defines.push("#define OPACITYFRESNEL");
  11986. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  11987. fresnelRank++;
  11988. }
  11989. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  11990. defines.push("#define REFLECTIONFRESNEL");
  11991. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  11992. fresnelRank++;
  11993. }
  11994. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  11995. defines.push("#define EMISSIVEFRESNEL");
  11996. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  11997. fresnelRank++;
  11998. }
  11999. defines.push("#define FRESNEL");
  12000. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12001. }
  12002. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12003. if (mesh) {
  12004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12005. attribs.push(BABYLON.VertexBuffer.UVKind);
  12006. defines.push("#define UV1");
  12007. }
  12008. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12009. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12010. defines.push("#define UV2");
  12011. }
  12012. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12013. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12014. defines.push("#define VERTEXCOLOR");
  12015. if (mesh.hasVertexAlpha) {
  12016. defines.push("#define VERTEXALPHA");
  12017. }
  12018. }
  12019. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12020. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12021. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12022. defines.push("#define BONES");
  12023. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12024. defines.push("#define BONES4");
  12025. fallbacks.addFallback(0, "BONES4");
  12026. }
  12027. if (useInstances) {
  12028. defines.push("#define INSTANCES");
  12029. attribs.push("world0");
  12030. attribs.push("world1");
  12031. attribs.push("world2");
  12032. attribs.push("world3");
  12033. }
  12034. }
  12035. var join = defines.join("\n");
  12036. if (this._cachedDefines != join) {
  12037. this._cachedDefines = join;
  12038. var shaderName = "default";
  12039. if (!scene.getEngine().getCaps().standardDerivatives) {
  12040. shaderName = "legacydefault";
  12041. }
  12042. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12043. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12044. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12045. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12046. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12047. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12048. "vFogInfos", "vFogColor", "pointSize",
  12049. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12050. "mBones",
  12051. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12052. "darkness0", "darkness1", "darkness2", "darkness3",
  12053. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12054. ], [
  12055. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12056. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12057. ], join, fallbacks, this.onCompiled, this.onError);
  12058. }
  12059. if (!this._effect.isReady()) {
  12060. return false;
  12061. }
  12062. this._renderId = scene.getRenderId();
  12063. this._wasPreviouslyReady = true;
  12064. return true;
  12065. };
  12066. StandardMaterial.prototype.unbind = function () {
  12067. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12068. this._effect.setTexture("reflection2DSampler", null);
  12069. }
  12070. };
  12071. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12072. this._effect.setMatrix("world", world);
  12073. };
  12074. StandardMaterial.prototype.bind = function (world, mesh) {
  12075. var scene = this.getScene();
  12076. this.bindOnlyWorldMatrix(world);
  12077. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12078. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12079. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12080. }
  12081. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12082. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12083. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12084. }
  12085. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12086. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12087. }
  12088. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12089. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12090. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12091. }
  12092. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12093. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12094. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12095. }
  12096. if (this.diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  12097. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12098. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12099. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12100. }
  12101. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  12102. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12103. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12104. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12105. }
  12106. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  12107. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12108. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12109. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12110. }
  12111. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  12112. if (this.reflectionTexture.isCube) {
  12113. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12114. } else {
  12115. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12116. }
  12117. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12118. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12119. }
  12120. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  12121. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12122. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12123. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12124. }
  12125. if (this.specularTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  12126. this._effect.setTexture("specularSampler", this.specularTexture);
  12127. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12128. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12129. }
  12130. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled) {
  12131. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12132. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12133. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12134. }
  12135. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12136. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12137. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12138. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12139. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12140. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12141. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12142. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12143. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12144. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12145. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12146. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12147. if (scene.lightsEnabled) {
  12148. var lightIndex = 0;
  12149. for (var index = 0; index < scene.lights.length; index++) {
  12150. var light = scene.lights[index];
  12151. if (!light.isEnabled()) {
  12152. continue;
  12153. }
  12154. if (!light.canAffectMesh(mesh)) {
  12155. continue;
  12156. }
  12157. if (light instanceof BABYLON.PointLight) {
  12158. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12159. } else if (light instanceof BABYLON.DirectionalLight) {
  12160. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12161. } else if (light instanceof BABYLON.SpotLight) {
  12162. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12163. } else if (light instanceof BABYLON.HemisphericLight) {
  12164. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12165. }
  12166. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12167. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12168. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12169. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12170. if (scene.shadowsEnabled) {
  12171. var shadowGenerator = light.getShadowGenerator();
  12172. if (mesh.receiveShadows && shadowGenerator) {
  12173. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  12174. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  12175. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  12176. }
  12177. }
  12178. lightIndex++;
  12179. if (lightIndex == maxSimultaneousLights)
  12180. break;
  12181. }
  12182. }
  12183. if (scene.clipPlane) {
  12184. var clipPlane = scene.clipPlane;
  12185. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12186. }
  12187. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  12188. this._effect.setMatrix("view", scene.getViewMatrix());
  12189. }
  12190. if (scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  12191. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  12192. this._effect.setColor3("vFogColor", scene.fogColor);
  12193. }
  12194. if (this.pointsCloud) {
  12195. this._effect.setFloat("pointSize", this.pointSize);
  12196. }
  12197. };
  12198. StandardMaterial.prototype.getAnimatables = function () {
  12199. var results = [];
  12200. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  12201. results.push(this.diffuseTexture);
  12202. }
  12203. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  12204. results.push(this.ambientTexture);
  12205. }
  12206. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  12207. results.push(this.opacityTexture);
  12208. }
  12209. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  12210. results.push(this.reflectionTexture);
  12211. }
  12212. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  12213. results.push(this.emissiveTexture);
  12214. }
  12215. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  12216. results.push(this.specularTexture);
  12217. }
  12218. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12219. results.push(this.bumpTexture);
  12220. }
  12221. return results;
  12222. };
  12223. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12224. if (this.diffuseTexture) {
  12225. this.diffuseTexture.dispose();
  12226. }
  12227. if (this.ambientTexture) {
  12228. this.ambientTexture.dispose();
  12229. }
  12230. if (this.opacityTexture) {
  12231. this.opacityTexture.dispose();
  12232. }
  12233. if (this.reflectionTexture) {
  12234. this.reflectionTexture.dispose();
  12235. }
  12236. if (this.emissiveTexture) {
  12237. this.emissiveTexture.dispose();
  12238. }
  12239. if (this.specularTexture) {
  12240. this.specularTexture.dispose();
  12241. }
  12242. if (this.bumpTexture) {
  12243. this.bumpTexture.dispose();
  12244. }
  12245. _super.prototype.dispose.call(this, forceDisposeEffect);
  12246. };
  12247. StandardMaterial.prototype.clone = function (name) {
  12248. var newStandardMaterial = new BABYLON.StandardMaterial(name, this.getScene());
  12249. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12250. newStandardMaterial.alpha = this.alpha;
  12251. newStandardMaterial.fillMode = this.fillMode;
  12252. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12253. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12254. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12255. }
  12256. if (this.ambientTexture && this.ambientTexture.clone) {
  12257. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12258. }
  12259. if (this.opacityTexture && this.opacityTexture.clone) {
  12260. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12261. }
  12262. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12263. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12264. }
  12265. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12266. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12267. }
  12268. if (this.specularTexture && this.specularTexture.clone) {
  12269. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12270. }
  12271. if (this.bumpTexture && this.bumpTexture.clone) {
  12272. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12273. }
  12274. newStandardMaterial.ambientColor = this.ambientColor.clone();
  12275. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  12276. newStandardMaterial.specularColor = this.specularColor.clone();
  12277. newStandardMaterial.specularPower = this.specularPower;
  12278. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  12279. return newStandardMaterial;
  12280. };
  12281. StandardMaterial.DiffuseTextureEnabled = true;
  12282. StandardMaterial.AmbientTextureEnabled = true;
  12283. StandardMaterial.OpacityTextureEnabled = true;
  12284. StandardMaterial.ReflectionTextureEnabled = true;
  12285. StandardMaterial.EmissiveTextureEnabled = true;
  12286. StandardMaterial.SpecularTextureEnabled = true;
  12287. StandardMaterial.BumpTextureEnabled = true;
  12288. return StandardMaterial;
  12289. })(BABYLON.Material);
  12290. BABYLON.StandardMaterial = StandardMaterial;
  12291. })(BABYLON || (BABYLON = {}));
  12292. var __extends = this.__extends || function (d, b) {
  12293. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12294. function __() { this.constructor = d; }
  12295. __.prototype = b.prototype;
  12296. d.prototype = new __();
  12297. };
  12298. var BABYLON;
  12299. (function (BABYLON) {
  12300. var MultiMaterial = (function (_super) {
  12301. __extends(MultiMaterial, _super);
  12302. function MultiMaterial(name, scene) {
  12303. _super.call(this, name, scene, true);
  12304. this.subMaterials = new Array();
  12305. scene.multiMaterials.push(this);
  12306. }
  12307. MultiMaterial.prototype.getSubMaterial = function (index) {
  12308. if (index < 0 || index >= this.subMaterials.length) {
  12309. return this.getScene().defaultMaterial;
  12310. }
  12311. return this.subMaterials[index];
  12312. };
  12313. MultiMaterial.prototype.isReady = function (mesh) {
  12314. for (var index = 0; index < this.subMaterials.length; index++) {
  12315. var subMaterial = this.subMaterials[index];
  12316. if (subMaterial) {
  12317. if (!this.subMaterials[index].isReady(mesh)) {
  12318. return false;
  12319. }
  12320. }
  12321. }
  12322. return true;
  12323. };
  12324. return MultiMaterial;
  12325. })(BABYLON.Material);
  12326. BABYLON.MultiMaterial = MultiMaterial;
  12327. })(BABYLON || (BABYLON = {}));
  12328. var BABYLON;
  12329. (function (BABYLON) {
  12330. var Database = (function () {
  12331. function Database(urlToScene, callbackManifestChecked) {
  12332. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  12333. this.callbackManifestChecked = callbackManifestChecked;
  12334. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  12335. this.db = null;
  12336. this.enableSceneOffline = false;
  12337. this.enableTexturesOffline = false;
  12338. this.manifestVersionFound = 0;
  12339. this.mustUpdateRessources = false;
  12340. this.hasReachedQuota = false;
  12341. this.checkManifestFile();
  12342. }
  12343. Database.prototype.checkManifestFile = function () {
  12344. var _this = this;
  12345. function noManifestFile() {
  12346. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  12347. that.enableSceneOffline = false;
  12348. that.enableTexturesOffline = false;
  12349. that.callbackManifestChecked(false);
  12350. }
  12351. var that = this;
  12352. var manifestURL = this.currentSceneUrl + ".manifest";
  12353. var xhr = new XMLHttpRequest();
  12354. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  12355. xhr.open("GET", manifestURLTimeStamped, true);
  12356. xhr.addEventListener("load", function () {
  12357. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12358. try {
  12359. var manifestFile = JSON.parse(xhr.response);
  12360. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  12361. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  12362. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  12363. _this.manifestVersionFound = manifestFile.version;
  12364. }
  12365. if (_this.callbackManifestChecked) {
  12366. _this.callbackManifestChecked(true);
  12367. }
  12368. } catch (ex) {
  12369. noManifestFile();
  12370. }
  12371. } else {
  12372. noManifestFile();
  12373. }
  12374. }, false);
  12375. xhr.addEventListener("error", function (event) {
  12376. noManifestFile();
  12377. }, false);
  12378. try {
  12379. xhr.send();
  12380. } catch (ex) {
  12381. BABYLON.Tools.Error("Error on XHR send request.");
  12382. that.callbackManifestChecked(false);
  12383. }
  12384. };
  12385. Database.prototype.openAsync = function (successCallback, errorCallback) {
  12386. var _this = this;
  12387. function handleError() {
  12388. that.isSupported = false;
  12389. if (errorCallback)
  12390. errorCallback();
  12391. }
  12392. var that = this;
  12393. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  12394. this.isSupported = false;
  12395. if (errorCallback)
  12396. errorCallback();
  12397. } else {
  12398. if (!this.db) {
  12399. this.hasReachedQuota = false;
  12400. this.isSupported = true;
  12401. var request = this.idbFactory.open("babylonjs", 1);
  12402. request.onerror = function (event) {
  12403. handleError();
  12404. };
  12405. request.onblocked = function (event) {
  12406. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  12407. handleError();
  12408. };
  12409. request.onsuccess = function (event) {
  12410. _this.db = request.result;
  12411. successCallback();
  12412. };
  12413. request.onupgradeneeded = function (event) {
  12414. _this.db = (event.target).result;
  12415. try {
  12416. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  12417. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  12418. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  12419. } catch (ex) {
  12420. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  12421. handleError();
  12422. }
  12423. };
  12424. } else {
  12425. if (successCallback)
  12426. successCallback();
  12427. }
  12428. }
  12429. };
  12430. Database.prototype.loadImageFromDB = function (url, image) {
  12431. var _this = this;
  12432. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  12433. var saveAndLoadImage = function () {
  12434. if (!_this.hasReachedQuota && _this.db !== null) {
  12435. _this._saveImageIntoDBAsync(completeURL, image);
  12436. } else {
  12437. image.src = url;
  12438. }
  12439. };
  12440. if (!this.mustUpdateRessources) {
  12441. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  12442. } else {
  12443. saveAndLoadImage();
  12444. }
  12445. };
  12446. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  12447. if (this.isSupported && this.db !== null) {
  12448. var texture;
  12449. var transaction = this.db.transaction(["textures"]);
  12450. transaction.onabort = function (event) {
  12451. image.src = url;
  12452. };
  12453. transaction.oncomplete = function (event) {
  12454. var blobTextureURL;
  12455. if (texture) {
  12456. var URL = window.URL || window.webkitURL;
  12457. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  12458. image.onerror = function () {
  12459. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  12460. image.src = url;
  12461. };
  12462. image.src = blobTextureURL;
  12463. } else {
  12464. notInDBCallback();
  12465. }
  12466. };
  12467. var getRequest = transaction.objectStore("textures").get(url);
  12468. getRequest.onsuccess = function (event) {
  12469. texture = (event.target).result;
  12470. };
  12471. getRequest.onerror = function (event) {
  12472. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  12473. image.src = url;
  12474. };
  12475. } else {
  12476. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12477. image.src = url;
  12478. }
  12479. };
  12480. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  12481. var _this = this;
  12482. if (this.isSupported) {
  12483. var generateBlobUrl = function () {
  12484. var blobTextureURL;
  12485. if (blob) {
  12486. var URL = window.URL || window.webkitURL;
  12487. try {
  12488. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  12489. } catch (ex) {
  12490. blobTextureURL = URL.createObjectURL(blob);
  12491. }
  12492. }
  12493. image.src = blobTextureURL;
  12494. };
  12495. if (BABYLON.Database.isUASupportingBlobStorage) {
  12496. var xhr = new XMLHttpRequest(), blob;
  12497. xhr.open("GET", url, true);
  12498. xhr.responseType = "blob";
  12499. xhr.addEventListener("load", function () {
  12500. if (xhr.status === 200) {
  12501. blob = xhr.response;
  12502. var transaction = _this.db.transaction(["textures"], "readwrite");
  12503. transaction.onabort = function (event) {
  12504. try {
  12505. if (event.srcElement.error.name === "QuotaExceededError") {
  12506. this.hasReachedQuota = true;
  12507. }
  12508. } catch (ex) {
  12509. }
  12510. generateBlobUrl();
  12511. };
  12512. transaction.oncomplete = function (event) {
  12513. generateBlobUrl();
  12514. };
  12515. var newTexture = { textureUrl: url, data: blob };
  12516. try {
  12517. var addRequest = transaction.objectStore("textures").put(newTexture);
  12518. addRequest.onsuccess = function (event) {
  12519. };
  12520. addRequest.onerror = function (event) {
  12521. generateBlobUrl();
  12522. };
  12523. } catch (ex) {
  12524. if (ex.code === 25) {
  12525. BABYLON.Database.isUASupportingBlobStorage = false;
  12526. }
  12527. image.src = url;
  12528. }
  12529. } else {
  12530. image.src = url;
  12531. }
  12532. }, false);
  12533. xhr.addEventListener("error", function (event) {
  12534. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  12535. image.src = url;
  12536. }, false);
  12537. xhr.send();
  12538. } else {
  12539. image.src = url;
  12540. }
  12541. } else {
  12542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12543. image.src = url;
  12544. }
  12545. };
  12546. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  12547. var _this = this;
  12548. var updateVersion = function (event) {
  12549. _this._saveVersionIntoDBAsync(url, versionLoaded);
  12550. };
  12551. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  12552. };
  12553. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  12554. var _this = this;
  12555. if (this.isSupported) {
  12556. var version;
  12557. try {
  12558. var transaction = this.db.transaction(["versions"]);
  12559. transaction.oncomplete = function (event) {
  12560. if (version) {
  12561. if (_this.manifestVersionFound > version.data) {
  12562. _this.mustUpdateRessources = true;
  12563. updateInDBCallback();
  12564. } else {
  12565. callback(version.data);
  12566. }
  12567. } else {
  12568. _this.mustUpdateRessources = true;
  12569. updateInDBCallback();
  12570. }
  12571. };
  12572. transaction.onabort = function (event) {
  12573. callback(-1);
  12574. };
  12575. var getRequest = transaction.objectStore("versions").get(url);
  12576. getRequest.onsuccess = function (event) {
  12577. version = (event.target).result;
  12578. };
  12579. getRequest.onerror = function (event) {
  12580. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  12581. callback(-1);
  12582. };
  12583. } catch (ex) {
  12584. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  12585. callback(-1);
  12586. }
  12587. } else {
  12588. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12589. callback(-1);
  12590. }
  12591. };
  12592. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  12593. var _this = this;
  12594. if (this.isSupported && !this.hasReachedQuota) {
  12595. try {
  12596. var transaction = this.db.transaction(["versions"], "readwrite");
  12597. transaction.onabort = function (event) {
  12598. try {
  12599. if (event.srcElement.error.name === "QuotaExceededError") {
  12600. _this.hasReachedQuota = true;
  12601. }
  12602. } catch (ex) {
  12603. }
  12604. callback(-1);
  12605. };
  12606. transaction.oncomplete = function (event) {
  12607. callback(_this.manifestVersionFound);
  12608. };
  12609. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  12610. var addRequest = transaction.objectStore("versions").put(newVersion);
  12611. addRequest.onsuccess = function (event) {
  12612. };
  12613. addRequest.onerror = function (event) {
  12614. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  12615. };
  12616. } catch (ex) {
  12617. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  12618. callback(-1);
  12619. }
  12620. } else {
  12621. callback(-1);
  12622. }
  12623. };
  12624. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  12625. var _this = this;
  12626. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  12627. var saveAndLoadFile = function (event) {
  12628. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  12629. };
  12630. this._checkVersionFromDB(completeUrl, function (version) {
  12631. if (version !== -1) {
  12632. if (!_this.mustUpdateRessources) {
  12633. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  12634. } else {
  12635. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  12636. }
  12637. } else {
  12638. errorCallback();
  12639. }
  12640. });
  12641. };
  12642. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  12643. if (this.isSupported) {
  12644. var targetStore;
  12645. if (url.indexOf(".babylon") !== -1) {
  12646. targetStore = "scenes";
  12647. } else {
  12648. targetStore = "textures";
  12649. }
  12650. var file;
  12651. var transaction = this.db.transaction([targetStore]);
  12652. transaction.oncomplete = function (event) {
  12653. if (file) {
  12654. callback(file.data);
  12655. } else {
  12656. notInDBCallback();
  12657. }
  12658. };
  12659. transaction.onabort = function (event) {
  12660. notInDBCallback();
  12661. };
  12662. var getRequest = transaction.objectStore(targetStore).get(url);
  12663. getRequest.onsuccess = function (event) {
  12664. file = (event.target).result;
  12665. };
  12666. getRequest.onerror = function (event) {
  12667. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  12668. notInDBCallback();
  12669. };
  12670. } else {
  12671. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12672. callback();
  12673. }
  12674. };
  12675. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  12676. var _this = this;
  12677. if (this.isSupported) {
  12678. var targetStore;
  12679. if (url.indexOf(".babylon") !== -1) {
  12680. targetStore = "scenes";
  12681. } else {
  12682. targetStore = "textures";
  12683. }
  12684. var xhr = new XMLHttpRequest(), fileData;
  12685. xhr.open("GET", url, true);
  12686. if (useArrayBuffer) {
  12687. xhr.responseType = "arraybuffer";
  12688. }
  12689. xhr.onprogress = progressCallback;
  12690. xhr.addEventListener("load", function () {
  12691. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  12692. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  12693. if (!_this.hasReachedQuota) {
  12694. var transaction = _this.db.transaction([targetStore], "readwrite");
  12695. transaction.onabort = function (event) {
  12696. try {
  12697. if (event.srcElement.error.name === "QuotaExceededError") {
  12698. this.hasReachedQuota = true;
  12699. }
  12700. } catch (ex) {
  12701. }
  12702. callback(fileData);
  12703. };
  12704. transaction.oncomplete = function (event) {
  12705. callback(fileData);
  12706. };
  12707. var newFile;
  12708. if (targetStore === "scenes") {
  12709. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  12710. } else {
  12711. newFile = { textureUrl: url, data: fileData };
  12712. }
  12713. try {
  12714. var addRequest = transaction.objectStore(targetStore).put(newFile);
  12715. addRequest.onsuccess = function (event) {
  12716. };
  12717. addRequest.onerror = function (event) {
  12718. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  12719. };
  12720. } catch (ex) {
  12721. callback(fileData);
  12722. }
  12723. } else {
  12724. callback(fileData);
  12725. }
  12726. } else {
  12727. callback();
  12728. }
  12729. }, false);
  12730. xhr.addEventListener("error", function (event) {
  12731. BABYLON.Tools.Error("error on XHR request.");
  12732. callback();
  12733. }, false);
  12734. xhr.send();
  12735. } else {
  12736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  12737. callback();
  12738. }
  12739. };
  12740. Database.isUASupportingBlobStorage = true;
  12741. Database.parseURL = function (url) {
  12742. var a = document.createElement('a');
  12743. a.href = url;
  12744. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  12745. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  12746. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  12747. return absLocation;
  12748. };
  12749. Database.ReturnFullUrlLocation = function (url) {
  12750. if (url.indexOf("http:/") === -1) {
  12751. return (BABYLON.Database.parseURL(window.location.href) + url);
  12752. } else {
  12753. return url;
  12754. }
  12755. };
  12756. return Database;
  12757. })();
  12758. BABYLON.Database = Database;
  12759. })(BABYLON || (BABYLON = {}));
  12760. var BABYLON;
  12761. (function (BABYLON) {
  12762. var SpriteManager = (function () {
  12763. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  12764. this.name = name;
  12765. this.cellSize = cellSize;
  12766. this.sprites = new Array();
  12767. this.renderingGroupId = 0;
  12768. this.fogEnabled = true;
  12769. this._vertexDeclaration = [3, 4, 4, 4];
  12770. this._vertexStrideSize = 15 * 4;
  12771. this._capacity = capacity;
  12772. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  12773. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12774. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12775. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  12776. this._scene = scene;
  12777. this._scene.spriteManagers.push(this);
  12778. this._vertexDeclaration = [3, 4, 4, 4];
  12779. this._vertexStrideSize = 15 * 4;
  12780. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  12781. var indices = [];
  12782. var index = 0;
  12783. for (var count = 0; count < capacity; count++) {
  12784. indices.push(index);
  12785. indices.push(index + 1);
  12786. indices.push(index + 2);
  12787. indices.push(index);
  12788. indices.push(index + 2);
  12789. indices.push(index + 3);
  12790. index += 4;
  12791. }
  12792. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12793. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  12794. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  12795. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  12796. }
  12797. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  12798. var arrayOffset = index * 15;
  12799. if (offsetX == 0)
  12800. offsetX = this._epsilon;
  12801. else if (offsetX == 1)
  12802. offsetX = 1 - this._epsilon;
  12803. if (offsetY == 0)
  12804. offsetY = this._epsilon;
  12805. else if (offsetY == 1)
  12806. offsetY = 1 - this._epsilon;
  12807. this._vertices[arrayOffset] = sprite.position.x;
  12808. this._vertices[arrayOffset + 1] = sprite.position.y;
  12809. this._vertices[arrayOffset + 2] = sprite.position.z;
  12810. this._vertices[arrayOffset + 3] = sprite.angle;
  12811. this._vertices[arrayOffset + 4] = sprite.size;
  12812. this._vertices[arrayOffset + 5] = offsetX;
  12813. this._vertices[arrayOffset + 6] = offsetY;
  12814. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  12815. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  12816. var offset = (sprite.cellIndex / rowSize) >> 0;
  12817. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  12818. this._vertices[arrayOffset + 10] = offset;
  12819. this._vertices[arrayOffset + 11] = sprite.color.r;
  12820. this._vertices[arrayOffset + 12] = sprite.color.g;
  12821. this._vertices[arrayOffset + 13] = sprite.color.b;
  12822. this._vertices[arrayOffset + 14] = sprite.color.a;
  12823. };
  12824. SpriteManager.prototype.render = function () {
  12825. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  12826. return;
  12827. var engine = this._scene.getEngine();
  12828. var baseSize = this._spriteTexture.getBaseSize();
  12829. var deltaTime = BABYLON.Tools.GetDeltaTime();
  12830. var max = Math.min(this._capacity, this.sprites.length);
  12831. var rowSize = baseSize.width / this.cellSize;
  12832. var offset = 0;
  12833. for (var index = 0; index < max; index++) {
  12834. var sprite = this.sprites[index];
  12835. if (!sprite) {
  12836. continue;
  12837. }
  12838. sprite._animate(deltaTime);
  12839. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  12840. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  12841. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  12842. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  12843. }
  12844. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, max * this._vertexStrideSize);
  12845. var effect = this._effectBase;
  12846. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12847. effect = this._effectFog;
  12848. }
  12849. engine.enableEffect(effect);
  12850. var viewMatrix = this._scene.getViewMatrix();
  12851. effect.setTexture("diffuseSampler", this._spriteTexture);
  12852. effect.setMatrix("view", viewMatrix);
  12853. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  12854. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  12855. if (this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12856. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  12857. effect.setColor3("vFogColor", this._scene.fogColor);
  12858. }
  12859. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  12860. effect.setBool("alphaTest", true);
  12861. engine.setColorWrite(false);
  12862. engine.draw(true, 0, max * 6);
  12863. engine.setColorWrite(true);
  12864. effect.setBool("alphaTest", false);
  12865. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12866. engine.draw(true, 0, max * 6);
  12867. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12868. };
  12869. SpriteManager.prototype.dispose = function () {
  12870. if (this._vertexBuffer) {
  12871. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  12872. this._vertexBuffer = null;
  12873. }
  12874. if (this._indexBuffer) {
  12875. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  12876. this._indexBuffer = null;
  12877. }
  12878. if (this._spriteTexture) {
  12879. this._spriteTexture.dispose();
  12880. this._spriteTexture = null;
  12881. }
  12882. var index = this._scene.spriteManagers.indexOf(this);
  12883. this._scene.spriteManagers.splice(index, 1);
  12884. if (this.onDispose) {
  12885. this.onDispose();
  12886. }
  12887. };
  12888. return SpriteManager;
  12889. })();
  12890. BABYLON.SpriteManager = SpriteManager;
  12891. })(BABYLON || (BABYLON = {}));
  12892. var BABYLON;
  12893. (function (BABYLON) {
  12894. var Sprite = (function () {
  12895. function Sprite(name, manager) {
  12896. this.name = name;
  12897. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  12898. this.size = 1.0;
  12899. this.angle = 0;
  12900. this.cellIndex = 0;
  12901. this.invertU = 0;
  12902. this.invertV = 0;
  12903. this.animations = new Array();
  12904. this._animationStarted = false;
  12905. this._loopAnimation = false;
  12906. this._fromIndex = 0;
  12907. this._toIndex = 0;
  12908. this._delay = 0;
  12909. this._direction = 1;
  12910. this._frameCount = 0;
  12911. this._time = 0;
  12912. this._manager = manager;
  12913. this._manager.sprites.push(this);
  12914. this.position = BABYLON.Vector3.Zero();
  12915. }
  12916. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  12917. this._fromIndex = from;
  12918. this._toIndex = to;
  12919. this._loopAnimation = loop;
  12920. this._delay = delay;
  12921. this._animationStarted = true;
  12922. this._direction = from < to ? 1 : -1;
  12923. this.cellIndex = from;
  12924. this._time = 0;
  12925. };
  12926. Sprite.prototype.stopAnimation = function () {
  12927. this._animationStarted = false;
  12928. };
  12929. Sprite.prototype._animate = function (deltaTime) {
  12930. if (!this._animationStarted)
  12931. return;
  12932. this._time += deltaTime;
  12933. if (this._time > this._delay) {
  12934. this._time = this._time % this._delay;
  12935. this.cellIndex += this._direction;
  12936. if (this.cellIndex == this._toIndex) {
  12937. if (this._loopAnimation) {
  12938. this.cellIndex = this._fromIndex;
  12939. } else {
  12940. this._animationStarted = false;
  12941. if (this.disposeWhenFinishedAnimating) {
  12942. this.dispose();
  12943. }
  12944. }
  12945. }
  12946. }
  12947. };
  12948. Sprite.prototype.dispose = function () {
  12949. for (var i = 0; i < this._manager.sprites.length; i++) {
  12950. if (this._manager.sprites[i] == this) {
  12951. this._manager.sprites.splice(i, 1);
  12952. }
  12953. }
  12954. };
  12955. return Sprite;
  12956. })();
  12957. BABYLON.Sprite = Sprite;
  12958. })(BABYLON || (BABYLON = {}));
  12959. var BABYLON;
  12960. (function (BABYLON) {
  12961. var Layer = (function () {
  12962. function Layer(name, imgUrl, scene, isBackground, color) {
  12963. this.name = name;
  12964. this._vertexDeclaration = [2];
  12965. this._vertexStrideSize = 2 * 4;
  12966. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  12967. this.isBackground = isBackground === undefined ? true : isBackground;
  12968. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  12969. this._scene = scene;
  12970. this._scene.layers.push(this);
  12971. var vertices = [];
  12972. vertices.push(1, 1);
  12973. vertices.push(-1, 1);
  12974. vertices.push(-1, -1);
  12975. vertices.push(1, -1);
  12976. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12977. var indices = [];
  12978. indices.push(0);
  12979. indices.push(1);
  12980. indices.push(2);
  12981. indices.push(0);
  12982. indices.push(2);
  12983. indices.push(3);
  12984. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12985. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  12986. }
  12987. Layer.prototype.render = function () {
  12988. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  12989. return;
  12990. var engine = this._scene.getEngine();
  12991. engine.enableEffect(this._effect);
  12992. engine.setState(false);
  12993. this._effect.setTexture("textureSampler", this.texture);
  12994. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  12995. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  12996. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12997. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12998. engine.draw(true, 0, 6);
  12999. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13000. };
  13001. Layer.prototype.dispose = function () {
  13002. if (this._vertexBuffer) {
  13003. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13004. this._vertexBuffer = null;
  13005. }
  13006. if (this._indexBuffer) {
  13007. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13008. this._indexBuffer = null;
  13009. }
  13010. if (this.texture) {
  13011. this.texture.dispose();
  13012. this.texture = null;
  13013. }
  13014. var index = this._scene.layers.indexOf(this);
  13015. this._scene.layers.splice(index, 1);
  13016. if (this.onDispose) {
  13017. this.onDispose();
  13018. }
  13019. };
  13020. return Layer;
  13021. })();
  13022. BABYLON.Layer = Layer;
  13023. })(BABYLON || (BABYLON = {}));
  13024. var BABYLON;
  13025. (function (BABYLON) {
  13026. var Particle = (function () {
  13027. function Particle() {
  13028. this.position = BABYLON.Vector3.Zero();
  13029. this.direction = BABYLON.Vector3.Zero();
  13030. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13031. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13032. this.lifeTime = 1.0;
  13033. this.age = 0;
  13034. this.size = 0;
  13035. this.angle = 0;
  13036. this.angularSpeed = 0;
  13037. }
  13038. return Particle;
  13039. })();
  13040. BABYLON.Particle = Particle;
  13041. })(BABYLON || (BABYLON = {}));
  13042. var BABYLON;
  13043. (function (BABYLON) {
  13044. var randomNumber = function (min, max) {
  13045. if (min == max) {
  13046. return (min);
  13047. }
  13048. var random = Math.random();
  13049. return ((random * (max - min)) + min);
  13050. };
  13051. var ParticleSystem = (function () {
  13052. function ParticleSystem(name, capacity, scene, customEffect) {
  13053. var _this = this;
  13054. this.name = name;
  13055. this.renderingGroupId = 0;
  13056. this.emitter = null;
  13057. this.emitRate = 10;
  13058. this.manualEmitCount = -1;
  13059. this.updateSpeed = 0.01;
  13060. this.targetStopDuration = 0;
  13061. this.disposeOnStop = false;
  13062. this.minEmitPower = 1;
  13063. this.maxEmitPower = 1;
  13064. this.minLifeTime = 1;
  13065. this.maxLifeTime = 1;
  13066. this.minSize = 1;
  13067. this.maxSize = 1;
  13068. this.minAngularSpeed = 0;
  13069. this.maxAngularSpeed = 0;
  13070. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  13071. this.forceDepthWrite = false;
  13072. this.gravity = BABYLON.Vector3.Zero();
  13073. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13074. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13075. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13076. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13077. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13078. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13079. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13080. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13081. this.particles = new Array();
  13082. this._vertexDeclaration = [3, 4, 4];
  13083. this._vertexStrideSize = 11 * 4;
  13084. this._stockParticles = new Array();
  13085. this._newPartsExcess = 0;
  13086. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13087. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13088. this._scaledDirection = BABYLON.Vector3.Zero();
  13089. this._scaledGravity = BABYLON.Vector3.Zero();
  13090. this._currentRenderId = -1;
  13091. this._started = false;
  13092. this._stopped = false;
  13093. this._actualFrame = 0;
  13094. this.id = name;
  13095. this._capacity = capacity;
  13096. this._scene = scene;
  13097. this._customEffect = customEffect;
  13098. scene.particleSystems.push(this);
  13099. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13100. var indices = [];
  13101. var index = 0;
  13102. for (var count = 0; count < capacity; count++) {
  13103. indices.push(index);
  13104. indices.push(index + 1);
  13105. indices.push(index + 2);
  13106. indices.push(index);
  13107. indices.push(index + 2);
  13108. indices.push(index + 3);
  13109. index += 4;
  13110. }
  13111. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13112. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13113. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13114. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13115. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13116. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13117. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13118. };
  13119. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13120. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13121. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13122. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13124. };
  13125. }
  13126. ParticleSystem.prototype.getCapacity = function () {
  13127. return this._capacity;
  13128. };
  13129. ParticleSystem.prototype.isAlive = function () {
  13130. return this._alive;
  13131. };
  13132. ParticleSystem.prototype.isStarted = function () {
  13133. return this._started;
  13134. };
  13135. ParticleSystem.prototype.start = function () {
  13136. this._started = true;
  13137. this._stopped = false;
  13138. this._actualFrame = 0;
  13139. };
  13140. ParticleSystem.prototype.stop = function () {
  13141. this._stopped = true;
  13142. };
  13143. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13144. var offset = index * 11;
  13145. this._vertices[offset] = particle.position.x;
  13146. this._vertices[offset + 1] = particle.position.y;
  13147. this._vertices[offset + 2] = particle.position.z;
  13148. this._vertices[offset + 3] = particle.color.r;
  13149. this._vertices[offset + 4] = particle.color.g;
  13150. this._vertices[offset + 5] = particle.color.b;
  13151. this._vertices[offset + 6] = particle.color.a;
  13152. this._vertices[offset + 7] = particle.angle;
  13153. this._vertices[offset + 8] = particle.size;
  13154. this._vertices[offset + 9] = offsetX;
  13155. this._vertices[offset + 10] = offsetY;
  13156. };
  13157. ParticleSystem.prototype._update = function (newParticles) {
  13158. this._alive = this.particles.length > 0;
  13159. for (var index = 0; index < this.particles.length; index++) {
  13160. var particle = this.particles[index];
  13161. particle.age += this._scaledUpdateSpeed;
  13162. if (particle.age >= particle.lifeTime) {
  13163. this._stockParticles.push(this.particles.splice(index, 1)[0]);
  13164. index--;
  13165. continue;
  13166. } else {
  13167. particle.colorStep.scaleToRef(this._scaledUpdateSpeed, this._scaledColorStep);
  13168. particle.color.addInPlace(this._scaledColorStep);
  13169. if (particle.color.a < 0)
  13170. particle.color.a = 0;
  13171. particle.angle += particle.angularSpeed * this._scaledUpdateSpeed;
  13172. particle.direction.scaleToRef(this._scaledUpdateSpeed, this._scaledDirection);
  13173. particle.position.addInPlace(this._scaledDirection);
  13174. this.gravity.scaleToRef(this._scaledUpdateSpeed, this._scaledGravity);
  13175. particle.direction.addInPlace(this._scaledGravity);
  13176. }
  13177. }
  13178. var worldMatrix;
  13179. if (this.emitter.position) {
  13180. worldMatrix = this.emitter.getWorldMatrix();
  13181. } else {
  13182. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13183. }
  13184. for (index = 0; index < newParticles; index++) {
  13185. if (this.particles.length == this._capacity) {
  13186. break;
  13187. }
  13188. if (this._stockParticles.length !== 0) {
  13189. particle = this._stockParticles.pop();
  13190. particle.age = 0;
  13191. } else {
  13192. particle = new BABYLON.Particle();
  13193. }
  13194. this.particles.push(particle);
  13195. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13196. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13197. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13198. particle.size = randomNumber(this.minSize, this.maxSize);
  13199. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13200. this.startPositionFunction(worldMatrix, particle.position);
  13201. var step = randomNumber(0, 1.0);
  13202. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13203. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13204. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13205. }
  13206. };
  13207. ParticleSystem.prototype._getEffect = function () {
  13208. if (this._customEffect) {
  13209. return this._customEffect;
  13210. }
  13211. ;
  13212. var defines = [];
  13213. if (this._scene.clipPlane) {
  13214. defines.push("#define CLIPPLANE");
  13215. }
  13216. var join = defines.join("\n");
  13217. if (this._cachedDefines != join) {
  13218. this._cachedDefines = join;
  13219. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13220. }
  13221. return this._effect;
  13222. };
  13223. ParticleSystem.prototype.animate = function () {
  13224. if (!this._started)
  13225. return;
  13226. var effect = this._getEffect();
  13227. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  13228. return;
  13229. if (this._currentRenderId === this._scene.getRenderId()) {
  13230. return;
  13231. }
  13232. this._currentRenderId = this._scene.getRenderId();
  13233. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  13234. var emitCout;
  13235. if (this.manualEmitCount > -1) {
  13236. emitCout = this.manualEmitCount;
  13237. this.manualEmitCount = 0;
  13238. } else {
  13239. emitCout = this.emitRate;
  13240. }
  13241. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  13242. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  13243. if (this._newPartsExcess > 1.0) {
  13244. newParticles += this._newPartsExcess >> 0;
  13245. this._newPartsExcess -= this._newPartsExcess >> 0;
  13246. }
  13247. this._alive = false;
  13248. if (!this._stopped) {
  13249. this._actualFrame += this._scaledUpdateSpeed;
  13250. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  13251. this.stop();
  13252. } else {
  13253. newParticles = 0;
  13254. }
  13255. this._update(newParticles);
  13256. if (this._stopped) {
  13257. if (!this._alive) {
  13258. this._started = false;
  13259. if (this.disposeOnStop) {
  13260. this._scene._toBeDisposed.push(this);
  13261. }
  13262. }
  13263. }
  13264. var offset = 0;
  13265. for (var index = 0; index < this.particles.length; index++) {
  13266. var particle = this.particles[index];
  13267. this._appendParticleVertex(offset++, particle, 0, 0);
  13268. this._appendParticleVertex(offset++, particle, 1, 0);
  13269. this._appendParticleVertex(offset++, particle, 1, 1);
  13270. this._appendParticleVertex(offset++, particle, 0, 1);
  13271. }
  13272. var engine = this._scene.getEngine();
  13273. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices, this.particles.length * this._vertexStrideSize);
  13274. };
  13275. ParticleSystem.prototype.render = function () {
  13276. var effect = this._getEffect();
  13277. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  13278. return 0;
  13279. var engine = this._scene.getEngine();
  13280. engine.enableEffect(effect);
  13281. engine.setState(false);
  13282. var viewMatrix = this._scene.getViewMatrix();
  13283. effect.setTexture("diffuseSampler", this.particleTexture);
  13284. effect.setMatrix("view", viewMatrix);
  13285. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13286. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  13287. if (this._scene.clipPlane) {
  13288. var clipPlane = this._scene.clipPlane;
  13289. var invView = viewMatrix.clone();
  13290. invView.invert();
  13291. effect.setMatrix("invView", invView);
  13292. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13293. }
  13294. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13295. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  13296. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13297. } else {
  13298. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13299. }
  13300. if (this.forceDepthWrite) {
  13301. engine.setDepthWrite(true);
  13302. }
  13303. engine.draw(true, 0, this.particles.length * 6);
  13304. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13305. return this.particles.length;
  13306. };
  13307. ParticleSystem.prototype.dispose = function () {
  13308. if (this._vertexBuffer) {
  13309. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13310. this._vertexBuffer = null;
  13311. }
  13312. if (this._indexBuffer) {
  13313. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13314. this._indexBuffer = null;
  13315. }
  13316. if (this.particleTexture) {
  13317. this.particleTexture.dispose();
  13318. this.particleTexture = null;
  13319. }
  13320. var index = this._scene.particleSystems.indexOf(this);
  13321. this._scene.particleSystems.splice(index, 1);
  13322. if (this.onDispose) {
  13323. this.onDispose();
  13324. }
  13325. };
  13326. ParticleSystem.prototype.clone = function (name, newEmitter) {
  13327. var result = new BABYLON.ParticleSystem(name, this._capacity, this._scene);
  13328. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  13329. if (newEmitter === undefined) {
  13330. newEmitter = this.emitter;
  13331. }
  13332. result.emitter = newEmitter;
  13333. if (this.particleTexture) {
  13334. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  13335. }
  13336. result.start();
  13337. return result;
  13338. };
  13339. ParticleSystem.BLENDMODE_ONEONE = 0;
  13340. ParticleSystem.BLENDMODE_STANDARD = 1;
  13341. return ParticleSystem;
  13342. })();
  13343. BABYLON.ParticleSystem = ParticleSystem;
  13344. })(BABYLON || (BABYLON = {}));
  13345. var BABYLON;
  13346. (function (BABYLON) {
  13347. var Animation = (function () {
  13348. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  13349. this.name = name;
  13350. this.targetProperty = targetProperty;
  13351. this.framePerSecond = framePerSecond;
  13352. this.dataType = dataType;
  13353. this.loopMode = loopMode;
  13354. this._offsetsCache = {};
  13355. this._highLimitsCache = {};
  13356. this._stopped = false;
  13357. this.targetPropertyPath = targetProperty.split(".");
  13358. this.dataType = dataType;
  13359. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  13360. }
  13361. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  13362. var dataType = undefined;
  13363. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  13364. dataType = Animation.ANIMATIONTYPE_FLOAT;
  13365. } else if (from instanceof BABYLON.Quaternion) {
  13366. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  13367. } else if (from instanceof BABYLON.Vector3) {
  13368. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  13369. } else if (from instanceof BABYLON.Vector2) {
  13370. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  13371. } else if (from instanceof BABYLON.Color3) {
  13372. dataType = Animation.ANIMATIONTYPE_COLOR3;
  13373. }
  13374. if (dataType == undefined) {
  13375. return;
  13376. }
  13377. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  13378. var keys = [];
  13379. keys.push({ frame: 0, value: from });
  13380. keys.push({ frame: totalFrame, value: to });
  13381. animation.setKeys(keys);
  13382. mesh.animations.push(animation);
  13383. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  13384. };
  13385. Animation.prototype.isStopped = function () {
  13386. return this._stopped;
  13387. };
  13388. Animation.prototype.getKeys = function () {
  13389. return this._keys;
  13390. };
  13391. Animation.prototype.getEasingFunction = function () {
  13392. return this._easingFunction;
  13393. };
  13394. Animation.prototype.setEasingFunction = function (easingFunction) {
  13395. this._easingFunction = easingFunction;
  13396. };
  13397. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  13398. return startValue + (endValue - startValue) * gradient;
  13399. };
  13400. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  13401. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  13402. };
  13403. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  13404. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  13405. };
  13406. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  13407. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  13408. };
  13409. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  13410. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  13411. };
  13412. Animation.prototype.clone = function () {
  13413. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  13414. clone.setKeys(this._keys);
  13415. return clone;
  13416. };
  13417. Animation.prototype.setKeys = function (values) {
  13418. this._keys = values.slice(0);
  13419. this._offsetsCache = {};
  13420. this._highLimitsCache = {};
  13421. };
  13422. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  13423. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  13424. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  13425. }
  13426. this.currentFrame = currentFrame;
  13427. for (var key = 0; key < this._keys.length; key++) {
  13428. if (this._keys[key + 1].frame >= currentFrame) {
  13429. var startValue = this._keys[key].value;
  13430. var endValue = this._keys[key + 1].value;
  13431. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  13432. if (this._easingFunction != null) {
  13433. gradient = this._easingFunction.ease(gradient);
  13434. }
  13435. switch (this.dataType) {
  13436. case Animation.ANIMATIONTYPE_FLOAT:
  13437. switch (loopMode) {
  13438. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13439. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13440. return this.floatInterpolateFunction(startValue, endValue, gradient);
  13441. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13442. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  13443. }
  13444. break;
  13445. case Animation.ANIMATIONTYPE_QUATERNION:
  13446. var quaternion = null;
  13447. switch (loopMode) {
  13448. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13449. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13450. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  13451. break;
  13452. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13453. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13454. break;
  13455. }
  13456. return quaternion;
  13457. case Animation.ANIMATIONTYPE_VECTOR3:
  13458. switch (loopMode) {
  13459. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13460. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13461. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  13462. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13463. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13464. }
  13465. case Animation.ANIMATIONTYPE_VECTOR2:
  13466. switch (loopMode) {
  13467. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13468. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13469. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  13470. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13471. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13472. }
  13473. case Animation.ANIMATIONTYPE_COLOR3:
  13474. switch (loopMode) {
  13475. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13476. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13477. return this.color3InterpolateFunction(startValue, endValue, gradient);
  13478. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13479. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  13480. }
  13481. case Animation.ANIMATIONTYPE_MATRIX:
  13482. switch (loopMode) {
  13483. case Animation.ANIMATIONLOOPMODE_CYCLE:
  13484. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  13485. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  13486. return startValue;
  13487. }
  13488. default:
  13489. break;
  13490. }
  13491. break;
  13492. }
  13493. }
  13494. return this._keys[this._keys.length - 1].value;
  13495. };
  13496. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  13497. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  13498. this._stopped = true;
  13499. return false;
  13500. }
  13501. var returnValue = true;
  13502. if (this._keys[0].frame != 0) {
  13503. var newKey = { frame: 0, value: this._keys[0].value };
  13504. this._keys.splice(0, 0, newKey);
  13505. }
  13506. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  13507. from = this._keys[0].frame;
  13508. }
  13509. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  13510. to = this._keys[this._keys.length - 1].frame;
  13511. }
  13512. var range = to - from;
  13513. var offsetValue;
  13514. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  13515. if (ratio > range && !loop) {
  13516. returnValue = false;
  13517. highLimitValue = this._keys[this._keys.length - 1].value;
  13518. } else {
  13519. var highLimitValue = 0;
  13520. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  13521. var keyOffset = to.toString() + from.toString();
  13522. if (!this._offsetsCache[keyOffset]) {
  13523. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13524. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  13525. switch (this.dataType) {
  13526. case Animation.ANIMATIONTYPE_FLOAT:
  13527. this._offsetsCache[keyOffset] = toValue - fromValue;
  13528. break;
  13529. case Animation.ANIMATIONTYPE_QUATERNION:
  13530. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13531. break;
  13532. case Animation.ANIMATIONTYPE_VECTOR3:
  13533. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13534. case Animation.ANIMATIONTYPE_VECTOR2:
  13535. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13536. case Animation.ANIMATIONTYPE_COLOR3:
  13537. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  13538. default:
  13539. break;
  13540. }
  13541. this._highLimitsCache[keyOffset] = toValue;
  13542. }
  13543. highLimitValue = this._highLimitsCache[keyOffset];
  13544. offsetValue = this._offsetsCache[keyOffset];
  13545. }
  13546. }
  13547. if (offsetValue === undefined) {
  13548. switch (this.dataType) {
  13549. case Animation.ANIMATIONTYPE_FLOAT:
  13550. offsetValue = 0;
  13551. break;
  13552. case Animation.ANIMATIONTYPE_QUATERNION:
  13553. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  13554. break;
  13555. case Animation.ANIMATIONTYPE_VECTOR3:
  13556. offsetValue = BABYLON.Vector3.Zero();
  13557. break;
  13558. case Animation.ANIMATIONTYPE_VECTOR2:
  13559. offsetValue = BABYLON.Vector2.Zero();
  13560. break;
  13561. case Animation.ANIMATIONTYPE_COLOR3:
  13562. offsetValue = BABYLON.Color3.Black();
  13563. }
  13564. }
  13565. var repeatCount = (ratio / range) >> 0;
  13566. var currentFrame = returnValue ? from + ratio % range : to;
  13567. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  13568. if (this.targetPropertyPath.length > 1) {
  13569. var property = this._target[this.targetPropertyPath[0]];
  13570. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  13571. property = property[this.targetPropertyPath[index]];
  13572. }
  13573. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  13574. } else {
  13575. this._target[this.targetPropertyPath[0]] = currentValue;
  13576. }
  13577. if (this._target.markAsDirty) {
  13578. this._target.markAsDirty(this.targetProperty);
  13579. }
  13580. if (!returnValue) {
  13581. this._stopped = true;
  13582. }
  13583. return returnValue;
  13584. };
  13585. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  13586. get: function () {
  13587. return Animation._ANIMATIONTYPE_FLOAT;
  13588. },
  13589. enumerable: true,
  13590. configurable: true
  13591. });
  13592. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  13593. get: function () {
  13594. return Animation._ANIMATIONTYPE_VECTOR3;
  13595. },
  13596. enumerable: true,
  13597. configurable: true
  13598. });
  13599. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  13600. get: function () {
  13601. return Animation._ANIMATIONTYPE_VECTOR2;
  13602. },
  13603. enumerable: true,
  13604. configurable: true
  13605. });
  13606. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  13607. get: function () {
  13608. return Animation._ANIMATIONTYPE_QUATERNION;
  13609. },
  13610. enumerable: true,
  13611. configurable: true
  13612. });
  13613. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  13614. get: function () {
  13615. return Animation._ANIMATIONTYPE_MATRIX;
  13616. },
  13617. enumerable: true,
  13618. configurable: true
  13619. });
  13620. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  13621. get: function () {
  13622. return Animation._ANIMATIONTYPE_COLOR3;
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  13628. get: function () {
  13629. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  13635. get: function () {
  13636. return Animation._ANIMATIONLOOPMODE_CYCLE;
  13637. },
  13638. enumerable: true,
  13639. configurable: true
  13640. });
  13641. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  13642. get: function () {
  13643. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  13644. },
  13645. enumerable: true,
  13646. configurable: true
  13647. });
  13648. Animation._ANIMATIONTYPE_FLOAT = 0;
  13649. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  13650. Animation._ANIMATIONTYPE_QUATERNION = 2;
  13651. Animation._ANIMATIONTYPE_MATRIX = 3;
  13652. Animation._ANIMATIONTYPE_COLOR3 = 4;
  13653. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  13654. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  13655. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  13656. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  13657. return Animation;
  13658. })();
  13659. BABYLON.Animation = Animation;
  13660. })(BABYLON || (BABYLON = {}));
  13661. var BABYLON;
  13662. (function (BABYLON) {
  13663. var Animatable = (function () {
  13664. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  13665. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  13666. if (typeof toFrame === "undefined") { toFrame = 100; }
  13667. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  13668. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  13669. this.target = target;
  13670. this.fromFrame = fromFrame;
  13671. this.toFrame = toFrame;
  13672. this.loopAnimation = loopAnimation;
  13673. this.speedRatio = speedRatio;
  13674. this.onAnimationEnd = onAnimationEnd;
  13675. this._animations = new Array();
  13676. this._paused = false;
  13677. this.animationStarted = false;
  13678. if (animations) {
  13679. this.appendAnimations(target, animations);
  13680. }
  13681. this._scene = scene;
  13682. scene._activeAnimatables.push(this);
  13683. }
  13684. Animatable.prototype.appendAnimations = function (target, animations) {
  13685. for (var index = 0; index < animations.length; index++) {
  13686. var animation = animations[index];
  13687. animation._target = target;
  13688. this._animations.push(animation);
  13689. }
  13690. };
  13691. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  13692. var animations = this._animations;
  13693. for (var index = 0; index < animations.length; index++) {
  13694. if (animations[index].targetProperty === property) {
  13695. return animations[index];
  13696. }
  13697. }
  13698. return null;
  13699. };
  13700. Animatable.prototype.pause = function () {
  13701. if (this._paused) {
  13702. return;
  13703. }
  13704. this._paused = true;
  13705. };
  13706. Animatable.prototype.restart = function () {
  13707. this._paused = false;
  13708. };
  13709. Animatable.prototype.stop = function () {
  13710. var index = this._scene._activeAnimatables.indexOf(this);
  13711. if (index > -1) {
  13712. this._scene._activeAnimatables.splice(index, 1);
  13713. }
  13714. if (this.onAnimationEnd) {
  13715. this.onAnimationEnd();
  13716. }
  13717. };
  13718. Animatable.prototype._animate = function (delay) {
  13719. if (this._paused) {
  13720. if (!this._pausedDelay) {
  13721. this._pausedDelay = delay;
  13722. }
  13723. return true;
  13724. }
  13725. if (!this._localDelayOffset) {
  13726. this._localDelayOffset = delay;
  13727. } else if (this._pausedDelay) {
  13728. this._localDelayOffset += delay - this._pausedDelay;
  13729. this._pausedDelay = null;
  13730. }
  13731. var running = false;
  13732. var animations = this._animations;
  13733. for (var index = 0; index < animations.length; index++) {
  13734. var animation = animations[index];
  13735. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  13736. running = running || isRunning;
  13737. }
  13738. if (!running && this.onAnimationEnd) {
  13739. this.onAnimationEnd();
  13740. }
  13741. return running;
  13742. };
  13743. return Animatable;
  13744. })();
  13745. BABYLON.Animatable = Animatable;
  13746. })(BABYLON || (BABYLON = {}));
  13747. var __extends = this.__extends || function (d, b) {
  13748. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13749. function __() { this.constructor = d; }
  13750. __.prototype = b.prototype;
  13751. d.prototype = new __();
  13752. };
  13753. var BABYLON;
  13754. (function (BABYLON) {
  13755. var EasingFunction = (function () {
  13756. function EasingFunction() {
  13757. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  13758. }
  13759. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  13760. get: function () {
  13761. return EasingFunction._EASINGMODE_EASEIN;
  13762. },
  13763. enumerable: true,
  13764. configurable: true
  13765. });
  13766. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  13767. get: function () {
  13768. return EasingFunction._EASINGMODE_EASEOUT;
  13769. },
  13770. enumerable: true,
  13771. configurable: true
  13772. });
  13773. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  13774. get: function () {
  13775. return EasingFunction._EASINGMODE_EASEINOUT;
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. EasingFunction.prototype.setEasingMode = function (easingMode) {
  13781. var n = Math.min(Math.max(easingMode, 0), 2);
  13782. this._easingMode = n;
  13783. };
  13784. EasingFunction.prototype.getEasingMode = function () {
  13785. return this._easingMode;
  13786. };
  13787. EasingFunction.prototype.easeInCore = function (gradient) {
  13788. throw new Error('You must implement this method');
  13789. };
  13790. EasingFunction.prototype.ease = function (gradient) {
  13791. switch (this._easingMode) {
  13792. case EasingFunction.EASINGMODE_EASEIN:
  13793. return this.easeInCore(gradient);
  13794. case EasingFunction.EASINGMODE_EASEOUT:
  13795. return (1 - this.easeInCore(1 - gradient));
  13796. }
  13797. if (gradient >= 0.5) {
  13798. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  13799. }
  13800. return (this.easeInCore(gradient * 2) * 0.5);
  13801. };
  13802. EasingFunction._EASINGMODE_EASEIN = 0;
  13803. EasingFunction._EASINGMODE_EASEOUT = 1;
  13804. EasingFunction._EASINGMODE_EASEINOUT = 2;
  13805. return EasingFunction;
  13806. })();
  13807. BABYLON.EasingFunction = EasingFunction;
  13808. var CircleEase = (function (_super) {
  13809. __extends(CircleEase, _super);
  13810. function CircleEase() {
  13811. _super.apply(this, arguments);
  13812. }
  13813. CircleEase.prototype.easeInCore = function (gradient) {
  13814. gradient = Math.max(0, Math.min(1, gradient));
  13815. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  13816. };
  13817. return CircleEase;
  13818. })(EasingFunction);
  13819. BABYLON.CircleEase = CircleEase;
  13820. var BackEase = (function (_super) {
  13821. __extends(BackEase, _super);
  13822. function BackEase(amplitude) {
  13823. if (typeof amplitude === "undefined") { amplitude = 1; }
  13824. _super.call(this);
  13825. this.amplitude = amplitude;
  13826. }
  13827. BackEase.prototype.easeInCore = function (gradient) {
  13828. var num = Math.max(0, this.amplitude);
  13829. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  13830. };
  13831. return BackEase;
  13832. })(EasingFunction);
  13833. BABYLON.BackEase = BackEase;
  13834. var BounceEase = (function (_super) {
  13835. __extends(BounceEase, _super);
  13836. function BounceEase(bounces, bounciness) {
  13837. if (typeof bounces === "undefined") { bounces = 3; }
  13838. if (typeof bounciness === "undefined") { bounciness = 2; }
  13839. _super.call(this);
  13840. this.bounces = bounces;
  13841. this.bounciness = bounciness;
  13842. }
  13843. BounceEase.prototype.easeInCore = function (gradient) {
  13844. var y = Math.max(0.0, this.bounces);
  13845. var bounciness = this.bounciness;
  13846. if (bounciness <= 1.0) {
  13847. bounciness = 1.001;
  13848. }
  13849. var num9 = Math.pow(bounciness, y);
  13850. var num5 = 1.0 - bounciness;
  13851. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  13852. var num15 = gradient * num4;
  13853. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  13854. var num3 = Math.floor(num65);
  13855. var num13 = num3 + 1.0;
  13856. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  13857. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  13858. var num7 = (num8 + num12) * 0.5;
  13859. var num6 = gradient - num7;
  13860. var num2 = num7 - num8;
  13861. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  13862. };
  13863. return BounceEase;
  13864. })(EasingFunction);
  13865. BABYLON.BounceEase = BounceEase;
  13866. var CubicEase = (function (_super) {
  13867. __extends(CubicEase, _super);
  13868. function CubicEase() {
  13869. _super.apply(this, arguments);
  13870. }
  13871. CubicEase.prototype.easeInCore = function (gradient) {
  13872. return (gradient * gradient * gradient);
  13873. };
  13874. return CubicEase;
  13875. })(EasingFunction);
  13876. BABYLON.CubicEase = CubicEase;
  13877. var ElasticEase = (function (_super) {
  13878. __extends(ElasticEase, _super);
  13879. function ElasticEase(oscillations, springiness) {
  13880. if (typeof oscillations === "undefined") { oscillations = 3; }
  13881. if (typeof springiness === "undefined") { springiness = 3; }
  13882. _super.call(this);
  13883. this.oscillations = oscillations;
  13884. this.springiness = springiness;
  13885. }
  13886. ElasticEase.prototype.easeInCore = function (gradient) {
  13887. var num2;
  13888. var num3 = Math.max(0.0, this.oscillations);
  13889. var num = Math.max(0.0, this.springiness);
  13890. if (num == 0) {
  13891. num2 = gradient;
  13892. } else {
  13893. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  13894. }
  13895. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  13896. };
  13897. return ElasticEase;
  13898. })(EasingFunction);
  13899. BABYLON.ElasticEase = ElasticEase;
  13900. var ExponentialEase = (function (_super) {
  13901. __extends(ExponentialEase, _super);
  13902. function ExponentialEase(exponent) {
  13903. if (typeof exponent === "undefined") { exponent = 2; }
  13904. _super.call(this);
  13905. this.exponent = exponent;
  13906. }
  13907. ExponentialEase.prototype.easeInCore = function (gradient) {
  13908. if (this.exponent <= 0) {
  13909. return gradient;
  13910. }
  13911. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  13912. };
  13913. return ExponentialEase;
  13914. })(EasingFunction);
  13915. BABYLON.ExponentialEase = ExponentialEase;
  13916. var PowerEase = (function (_super) {
  13917. __extends(PowerEase, _super);
  13918. function PowerEase(power) {
  13919. if (typeof power === "undefined") { power = 2; }
  13920. _super.call(this);
  13921. this.power = power;
  13922. }
  13923. PowerEase.prototype.easeInCore = function (gradient) {
  13924. var y = Math.max(0.0, this.power);
  13925. return Math.pow(gradient, y);
  13926. };
  13927. return PowerEase;
  13928. })(EasingFunction);
  13929. BABYLON.PowerEase = PowerEase;
  13930. var QuadraticEase = (function (_super) {
  13931. __extends(QuadraticEase, _super);
  13932. function QuadraticEase() {
  13933. _super.apply(this, arguments);
  13934. }
  13935. QuadraticEase.prototype.easeInCore = function (gradient) {
  13936. return (gradient * gradient);
  13937. };
  13938. return QuadraticEase;
  13939. })(EasingFunction);
  13940. BABYLON.QuadraticEase = QuadraticEase;
  13941. var QuarticEase = (function (_super) {
  13942. __extends(QuarticEase, _super);
  13943. function QuarticEase() {
  13944. _super.apply(this, arguments);
  13945. }
  13946. QuarticEase.prototype.easeInCore = function (gradient) {
  13947. return (gradient * gradient * gradient * gradient);
  13948. };
  13949. return QuarticEase;
  13950. })(EasingFunction);
  13951. BABYLON.QuarticEase = QuarticEase;
  13952. var QuinticEase = (function (_super) {
  13953. __extends(QuinticEase, _super);
  13954. function QuinticEase() {
  13955. _super.apply(this, arguments);
  13956. }
  13957. QuinticEase.prototype.easeInCore = function (gradient) {
  13958. return (gradient * gradient * gradient * gradient * gradient);
  13959. };
  13960. return QuinticEase;
  13961. })(EasingFunction);
  13962. BABYLON.QuinticEase = QuinticEase;
  13963. var SineEase = (function (_super) {
  13964. __extends(SineEase, _super);
  13965. function SineEase() {
  13966. _super.apply(this, arguments);
  13967. }
  13968. SineEase.prototype.easeInCore = function (gradient) {
  13969. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  13970. };
  13971. return SineEase;
  13972. })(EasingFunction);
  13973. BABYLON.SineEase = SineEase;
  13974. var BezierCurveEase = (function (_super) {
  13975. __extends(BezierCurveEase, _super);
  13976. function BezierCurveEase(x1, y1, x2, y2) {
  13977. if (typeof x1 === "undefined") { x1 = 0; }
  13978. if (typeof y1 === "undefined") { y1 = 0; }
  13979. if (typeof x2 === "undefined") { x2 = 1; }
  13980. if (typeof y2 === "undefined") { y2 = 1; }
  13981. _super.call(this);
  13982. this.x1 = x1;
  13983. this.y1 = y1;
  13984. this.x2 = x2;
  13985. this.y2 = y2;
  13986. }
  13987. BezierCurveEase.prototype.easeInCore = function (gradient) {
  13988. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  13989. };
  13990. return BezierCurveEase;
  13991. })(EasingFunction);
  13992. BABYLON.BezierCurveEase = BezierCurveEase;
  13993. })(BABYLON || (BABYLON = {}));
  13994. var BABYLON;
  13995. (function (BABYLON) {
  13996. var Octree = (function () {
  13997. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  13998. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  13999. this.maxDepth = maxDepth;
  14000. this.dynamicContent = new Array();
  14001. this._maxBlockCapacity = maxBlockCapacity || 64;
  14002. this._selectionContent = new BABYLON.SmartArray(1024);
  14003. this._creationFunc = creationFunc;
  14004. }
  14005. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14006. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14007. };
  14008. Octree.prototype.addMesh = function (entry) {
  14009. for (var index = 0; index < this.blocks.length; index++) {
  14010. var block = this.blocks[index];
  14011. block.addEntry(entry);
  14012. }
  14013. };
  14014. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14015. this._selectionContent.reset();
  14016. for (var index = 0; index < this.blocks.length; index++) {
  14017. var block = this.blocks[index];
  14018. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14019. }
  14020. if (allowDuplicate) {
  14021. this._selectionContent.concat(this.dynamicContent);
  14022. } else {
  14023. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14024. }
  14025. return this._selectionContent;
  14026. };
  14027. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14028. this._selectionContent.reset();
  14029. for (var index = 0; index < this.blocks.length; index++) {
  14030. var block = this.blocks[index];
  14031. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14032. }
  14033. if (allowDuplicate) {
  14034. this._selectionContent.concat(this.dynamicContent);
  14035. } else {
  14036. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14037. }
  14038. return this._selectionContent;
  14039. };
  14040. Octree.prototype.intersectsRay = function (ray) {
  14041. this._selectionContent.reset();
  14042. for (var index = 0; index < this.blocks.length; index++) {
  14043. var block = this.blocks[index];
  14044. block.intersectsRay(ray, this._selectionContent);
  14045. }
  14046. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14047. return this._selectionContent;
  14048. };
  14049. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14050. target.blocks = new Array();
  14051. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14052. for (var x = 0; x < 2; x++) {
  14053. for (var y = 0; y < 2; y++) {
  14054. for (var z = 0; z < 2; z++) {
  14055. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14056. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14057. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14058. block.addEntries(entries);
  14059. target.blocks.push(block);
  14060. }
  14061. }
  14062. }
  14063. };
  14064. Octree.CreationFuncForMeshes = function (entry, block) {
  14065. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14066. block.entries.push(entry);
  14067. }
  14068. };
  14069. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14070. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14071. block.entries.push(entry);
  14072. }
  14073. };
  14074. return Octree;
  14075. })();
  14076. BABYLON.Octree = Octree;
  14077. })(BABYLON || (BABYLON = {}));
  14078. var BABYLON;
  14079. (function (BABYLON) {
  14080. var OctreeBlock = (function () {
  14081. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14082. this.entries = new Array();
  14083. this._boundingVectors = new Array();
  14084. this._capacity = capacity;
  14085. this._depth = depth;
  14086. this._maxDepth = maxDepth;
  14087. this._creationFunc = creationFunc;
  14088. this._minPoint = minPoint;
  14089. this._maxPoint = maxPoint;
  14090. this._boundingVectors.push(minPoint.clone());
  14091. this._boundingVectors.push(maxPoint.clone());
  14092. this._boundingVectors.push(minPoint.clone());
  14093. this._boundingVectors[2].x = maxPoint.x;
  14094. this._boundingVectors.push(minPoint.clone());
  14095. this._boundingVectors[3].y = maxPoint.y;
  14096. this._boundingVectors.push(minPoint.clone());
  14097. this._boundingVectors[4].z = maxPoint.z;
  14098. this._boundingVectors.push(maxPoint.clone());
  14099. this._boundingVectors[5].z = minPoint.z;
  14100. this._boundingVectors.push(maxPoint.clone());
  14101. this._boundingVectors[6].x = minPoint.x;
  14102. this._boundingVectors.push(maxPoint.clone());
  14103. this._boundingVectors[7].y = minPoint.y;
  14104. }
  14105. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14106. get: function () {
  14107. return this._capacity;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14113. get: function () {
  14114. return this._minPoint;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14120. get: function () {
  14121. return this._maxPoint;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. OctreeBlock.prototype.addEntry = function (entry) {
  14127. if (this.blocks) {
  14128. for (var index = 0; index < this.blocks.length; index++) {
  14129. var block = this.blocks[index];
  14130. block.addEntry(entry);
  14131. }
  14132. return;
  14133. }
  14134. this._creationFunc(entry, this);
  14135. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14136. this.createInnerBlocks();
  14137. }
  14138. };
  14139. OctreeBlock.prototype.addEntries = function (entries) {
  14140. for (var index = 0; index < entries.length; index++) {
  14141. var mesh = entries[index];
  14142. this.addEntry(mesh);
  14143. }
  14144. };
  14145. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14146. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14147. if (this.blocks) {
  14148. for (var index = 0; index < this.blocks.length; index++) {
  14149. var block = this.blocks[index];
  14150. block.select(frustumPlanes, selection, allowDuplicate);
  14151. }
  14152. return;
  14153. }
  14154. if (allowDuplicate) {
  14155. selection.concat(this.entries);
  14156. } else {
  14157. selection.concatWithNoDuplicate(this.entries);
  14158. }
  14159. }
  14160. };
  14161. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14162. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14163. if (this.blocks) {
  14164. for (var index = 0; index < this.blocks.length; index++) {
  14165. var block = this.blocks[index];
  14166. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14167. }
  14168. return;
  14169. }
  14170. if (allowDuplicate) {
  14171. selection.concat(this.entries);
  14172. } else {
  14173. selection.concatWithNoDuplicate(this.entries);
  14174. }
  14175. }
  14176. };
  14177. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14178. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14179. if (this.blocks) {
  14180. for (var index = 0; index < this.blocks.length; index++) {
  14181. var block = this.blocks[index];
  14182. block.intersectsRay(ray, selection);
  14183. }
  14184. return;
  14185. }
  14186. selection.concatWithNoDuplicate(this.entries);
  14187. }
  14188. };
  14189. OctreeBlock.prototype.createInnerBlocks = function () {
  14190. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  14191. };
  14192. return OctreeBlock;
  14193. })();
  14194. BABYLON.OctreeBlock = OctreeBlock;
  14195. })(BABYLON || (BABYLON = {}));
  14196. var BABYLON;
  14197. (function (BABYLON) {
  14198. var Bone = (function () {
  14199. function Bone(name, skeleton, parentBone, matrix) {
  14200. this.name = name;
  14201. this.children = new Array();
  14202. this.animations = new Array();
  14203. this._worldTransform = new BABYLON.Matrix();
  14204. this._absoluteTransform = new BABYLON.Matrix();
  14205. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  14206. this._skeleton = skeleton;
  14207. this._matrix = matrix;
  14208. this._baseMatrix = matrix;
  14209. skeleton.bones.push(this);
  14210. if (parentBone) {
  14211. this._parent = parentBone;
  14212. parentBone.children.push(this);
  14213. } else {
  14214. this._parent = null;
  14215. }
  14216. this._updateDifferenceMatrix();
  14217. }
  14218. Bone.prototype.getParent = function () {
  14219. return this._parent;
  14220. };
  14221. Bone.prototype.getLocalMatrix = function () {
  14222. return this._matrix;
  14223. };
  14224. Bone.prototype.getBaseMatrix = function () {
  14225. return this._baseMatrix;
  14226. };
  14227. Bone.prototype.getWorldMatrix = function () {
  14228. return this._worldTransform;
  14229. };
  14230. Bone.prototype.getInvertedAbsoluteTransform = function () {
  14231. return this._invertedAbsoluteTransform;
  14232. };
  14233. Bone.prototype.getAbsoluteMatrix = function () {
  14234. var matrix = this._matrix.clone();
  14235. var parent = this._parent;
  14236. while (parent) {
  14237. matrix = matrix.multiply(parent.getLocalMatrix());
  14238. parent = parent.getParent();
  14239. }
  14240. return matrix;
  14241. };
  14242. Bone.prototype.updateMatrix = function (matrix) {
  14243. this._matrix = matrix;
  14244. this._skeleton._markAsDirty();
  14245. this._updateDifferenceMatrix();
  14246. };
  14247. Bone.prototype._updateDifferenceMatrix = function () {
  14248. if (this._parent) {
  14249. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  14250. } else {
  14251. this._absoluteTransform.copyFrom(this._matrix);
  14252. }
  14253. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  14254. for (var index = 0; index < this.children.length; index++) {
  14255. this.children[index]._updateDifferenceMatrix();
  14256. }
  14257. };
  14258. Bone.prototype.markAsDirty = function () {
  14259. this._skeleton._markAsDirty();
  14260. };
  14261. return Bone;
  14262. })();
  14263. BABYLON.Bone = Bone;
  14264. })(BABYLON || (BABYLON = {}));
  14265. var BABYLON;
  14266. (function (BABYLON) {
  14267. var Skeleton = (function () {
  14268. function Skeleton(name, id, scene) {
  14269. this.name = name;
  14270. this.id = id;
  14271. this.bones = new Array();
  14272. this._isDirty = true;
  14273. this._identity = BABYLON.Matrix.Identity();
  14274. this.bones = [];
  14275. this._scene = scene;
  14276. scene.skeletons.push(this);
  14277. }
  14278. Skeleton.prototype.getTransformMatrices = function () {
  14279. return this._transformMatrices;
  14280. };
  14281. Skeleton.prototype._markAsDirty = function () {
  14282. this._isDirty = true;
  14283. };
  14284. Skeleton.prototype.prepare = function () {
  14285. if (!this._isDirty) {
  14286. return;
  14287. }
  14288. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  14289. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  14290. }
  14291. for (var index = 0; index < this.bones.length; index++) {
  14292. var bone = this.bones[index];
  14293. var parentBone = bone.getParent();
  14294. if (parentBone) {
  14295. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  14296. } else {
  14297. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  14298. }
  14299. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  14300. }
  14301. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  14302. this._isDirty = false;
  14303. };
  14304. Skeleton.prototype.getAnimatables = function () {
  14305. if (!this._animatables || this._animatables.length != this.bones.length) {
  14306. this._animatables = [];
  14307. for (var index = 0; index < this.bones.length; index++) {
  14308. this._animatables.push(this.bones[index]);
  14309. }
  14310. }
  14311. return this._animatables;
  14312. };
  14313. Skeleton.prototype.clone = function (name, id) {
  14314. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  14315. for (var index = 0; index < this.bones.length; index++) {
  14316. var source = this.bones[index];
  14317. var parentBone = null;
  14318. if (source.getParent()) {
  14319. var parentIndex = this.bones.indexOf(source.getParent());
  14320. parentBone = result.bones[parentIndex];
  14321. }
  14322. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  14323. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  14324. }
  14325. return result;
  14326. };
  14327. return Skeleton;
  14328. })();
  14329. BABYLON.Skeleton = Skeleton;
  14330. })(BABYLON || (BABYLON = {}));
  14331. var BABYLON;
  14332. (function (BABYLON) {
  14333. var PostProcess = (function () {
  14334. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  14335. this.name = name;
  14336. this.width = -1;
  14337. this.height = -1;
  14338. this._reusable = false;
  14339. this._textures = new BABYLON.SmartArray(2);
  14340. this._currentRenderTextureInd = 0;
  14341. if (camera != null) {
  14342. this._camera = camera;
  14343. this._scene = camera.getScene();
  14344. camera.attachPostProcess(this);
  14345. this._engine = this._scene.getEngine();
  14346. } else {
  14347. this._engine = engine;
  14348. }
  14349. this._renderRatio = ratio;
  14350. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14351. this._reusable = reusable || false;
  14352. samplers = samplers || [];
  14353. samplers.push("textureSampler");
  14354. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  14355. }
  14356. PostProcess.prototype.isReusable = function () {
  14357. return this._reusable;
  14358. };
  14359. PostProcess.prototype.activate = function (camera, sourceTexture) {
  14360. camera = camera || this._camera;
  14361. var scene = camera.getScene();
  14362. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  14363. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  14364. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  14365. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  14366. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  14367. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  14368. if (this._textures.length > 0) {
  14369. for (var i = 0; i < this._textures.length; i++) {
  14370. this._engine._releaseTexture(this._textures.data[i]);
  14371. }
  14372. this._textures.reset();
  14373. }
  14374. this.width = desiredWidth;
  14375. this.height = desiredHeight;
  14376. 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 }));
  14377. if (this._reusable) {
  14378. 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 }));
  14379. }
  14380. if (this.onSizeChanged) {
  14381. this.onSizeChanged();
  14382. }
  14383. }
  14384. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  14385. if (this.onActivate) {
  14386. this.onActivate(camera);
  14387. }
  14388. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  14389. if (this._reusable) {
  14390. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  14391. }
  14392. };
  14393. PostProcess.prototype.apply = function () {
  14394. if (!this._effect.isReady())
  14395. return null;
  14396. this._engine.enableEffect(this._effect);
  14397. this._engine.setState(false);
  14398. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14399. this._engine.setDepthBuffer(false);
  14400. this._engine.setDepthWrite(false);
  14401. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  14402. if (this.onApply) {
  14403. this.onApply(this._effect);
  14404. }
  14405. return this._effect;
  14406. };
  14407. PostProcess.prototype.dispose = function (camera) {
  14408. camera = camera || this._camera;
  14409. if (this._textures.length > 0) {
  14410. for (var i = 0; i < this._textures.length; i++) {
  14411. this._engine._releaseTexture(this._textures.data[i]);
  14412. }
  14413. this._textures.reset();
  14414. }
  14415. camera.detachPostProcess(this);
  14416. var index = camera._postProcesses.indexOf(this);
  14417. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  14418. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1;
  14419. }
  14420. };
  14421. return PostProcess;
  14422. })();
  14423. BABYLON.PostProcess = PostProcess;
  14424. })(BABYLON || (BABYLON = {}));
  14425. var BABYLON;
  14426. (function (BABYLON) {
  14427. var PostProcessManager = (function () {
  14428. function PostProcessManager(scene) {
  14429. this._vertexDeclaration = [2];
  14430. this._vertexStrideSize = 2 * 4;
  14431. this._scene = scene;
  14432. var vertices = [];
  14433. vertices.push(1, 1);
  14434. vertices.push(-1, 1);
  14435. vertices.push(-1, -1);
  14436. vertices.push(1, -1);
  14437. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14438. var indices = [];
  14439. indices.push(0);
  14440. indices.push(1);
  14441. indices.push(2);
  14442. indices.push(0);
  14443. indices.push(2);
  14444. indices.push(3);
  14445. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14446. }
  14447. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  14448. var postProcesses = this._scene.activeCamera._postProcesses;
  14449. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14450. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14451. return false;
  14452. }
  14453. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  14454. return true;
  14455. };
  14456. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  14457. var postProcesses = this._scene.activeCamera._postProcesses;
  14458. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  14459. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  14460. return;
  14461. }
  14462. var engine = this._scene.getEngine();
  14463. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  14464. if (index < postProcessesTakenIndices.length - 1) {
  14465. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  14466. } else {
  14467. if (targetTexture) {
  14468. engine.bindFramebuffer(targetTexture);
  14469. } else {
  14470. engine.restoreDefaultFramebuffer();
  14471. }
  14472. }
  14473. if (doNotPresent) {
  14474. break;
  14475. }
  14476. var pp = postProcesses[postProcessesTakenIndices[index]];
  14477. var effect = pp.apply();
  14478. if (effect) {
  14479. if (pp.onBeforeRender) {
  14480. pp.onBeforeRender(effect);
  14481. }
  14482. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14483. engine.draw(true, 0, 6);
  14484. }
  14485. }
  14486. engine.setDepthBuffer(true);
  14487. engine.setDepthWrite(true);
  14488. };
  14489. PostProcessManager.prototype.dispose = function () {
  14490. if (this._vertexBuffer) {
  14491. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14492. this._vertexBuffer = null;
  14493. }
  14494. if (this._indexBuffer) {
  14495. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14496. this._indexBuffer = null;
  14497. }
  14498. };
  14499. return PostProcessManager;
  14500. })();
  14501. BABYLON.PostProcessManager = PostProcessManager;
  14502. })(BABYLON || (BABYLON = {}));
  14503. var __extends = this.__extends || function (d, b) {
  14504. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14505. function __() { this.constructor = d; }
  14506. __.prototype = b.prototype;
  14507. d.prototype = new __();
  14508. };
  14509. var BABYLON;
  14510. (function (BABYLON) {
  14511. var PassPostProcess = (function (_super) {
  14512. __extends(PassPostProcess, _super);
  14513. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14514. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  14515. }
  14516. return PassPostProcess;
  14517. })(BABYLON.PostProcess);
  14518. BABYLON.PassPostProcess = PassPostProcess;
  14519. })(BABYLON || (BABYLON = {}));
  14520. var __extends = this.__extends || function (d, b) {
  14521. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14522. function __() { this.constructor = d; }
  14523. __.prototype = b.prototype;
  14524. d.prototype = new __();
  14525. };
  14526. var BABYLON;
  14527. (function (BABYLON) {
  14528. var BlurPostProcess = (function (_super) {
  14529. __extends(BlurPostProcess, _super);
  14530. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  14531. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  14532. var _this = this;
  14533. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  14534. this.direction = direction;
  14535. this.blurWidth = blurWidth;
  14536. this.onApply = function (effect) {
  14537. effect.setFloat2("screenSize", _this.width, _this.height);
  14538. effect.setVector2("direction", _this.direction);
  14539. effect.setFloat("blurWidth", _this.blurWidth);
  14540. };
  14541. }
  14542. return BlurPostProcess;
  14543. })(BABYLON.PostProcess);
  14544. BABYLON.BlurPostProcess = BlurPostProcess;
  14545. })(BABYLON || (BABYLON = {}));
  14546. var __extends = this.__extends || function (d, b) {
  14547. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14548. function __() { this.constructor = d; }
  14549. __.prototype = b.prototype;
  14550. d.prototype = new __();
  14551. };
  14552. var BABYLON;
  14553. (function (BABYLON) {
  14554. var FilterPostProcess = (function (_super) {
  14555. __extends(FilterPostProcess, _super);
  14556. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  14557. var _this = this;
  14558. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  14559. this.kernelMatrix = kernelMatrix;
  14560. this.onApply = function (effect) {
  14561. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  14562. };
  14563. }
  14564. return FilterPostProcess;
  14565. })(BABYLON.PostProcess);
  14566. BABYLON.FilterPostProcess = FilterPostProcess;
  14567. })(BABYLON || (BABYLON = {}));
  14568. var __extends = this.__extends || function (d, b) {
  14569. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14570. function __() { this.constructor = d; }
  14571. __.prototype = b.prototype;
  14572. d.prototype = new __();
  14573. };
  14574. var BABYLON;
  14575. (function (BABYLON) {
  14576. var RefractionPostProcess = (function (_super) {
  14577. __extends(RefractionPostProcess, _super);
  14578. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  14579. var _this = this;
  14580. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  14581. this.color = color;
  14582. this.depth = depth;
  14583. this.colorLevel = colorLevel;
  14584. this.onActivate = function (cam) {
  14585. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  14586. };
  14587. this.onApply = function (effect) {
  14588. effect.setColor3("baseColor", _this.color);
  14589. effect.setFloat("depth", _this.depth);
  14590. effect.setFloat("colorLevel", _this.colorLevel);
  14591. effect.setTexture("refractionSampler", _this._refRexture);
  14592. };
  14593. }
  14594. RefractionPostProcess.prototype.dispose = function (camera) {
  14595. if (this._refRexture) {
  14596. this._refRexture.dispose();
  14597. }
  14598. _super.prototype.dispose.call(this, camera);
  14599. };
  14600. return RefractionPostProcess;
  14601. })(BABYLON.PostProcess);
  14602. BABYLON.RefractionPostProcess = RefractionPostProcess;
  14603. })(BABYLON || (BABYLON = {}));
  14604. var __extends = this.__extends || function (d, b) {
  14605. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14606. function __() { this.constructor = d; }
  14607. __.prototype = b.prototype;
  14608. d.prototype = new __();
  14609. };
  14610. var BABYLON;
  14611. (function (BABYLON) {
  14612. var BlackAndWhitePostProcess = (function (_super) {
  14613. __extends(BlackAndWhitePostProcess, _super);
  14614. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14615. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  14616. }
  14617. return BlackAndWhitePostProcess;
  14618. })(BABYLON.PostProcess);
  14619. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  14620. })(BABYLON || (BABYLON = {}));
  14621. var __extends = this.__extends || function (d, b) {
  14622. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14623. function __() { this.constructor = d; }
  14624. __.prototype = b.prototype;
  14625. d.prototype = new __();
  14626. };
  14627. var BABYLON;
  14628. (function (BABYLON) {
  14629. var ConvolutionPostProcess = (function (_super) {
  14630. __extends(ConvolutionPostProcess, _super);
  14631. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  14632. var _this = this;
  14633. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  14634. this.kernel = kernel;
  14635. this.onApply = function (effect) {
  14636. effect.setFloat2("screenSize", _this.width, _this.height);
  14637. effect.setArray("kernel", _this.kernel);
  14638. };
  14639. }
  14640. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  14641. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  14642. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  14643. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  14644. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  14645. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  14646. return ConvolutionPostProcess;
  14647. })(BABYLON.PostProcess);
  14648. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  14649. })(BABYLON || (BABYLON = {}));
  14650. var __extends = this.__extends || function (d, b) {
  14651. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14652. function __() { this.constructor = d; }
  14653. __.prototype = b.prototype;
  14654. d.prototype = new __();
  14655. };
  14656. var BABYLON;
  14657. (function (BABYLON) {
  14658. var FxaaPostProcess = (function (_super) {
  14659. __extends(FxaaPostProcess, _super);
  14660. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  14661. var _this = this;
  14662. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  14663. this.onSizeChanged = function () {
  14664. _this.texelWidth = 1.0 / _this.width;
  14665. _this.texelHeight = 1.0 / _this.height;
  14666. };
  14667. this.onApply = function (effect) {
  14668. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  14669. };
  14670. }
  14671. return FxaaPostProcess;
  14672. })(BABYLON.PostProcess);
  14673. BABYLON.FxaaPostProcess = FxaaPostProcess;
  14674. })(BABYLON || (BABYLON = {}));
  14675. var BABYLON;
  14676. (function (BABYLON) {
  14677. var LensFlare = (function () {
  14678. function LensFlare(size, position, color, imgUrl, system) {
  14679. this.size = size;
  14680. this.position = position;
  14681. this.dispose = function () {
  14682. if (this.texture) {
  14683. this.texture.dispose();
  14684. }
  14685. var index = this._system.lensFlares.indexOf(this);
  14686. this._system.lensFlares.splice(index, 1);
  14687. };
  14688. this.color = color || new BABYLON.Color3(1, 1, 1);
  14689. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  14690. this._system = system;
  14691. system.lensFlares.push(this);
  14692. }
  14693. return LensFlare;
  14694. })();
  14695. BABYLON.LensFlare = LensFlare;
  14696. })(BABYLON || (BABYLON = {}));
  14697. var BABYLON;
  14698. (function (BABYLON) {
  14699. var LensFlareSystem = (function () {
  14700. function LensFlareSystem(name, emitter, scene) {
  14701. this.name = name;
  14702. this.lensFlares = new Array();
  14703. this.borderLimit = 300;
  14704. this._vertexDeclaration = [2];
  14705. this._vertexStrideSize = 2 * 4;
  14706. this._isEnabled = true;
  14707. this._scene = scene;
  14708. this._emitter = emitter;
  14709. scene.lensFlareSystems.push(this);
  14710. this.meshesSelectionPredicate = function (m) {
  14711. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  14712. };
  14713. var vertices = [];
  14714. vertices.push(1, 1);
  14715. vertices.push(-1, 1);
  14716. vertices.push(-1, -1);
  14717. vertices.push(1, -1);
  14718. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14719. var indices = [];
  14720. indices.push(0);
  14721. indices.push(1);
  14722. indices.push(2);
  14723. indices.push(0);
  14724. indices.push(2);
  14725. indices.push(3);
  14726. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14727. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  14728. }
  14729. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  14730. get: function () {
  14731. return this._isEnabled;
  14732. },
  14733. set: function (value) {
  14734. this._isEnabled = value;
  14735. },
  14736. enumerable: true,
  14737. configurable: true
  14738. });
  14739. LensFlareSystem.prototype.getScene = function () {
  14740. return this._scene;
  14741. };
  14742. LensFlareSystem.prototype.getEmitter = function () {
  14743. return this._emitter;
  14744. };
  14745. LensFlareSystem.prototype.getEmitterPosition = function () {
  14746. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  14747. };
  14748. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  14749. var position = this.getEmitterPosition();
  14750. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  14751. this._positionX = position.x;
  14752. this._positionY = position.y;
  14753. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  14754. if (position.z > 0) {
  14755. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  14756. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  14757. return true;
  14758. }
  14759. }
  14760. return false;
  14761. };
  14762. LensFlareSystem.prototype._isVisible = function () {
  14763. if (!this._isEnabled) {
  14764. return false;
  14765. }
  14766. var emitterPosition = this.getEmitterPosition();
  14767. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  14768. var distance = direction.length();
  14769. direction.normalize();
  14770. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  14771. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  14772. return !pickInfo.hit || pickInfo.distance > distance;
  14773. };
  14774. LensFlareSystem.prototype.render = function () {
  14775. if (!this._effect.isReady())
  14776. return false;
  14777. var engine = this._scene.getEngine();
  14778. var viewport = this._scene.activeCamera.viewport;
  14779. var globalViewport = viewport.toGlobal(engine);
  14780. if (!this.computeEffectivePosition(globalViewport)) {
  14781. return false;
  14782. }
  14783. if (!this._isVisible()) {
  14784. return false;
  14785. }
  14786. var awayX;
  14787. var awayY;
  14788. if (this._positionX < this.borderLimit + globalViewport.x) {
  14789. awayX = this.borderLimit + globalViewport.x - this._positionX;
  14790. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  14791. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  14792. } else {
  14793. awayX = 0;
  14794. }
  14795. if (this._positionY < this.borderLimit + globalViewport.y) {
  14796. awayY = this.borderLimit + globalViewport.y - this._positionY;
  14797. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  14798. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  14799. } else {
  14800. awayY = 0;
  14801. }
  14802. var away = (awayX > awayY) ? awayX : awayY;
  14803. if (away > this.borderLimit) {
  14804. away = this.borderLimit;
  14805. }
  14806. var intensity = 1.0 - (away / this.borderLimit);
  14807. if (intensity < 0) {
  14808. return false;
  14809. }
  14810. if (intensity > 1.0) {
  14811. intensity = 1.0;
  14812. }
  14813. var centerX = globalViewport.x + globalViewport.width / 2;
  14814. var centerY = globalViewport.y + globalViewport.height / 2;
  14815. var distX = centerX - this._positionX;
  14816. var distY = centerY - this._positionY;
  14817. engine.enableEffect(this._effect);
  14818. engine.setState(false);
  14819. engine.setDepthBuffer(false);
  14820. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14821. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14822. for (var index = 0; index < this.lensFlares.length; index++) {
  14823. var flare = this.lensFlares[index];
  14824. var x = centerX - (distX * flare.position);
  14825. var y = centerY - (distY * flare.position);
  14826. var cw = flare.size;
  14827. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  14828. var cx = 2 * (x / globalViewport.width) - 1.0;
  14829. var cy = 1.0 - 2 * (y / globalViewport.height);
  14830. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  14831. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  14832. this._effect.setTexture("textureSampler", flare.texture);
  14833. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  14834. engine.draw(true, 0, 6);
  14835. }
  14836. engine.setDepthBuffer(true);
  14837. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14838. return true;
  14839. };
  14840. LensFlareSystem.prototype.dispose = function () {
  14841. if (this._vertexBuffer) {
  14842. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14843. this._vertexBuffer = null;
  14844. }
  14845. if (this._indexBuffer) {
  14846. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14847. this._indexBuffer = null;
  14848. }
  14849. while (this.lensFlares.length) {
  14850. this.lensFlares[0].dispose();
  14851. }
  14852. var index = this._scene.lensFlareSystems.indexOf(this);
  14853. this._scene.lensFlareSystems.splice(index, 1);
  14854. };
  14855. return LensFlareSystem;
  14856. })();
  14857. BABYLON.LensFlareSystem = LensFlareSystem;
  14858. })(BABYLON || (BABYLON = {}));
  14859. var BABYLON;
  14860. (function (BABYLON) {
  14861. var IntersectionInfo = (function () {
  14862. function IntersectionInfo(bu, bv, distance) {
  14863. this.bu = bu;
  14864. this.bv = bv;
  14865. this.distance = distance;
  14866. this.faceId = 0;
  14867. }
  14868. return IntersectionInfo;
  14869. })();
  14870. BABYLON.IntersectionInfo = IntersectionInfo;
  14871. var PickingInfo = (function () {
  14872. function PickingInfo() {
  14873. this.hit = false;
  14874. this.distance = 0;
  14875. this.pickedPoint = null;
  14876. this.pickedMesh = null;
  14877. this.bu = 0;
  14878. this.bv = 0;
  14879. this.faceId = -1;
  14880. }
  14881. PickingInfo.prototype.getNormal = function () {
  14882. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14883. return null;
  14884. }
  14885. var indices = this.pickedMesh.getIndices();
  14886. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14887. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  14888. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  14889. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  14890. normal0 = normal0.scale(this.bu);
  14891. normal1 = normal1.scale(this.bv);
  14892. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  14893. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  14894. };
  14895. PickingInfo.prototype.getTextureCoordinates = function () {
  14896. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14897. return null;
  14898. }
  14899. var indices = this.pickedMesh.getIndices();
  14900. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14901. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  14902. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  14903. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  14904. uv0 = uv0.scale(this.bu);
  14905. uv1 = uv1.scale(this.bv);
  14906. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  14907. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  14908. };
  14909. return PickingInfo;
  14910. })();
  14911. BABYLON.PickingInfo = PickingInfo;
  14912. })(BABYLON || (BABYLON = {}));
  14913. var BABYLON;
  14914. (function (BABYLON) {
  14915. var FilesInput = (function () {
  14916. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  14917. this.engine = p_engine;
  14918. this.canvas = p_canvas;
  14919. this.currentScene = p_scene;
  14920. this.sceneLoadedCallback = p_sceneLoadedCallback;
  14921. this.progressCallback = p_progressCallback;
  14922. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  14923. this.textureLoadingCallback = p_textureLoadingCallback;
  14924. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  14925. }
  14926. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  14927. var _this = this;
  14928. if (p_elementToMonitor) {
  14929. this.elementToMonitor = p_elementToMonitor;
  14930. this.elementToMonitor.addEventListener("dragenter", function (e) {
  14931. _this.drag(e);
  14932. }, false);
  14933. this.elementToMonitor.addEventListener("dragover", function (e) {
  14934. _this.drag(e);
  14935. }, false);
  14936. this.elementToMonitor.addEventListener("drop", function (e) {
  14937. _this.drop(e);
  14938. }, false);
  14939. }
  14940. };
  14941. FilesInput.prototype.renderFunction = function () {
  14942. if (this.additionnalRenderLoopLogicCallback) {
  14943. this.additionnalRenderLoopLogicCallback();
  14944. }
  14945. if (this.currentScene) {
  14946. if (this.textureLoadingCallback) {
  14947. var remaining = this.currentScene.getWaitingItemsCount();
  14948. if (remaining > 0) {
  14949. this.textureLoadingCallback(remaining);
  14950. }
  14951. }
  14952. this.currentScene.render();
  14953. }
  14954. };
  14955. FilesInput.prototype.drag = function (e) {
  14956. e.stopPropagation();
  14957. e.preventDefault();
  14958. };
  14959. FilesInput.prototype.drop = function (eventDrop) {
  14960. eventDrop.stopPropagation();
  14961. eventDrop.preventDefault();
  14962. this.loadFiles(eventDrop);
  14963. };
  14964. FilesInput.prototype.loadFiles = function (event) {
  14965. var _this = this;
  14966. var that = this;
  14967. if (this.startingProcessingFilesCallback)
  14968. this.startingProcessingFilesCallback();
  14969. var sceneFileToLoad;
  14970. var filesToLoad;
  14971. if (event && event.dataTransfer && event.dataTransfer.files) {
  14972. filesToLoad = event.dataTransfer.files;
  14973. }
  14974. if (event && event.target && event.target.files) {
  14975. filesToLoad = event.target.files;
  14976. }
  14977. if (filesToLoad && filesToLoad.length > 0) {
  14978. for (var i = 0; i < filesToLoad.length; i++) {
  14979. switch (filesToLoad[i].type) {
  14980. case "image/jpeg":
  14981. case "image/png":
  14982. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  14983. break;
  14984. case "image/targa":
  14985. case "image/vnd.ms-dds":
  14986. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  14987. break;
  14988. default:
  14989. 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) {
  14990. sceneFileToLoad = filesToLoad[i];
  14991. }
  14992. break;
  14993. }
  14994. }
  14995. if (sceneFileToLoad) {
  14996. if (this.currentScene) {
  14997. this.engine.stopRenderLoop();
  14998. this.currentScene.dispose();
  14999. }
  15000. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15001. that.currentScene = newScene;
  15002. that.currentScene.executeWhenReady(function () {
  15003. if (that.currentScene.activeCamera) {
  15004. that.currentScene.activeCamera.attachControl(that.canvas);
  15005. }
  15006. if (that.sceneLoadedCallback) {
  15007. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15008. }
  15009. that.engine.runRenderLoop(function () {
  15010. that.renderFunction();
  15011. });
  15012. });
  15013. }, function (progress) {
  15014. if (_this.progressCallback) {
  15015. _this.progressCallback(progress);
  15016. }
  15017. });
  15018. } else {
  15019. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15020. }
  15021. }
  15022. };
  15023. FilesInput.FilesTextures = new Array();
  15024. FilesInput.FilesToLoad = new Array();
  15025. return FilesInput;
  15026. })();
  15027. BABYLON.FilesInput = FilesInput;
  15028. })(BABYLON || (BABYLON = {}));
  15029. var BABYLON;
  15030. (function (BABYLON) {
  15031. var OimoJSPlugin = (function () {
  15032. function OimoJSPlugin() {
  15033. this._registeredMeshes = [];
  15034. /**
  15035. * Update the body position according to the mesh position
  15036. * @param mesh
  15037. */
  15038. this.updateBodyPosition = function (mesh) {
  15039. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15040. var registeredMesh = this._registeredMeshes[index];
  15041. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15042. var body = registeredMesh.body.body;
  15043. mesh.computeWorldMatrix(true);
  15044. var center = mesh.getBoundingInfo().boundingBox.center;
  15045. body.setPosition(center.x, center.y, center.z);
  15046. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15047. return;
  15048. }
  15049. if (registeredMesh.mesh.parent === mesh) {
  15050. mesh.computeWorldMatrix(true);
  15051. registeredMesh.mesh.computeWorldMatrix(true);
  15052. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15053. var absoluteRotation = mesh.rotation;
  15054. body = registeredMesh.body.body;
  15055. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15056. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15057. return;
  15058. }
  15059. }
  15060. };
  15061. }
  15062. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15063. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15064. };
  15065. OimoJSPlugin.prototype.initialize = function (iterations) {
  15066. this._world = new OIMO.World();
  15067. this._world.clear();
  15068. };
  15069. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15070. this._world.gravity = gravity;
  15071. };
  15072. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15073. var body = null;
  15074. this.unregisterMesh(mesh);
  15075. mesh.computeWorldMatrix(true);
  15076. switch (impostor) {
  15077. case BABYLON.PhysicsEngine.SphereImpostor:
  15078. var bbox = mesh.getBoundingInfo().boundingBox;
  15079. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15080. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15081. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15082. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15083. var deltaPosition = mesh.position.subtract(bbox.center);
  15084. body = new OIMO.Body({
  15085. type: 'sphere',
  15086. size: [size],
  15087. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15088. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15089. move: options.mass != 0,
  15090. config: [options.mass, options.friction, options.restitution],
  15091. world: this._world
  15092. });
  15093. this._registeredMeshes.push({
  15094. mesh: mesh,
  15095. body: body,
  15096. delta: deltaPosition
  15097. });
  15098. break;
  15099. case BABYLON.PhysicsEngine.PlaneImpostor:
  15100. case BABYLON.PhysicsEngine.BoxImpostor:
  15101. bbox = mesh.getBoundingInfo().boundingBox;
  15102. var min = bbox.minimumWorld;
  15103. var max = bbox.maximumWorld;
  15104. var box = max.subtract(min);
  15105. var sizeX = this._checkWithEpsilon(box.x);
  15106. var sizeY = this._checkWithEpsilon(box.y);
  15107. var sizeZ = this._checkWithEpsilon(box.z);
  15108. var deltaPosition = mesh.position.subtract(bbox.center);
  15109. body = new OIMO.Body({
  15110. type: 'box',
  15111. size: [sizeX, sizeY, sizeZ],
  15112. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15113. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15114. move: options.mass != 0,
  15115. config: [options.mass, options.friction, options.restitution],
  15116. world: this._world
  15117. });
  15118. this._registeredMeshes.push({
  15119. mesh: mesh,
  15120. body: body,
  15121. delta: deltaPosition
  15122. });
  15123. break;
  15124. }
  15125. return body;
  15126. };
  15127. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15128. var types = [], sizes = [], positions = [], rotations = [];
  15129. var initialMesh = parts[0].mesh;
  15130. for (var index = 0; index < parts.length; index++) {
  15131. var part = parts[index];
  15132. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  15133. types.push(bodyParameters.type);
  15134. sizes.push.apply(sizes, bodyParameters.size);
  15135. positions.push.apply(positions, bodyParameters.pos);
  15136. rotations.push.apply(rotations, bodyParameters.rot);
  15137. }
  15138. var body = new OIMO.Body({
  15139. type: types,
  15140. size: sizes,
  15141. pos: positions,
  15142. rot: rotations,
  15143. move: options.mass != 0,
  15144. config: [options.mass, options.friction, options.restitution],
  15145. world: this._world
  15146. });
  15147. this._registeredMeshes.push({
  15148. mesh: initialMesh,
  15149. body: body
  15150. });
  15151. return body;
  15152. };
  15153. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  15154. var bodyParameters = null;
  15155. var mesh = part.mesh;
  15156. switch (part.impostor) {
  15157. case BABYLON.PhysicsEngine.SphereImpostor:
  15158. var bbox = mesh.getBoundingInfo().boundingBox;
  15159. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15160. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15161. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15162. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15163. bodyParameters = {
  15164. type: 'sphere',
  15165. /* bug with oimo : sphere needs 3 sizes in this case */
  15166. size: [size, -1, -1],
  15167. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15168. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15169. };
  15170. break;
  15171. case BABYLON.PhysicsEngine.PlaneImpostor:
  15172. case BABYLON.PhysicsEngine.BoxImpostor:
  15173. bbox = mesh.getBoundingInfo().boundingBox;
  15174. var min = bbox.minimumWorld;
  15175. var max = bbox.maximumWorld;
  15176. var box = max.subtract(min);
  15177. var sizeX = this._checkWithEpsilon(box.x);
  15178. var sizeY = this._checkWithEpsilon(box.y);
  15179. var sizeZ = this._checkWithEpsilon(box.z);
  15180. var relativePosition = mesh.position;
  15181. bodyParameters = {
  15182. type: 'box',
  15183. size: [sizeX, sizeY, sizeZ],
  15184. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  15185. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15186. };
  15187. break;
  15188. }
  15189. return bodyParameters;
  15190. };
  15191. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  15192. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15193. var registeredMesh = this._registeredMeshes[index];
  15194. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15195. if (registeredMesh.body) {
  15196. this._world.removeRigidBody(registeredMesh.body.body);
  15197. this._unbindBody(registeredMesh.body);
  15198. }
  15199. this._registeredMeshes.splice(index, 1);
  15200. return;
  15201. }
  15202. }
  15203. };
  15204. OimoJSPlugin.prototype._unbindBody = function (body) {
  15205. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15206. var registeredMesh = this._registeredMeshes[index];
  15207. if (registeredMesh.body === body) {
  15208. registeredMesh.body = null;
  15209. }
  15210. }
  15211. };
  15212. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  15213. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15214. var registeredMesh = this._registeredMeshes[index];
  15215. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15216. var mass = registeredMesh.body.body.massInfo.mass;
  15217. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  15218. return;
  15219. }
  15220. }
  15221. };
  15222. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15223. var body1 = null, body2 = null;
  15224. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15225. var registeredMesh = this._registeredMeshes[index];
  15226. if (registeredMesh.mesh === mesh1) {
  15227. body1 = registeredMesh.body.body;
  15228. } else if (registeredMesh.mesh === mesh2) {
  15229. body2 = registeredMesh.body.body;
  15230. }
  15231. }
  15232. if (!body1 || !body2) {
  15233. return false;
  15234. }
  15235. if (!options) {
  15236. options = {};
  15237. }
  15238. new OIMO.Link({
  15239. type: options.type,
  15240. body1: body1,
  15241. body2: body2,
  15242. min: options.min,
  15243. max: options.max,
  15244. axe1: options.axe1,
  15245. axe2: options.axe2,
  15246. pos1: [pivot1.x, pivot1.y, pivot1.z],
  15247. pos2: [pivot2.x, pivot2.y, pivot2.z],
  15248. collision: options.collision,
  15249. spring: options.spring,
  15250. world: this._world
  15251. });
  15252. return true;
  15253. };
  15254. OimoJSPlugin.prototype.dispose = function () {
  15255. this._world.clear();
  15256. while (this._registeredMeshes.length) {
  15257. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15258. }
  15259. };
  15260. OimoJSPlugin.prototype.isSupported = function () {
  15261. return OIMO !== undefined;
  15262. };
  15263. OimoJSPlugin.prototype._getLastShape = function (body) {
  15264. var lastShape = body.shapes;
  15265. while (lastShape.next) {
  15266. lastShape = lastShape.next;
  15267. }
  15268. return lastShape;
  15269. };
  15270. OimoJSPlugin.prototype.runOneStep = function (time) {
  15271. this._world.step();
  15272. var i = this._registeredMeshes.length;
  15273. var m;
  15274. while (i--) {
  15275. var body = this._registeredMeshes[i].body.body;
  15276. var mesh = this._registeredMeshes[i].mesh;
  15277. var delta = this._registeredMeshes[i].delta;
  15278. if (!body.sleeping) {
  15279. if (body.shapes.next) {
  15280. var parentShape = this._getLastShape(body);
  15281. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  15282. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  15283. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  15284. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  15285. if (!mesh.rotationQuaternion) {
  15286. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15287. }
  15288. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15289. mesh.computeWorldMatrix();
  15290. } else {
  15291. m = body.getMatrix();
  15292. mtx = BABYLON.Matrix.FromArray(m);
  15293. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  15294. if (!delta) {
  15295. mesh.position.x = bodyX;
  15296. mesh.position.y = bodyY;
  15297. mesh.position.z = bodyZ;
  15298. } else {
  15299. mesh.position.x = bodyX + delta.x;
  15300. mesh.position.y = bodyY + delta.y;
  15301. mesh.position.z = bodyZ + delta.z;
  15302. }
  15303. if (!mesh.rotationQuaternion) {
  15304. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15305. }
  15306. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  15307. mesh.computeWorldMatrix();
  15308. }
  15309. }
  15310. }
  15311. };
  15312. return OimoJSPlugin;
  15313. })();
  15314. BABYLON.OimoJSPlugin = OimoJSPlugin;
  15315. })(BABYLON || (BABYLON = {}));
  15316. var BABYLON;
  15317. (function (BABYLON) {
  15318. var PhysicsEngine = (function () {
  15319. function PhysicsEngine(plugin) {
  15320. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  15321. }
  15322. PhysicsEngine.prototype._initialize = function (gravity) {
  15323. this._currentPlugin.initialize();
  15324. this._setGravity(gravity);
  15325. };
  15326. PhysicsEngine.prototype._runOneStep = function (delta) {
  15327. if (delta > 0.1) {
  15328. delta = 0.1;
  15329. } else if (delta <= 0) {
  15330. delta = 1.0 / 60.0;
  15331. }
  15332. this._currentPlugin.runOneStep(delta);
  15333. };
  15334. PhysicsEngine.prototype._setGravity = function (gravity) {
  15335. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  15336. this._currentPlugin.setGravity(this.gravity);
  15337. };
  15338. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  15339. return this._currentPlugin.registerMesh(mesh, impostor, options);
  15340. };
  15341. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  15342. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  15343. };
  15344. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  15345. this._currentPlugin.unregisterMesh(mesh);
  15346. };
  15347. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  15348. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  15349. };
  15350. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15351. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  15352. };
  15353. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  15354. this._currentPlugin.updateBodyPosition(mesh);
  15355. };
  15356. PhysicsEngine.prototype.dispose = function () {
  15357. this._currentPlugin.dispose();
  15358. };
  15359. PhysicsEngine.prototype.isSupported = function () {
  15360. return this._currentPlugin.isSupported();
  15361. };
  15362. PhysicsEngine.NoImpostor = 0;
  15363. PhysicsEngine.SphereImpostor = 1;
  15364. PhysicsEngine.BoxImpostor = 2;
  15365. PhysicsEngine.PlaneImpostor = 3;
  15366. PhysicsEngine.MeshImpostor = 4;
  15367. PhysicsEngine.CapsuleImpostor = 5;
  15368. PhysicsEngine.ConeImpostor = 6;
  15369. PhysicsEngine.CylinderImpostor = 7;
  15370. PhysicsEngine.ConvexHullImpostor = 8;
  15371. PhysicsEngine.Epsilon = 0.001;
  15372. return PhysicsEngine;
  15373. })();
  15374. BABYLON.PhysicsEngine = PhysicsEngine;
  15375. })(BABYLON || (BABYLON = {}));
  15376. var BABYLON;
  15377. (function (BABYLON) {
  15378. var serializeLight = function (light) {
  15379. var serializationObject = {};
  15380. serializationObject.name = light.name;
  15381. serializationObject.id = light.id;
  15382. serializationObject.tags = BABYLON.Tags.GetTags(light);
  15383. if (light instanceof BABYLON.PointLight) {
  15384. serializationObject.type = 0;
  15385. serializationObject.position = light.position.asArray();
  15386. } else if (light instanceof BABYLON.DirectionalLight) {
  15387. serializationObject.type = 1;
  15388. var directionalLight = light;
  15389. serializationObject.position = directionalLight.position.asArray();
  15390. serializationObject.direction = directionalLight.direction.asArray();
  15391. } else if (light instanceof BABYLON.SpotLight) {
  15392. serializationObject.type = 2;
  15393. var spotLight = light;
  15394. serializationObject.position = spotLight.position.asArray();
  15395. serializationObject.direction = spotLight.position.asArray();
  15396. serializationObject.angle = spotLight.angle;
  15397. serializationObject.exponent = spotLight.exponent;
  15398. } else if (light instanceof BABYLON.HemisphericLight) {
  15399. serializationObject.type = 3;
  15400. var hemisphericLight = light;
  15401. serializationObject.direction = hemisphericLight.direction.asArray();
  15402. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  15403. }
  15404. if (light.intensity) {
  15405. serializationObject.intensity = light.intensity;
  15406. }
  15407. serializationObject.range = light.range;
  15408. serializationObject.diffuse = light.diffuse.asArray();
  15409. serializationObject.specular = light.specular.asArray();
  15410. return serializationObject;
  15411. };
  15412. var serializeFresnelParameter = function (fresnelParameter) {
  15413. var serializationObject = {};
  15414. serializationObject.isEnabled = fresnelParameter.isEnabled;
  15415. serializationObject.leftColor = fresnelParameter.leftColor;
  15416. serializationObject.rightColor = fresnelParameter.rightColor;
  15417. serializationObject.bias = fresnelParameter.bias;
  15418. serializationObject.power = fresnelParameter.power;
  15419. return serializationObject;
  15420. };
  15421. var serializeCamera = function (camera) {
  15422. var serializationObject = {};
  15423. serializationObject.name = camera.name;
  15424. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  15425. serializationObject.id = camera.id;
  15426. serializationObject.position = camera.position.asArray();
  15427. if (camera.parent) {
  15428. serializationObject.parentId = camera.parent.id;
  15429. }
  15430. serializationObject.rotation = camera.rotation.asArray();
  15431. if (camera.lockedTarget && camera.lockedTarget.id) {
  15432. serializationObject.lockedTargetId = camera.lockedTarget.id;
  15433. }
  15434. serializationObject.fov = camera.fov;
  15435. serializationObject.minZ = camera.minZ;
  15436. serializationObject.maxZ = camera.maxZ;
  15437. serializationObject.speed = camera.speed;
  15438. serializationObject.inertia = camera.inertia;
  15439. serializationObject.checkCollisions = camera.checkCollisions;
  15440. serializationObject.applyGravity = camera.applyGravity;
  15441. if (camera.ellipsoid) {
  15442. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  15443. }
  15444. appendAnimations(camera, serializationObject);
  15445. serializationObject.layerMask = camera.layerMask;
  15446. return serializationObject;
  15447. };
  15448. var appendAnimations = function (source, destination) {
  15449. if (source.animations) {
  15450. destination.animations = [];
  15451. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  15452. var animation = source.animations[animationIndex];
  15453. destination.animations.push(serializeAnimation(animation));
  15454. }
  15455. }
  15456. };
  15457. var serializeAnimation = function (animation) {
  15458. var serializationObject = {};
  15459. serializationObject.name = animation.name;
  15460. serializationObject.property = animation.targetProperty;
  15461. serializationObject.framePerSecond = animation.framePerSecond;
  15462. serializationObject.dataType = animation.dataType;
  15463. serializationObject.loopBehavior = animation.loopMode;
  15464. var dataType = animation.dataType;
  15465. serializationObject.keys = [];
  15466. var keys = animation.getKeys();
  15467. for (var index = 0; index < keys.length; index++) {
  15468. var animationKey = keys[index];
  15469. var key = {};
  15470. key.frame = animationKey.frame;
  15471. switch (dataType) {
  15472. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  15473. key.values = [animationKey.value];
  15474. break;
  15475. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  15476. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  15477. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  15478. key.values = animationKey.value.asArray();
  15479. break;
  15480. }
  15481. serializationObject.keys.push(key);
  15482. }
  15483. return serializationObject;
  15484. };
  15485. var serializeMultiMaterial = function (material) {
  15486. var serializationObject = {};
  15487. serializationObject.name = material.name;
  15488. serializationObject.id = material.id;
  15489. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15490. serializationObject.materials = [];
  15491. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  15492. var subMat = material.subMaterials[matIndex];
  15493. if (subMat) {
  15494. serializationObject.materials.push(subMat.id);
  15495. } else {
  15496. serializationObject.materials.push(null);
  15497. }
  15498. }
  15499. return serializationObject;
  15500. };
  15501. var serializeMaterial = function (material) {
  15502. var serializationObject = {};
  15503. serializationObject.name = material.name;
  15504. serializationObject.ambient = material.ambientColor.asArray();
  15505. serializationObject.diffuse = material.diffuseColor.asArray();
  15506. serializationObject.specular = material.specularColor.asArray();
  15507. serializationObject.specularPower = material.specularPower;
  15508. serializationObject.emissive = material.emissiveColor.asArray();
  15509. serializationObject.alpha = material.alpha;
  15510. serializationObject.id = material.id;
  15511. serializationObject.tags = BABYLON.Tags.GetTags(material);
  15512. serializationObject.backFaceCulling = material.backFaceCulling;
  15513. if (material.diffuseTexture) {
  15514. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  15515. }
  15516. if (material.diffuseFresnelParameters) {
  15517. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  15518. }
  15519. if (material.ambientTexture) {
  15520. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  15521. }
  15522. if (material.opacityTexture) {
  15523. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  15524. }
  15525. if (material.opacityFresnelParameters) {
  15526. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  15527. }
  15528. if (material.reflectionTexture) {
  15529. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  15530. }
  15531. if (material.reflectionFresnelParameters) {
  15532. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  15533. }
  15534. if (material.emissiveTexture) {
  15535. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  15536. }
  15537. if (material.emissiveFresnelParameters) {
  15538. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  15539. }
  15540. if (material.specularTexture) {
  15541. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  15542. }
  15543. if (material.bumpTexture) {
  15544. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  15545. }
  15546. return serializationObject;
  15547. };
  15548. var serializeTexture = function (texture) {
  15549. var serializationObject = {};
  15550. if (!texture.name) {
  15551. return null;
  15552. }
  15553. if (texture instanceof BABYLON.CubeTexture) {
  15554. serializationObject.name = texture.name;
  15555. serializationObject.hasAlpha = texture.hasAlpha;
  15556. serializationObject.level = texture.level;
  15557. serializationObject.coordinatesMode = texture.coordinatesMode;
  15558. return serializationObject;
  15559. }
  15560. if (texture instanceof BABYLON.MirrorTexture) {
  15561. var mirrorTexture = texture;
  15562. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  15563. serializationObject.renderList = [];
  15564. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  15565. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  15566. }
  15567. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  15568. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  15569. var renderTargetTexture = texture;
  15570. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  15571. serializationObject.renderList = [];
  15572. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  15573. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  15574. }
  15575. }
  15576. var regularTexture = texture;
  15577. serializationObject.name = texture.name;
  15578. serializationObject.hasAlpha = texture.hasAlpha;
  15579. serializationObject.level = texture.level;
  15580. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  15581. serializationObject.coordinatesMode = texture.coordinatesMode;
  15582. serializationObject.uOffset = regularTexture.uOffset;
  15583. serializationObject.vOffset = regularTexture.vOffset;
  15584. serializationObject.uScale = regularTexture.uScale;
  15585. serializationObject.vScale = regularTexture.vScale;
  15586. serializationObject.uAng = regularTexture.uAng;
  15587. serializationObject.vAng = regularTexture.vAng;
  15588. serializationObject.wAng = regularTexture.wAng;
  15589. serializationObject.wrapU = texture.wrapU;
  15590. serializationObject.wrapV = texture.wrapV;
  15591. appendAnimations(texture, serializationObject);
  15592. return serializationObject;
  15593. };
  15594. var serializeSkeleton = function (skeleton) {
  15595. var serializationObject = {};
  15596. serializationObject.name = skeleton.name;
  15597. serializationObject.id = skeleton.id;
  15598. serializationObject.bones = [];
  15599. for (var index = 0; index < skeleton.bones.length; index++) {
  15600. var bone = skeleton.bones[index];
  15601. var serializedBone = {
  15602. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  15603. name: bone.name,
  15604. matrix: bone.getLocalMatrix().toArray()
  15605. };
  15606. serializationObject.bones.push(serializedBone);
  15607. if (bone.animations && bone.animations.length > 0) {
  15608. serializedBone.animation = serializeAnimation(bone.animations[0]);
  15609. }
  15610. }
  15611. return serializationObject;
  15612. };
  15613. var serializeParticleSystem = function (particleSystem) {
  15614. var serializationObject = {};
  15615. serializationObject.emitterId = particleSystem.emitter.id;
  15616. serializationObject.capacity = particleSystem.getCapacity();
  15617. if (particleSystem.particleTexture) {
  15618. serializationObject.textureName = particleSystem.particleTexture.name;
  15619. }
  15620. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  15621. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  15622. serializationObject.minSize = particleSystem.minSize;
  15623. serializationObject.maxSize = particleSystem.maxSize;
  15624. serializationObject.minLifeTime = particleSystem.minLifeTime;
  15625. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  15626. serializationObject.emitRate = particleSystem.emitRate;
  15627. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  15628. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  15629. serializationObject.gravity = particleSystem.gravity.asArray();
  15630. serializationObject.direction1 = particleSystem.direction1.asArray();
  15631. serializationObject.direction2 = particleSystem.direction2.asArray();
  15632. serializationObject.color1 = particleSystem.color1.asArray();
  15633. serializationObject.color2 = particleSystem.color2.asArray();
  15634. serializationObject.colorDead = particleSystem.colorDead.asArray();
  15635. serializationObject.updateSpeed = particleSystem.updateSpeed;
  15636. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  15637. serializationObject.textureMask = particleSystem.textureMask.asArray();
  15638. serializationObject.blendMode = particleSystem.blendMode;
  15639. return serializationObject;
  15640. };
  15641. var serializeLensFlareSystem = function (lensFlareSystem) {
  15642. var serializationObject = {};
  15643. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  15644. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  15645. serializationObject.flares = [];
  15646. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  15647. var flare = lensFlareSystem.lensFlares[index];
  15648. serializationObject.flares.push({
  15649. size: flare.size,
  15650. position: flare.position,
  15651. color: flare.color.asArray(),
  15652. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  15653. });
  15654. }
  15655. return serializationObject;
  15656. };
  15657. var serializeShadowGenerator = function (light) {
  15658. var serializationObject = {};
  15659. var shadowGenerator = light.getShadowGenerator();
  15660. serializationObject.lightId = light.id;
  15661. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  15662. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  15663. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  15664. serializationObject.renderList = [];
  15665. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  15666. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  15667. serializationObject.renderList.push(mesh.id);
  15668. }
  15669. return serializationObject;
  15670. };
  15671. var serializedGeometries = [];
  15672. var serializeGeometry = function (geometry, serializationGeometries) {
  15673. if (serializedGeometries[geometry.id]) {
  15674. return;
  15675. }
  15676. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  15677. serializationGeometries.boxes.push(serializeBox(geometry));
  15678. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  15679. serializationGeometries.spheres.push(serializeSphere(geometry));
  15680. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  15681. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  15682. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  15683. serializationGeometries.toruses.push(serializeTorus(geometry));
  15684. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  15685. serializationGeometries.grounds.push(serializeGround(geometry));
  15686. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  15687. serializationGeometries.planes.push(serializePlane(geometry));
  15688. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  15689. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  15690. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  15691. throw new Error("Unknow primitive type");
  15692. } else {
  15693. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  15694. }
  15695. serializedGeometries[geometry.id] = true;
  15696. };
  15697. var serializeGeometryBase = function (geometry) {
  15698. var serializationObject = {};
  15699. serializationObject.id = geometry.id;
  15700. if (BABYLON.Tags.HasTags(geometry)) {
  15701. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  15702. }
  15703. return serializationObject;
  15704. };
  15705. var serializeVertexData = function (vertexData) {
  15706. var serializationObject = serializeGeometryBase(vertexData);
  15707. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15708. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15709. }
  15710. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15711. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15712. }
  15713. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15714. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15715. }
  15716. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15717. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  15718. }
  15719. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15720. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  15721. }
  15722. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15723. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15724. serializationObject.matricesIndices._isExpanded = true;
  15725. }
  15726. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15727. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15728. }
  15729. serializationObject.indices = vertexData.getIndices();
  15730. return serializationObject;
  15731. };
  15732. var serializePrimitive = function (primitive) {
  15733. var serializationObject = serializeGeometryBase(primitive);
  15734. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  15735. return serializationObject;
  15736. };
  15737. var serializeBox = function (box) {
  15738. var serializationObject = serializePrimitive(box);
  15739. serializationObject.size = box.size;
  15740. return serializationObject;
  15741. };
  15742. var serializeSphere = function (sphere) {
  15743. var serializationObject = serializePrimitive(sphere);
  15744. serializationObject.segments = sphere.segments;
  15745. serializationObject.diameter = sphere.diameter;
  15746. return serializationObject;
  15747. };
  15748. var serializeCylinder = function (cylinder) {
  15749. var serializationObject = serializePrimitive(cylinder);
  15750. serializationObject.height = cylinder.height;
  15751. serializationObject.diameterTop = cylinder.diameterTop;
  15752. serializationObject.diameterBottom = cylinder.diameterBottom;
  15753. serializationObject.tessellation = cylinder.tessellation;
  15754. return serializationObject;
  15755. };
  15756. var serializeTorus = function (torus) {
  15757. var serializationObject = serializePrimitive(torus);
  15758. serializationObject.diameter = torus.diameter;
  15759. serializationObject.thickness = torus.thickness;
  15760. serializationObject.tessellation = torus.tessellation;
  15761. return serializationObject;
  15762. };
  15763. var serializeGround = function (ground) {
  15764. var serializationObject = serializePrimitive(ground);
  15765. serializationObject.width = ground.width;
  15766. serializationObject.height = ground.height;
  15767. serializationObject.subdivisions = ground.subdivisions;
  15768. return serializationObject;
  15769. };
  15770. var serializePlane = function (plane) {
  15771. var serializationObject = serializePrimitive(plane);
  15772. serializationObject.size = plane.size;
  15773. return serializationObject;
  15774. };
  15775. var serializeTorusKnot = function (torusKnot) {
  15776. var serializationObject = serializePrimitive(torusKnot);
  15777. serializationObject.radius = torusKnot.radius;
  15778. serializationObject.tube = torusKnot.tube;
  15779. serializationObject.radialSegments = torusKnot.radialSegments;
  15780. serializationObject.tubularSegments = torusKnot.tubularSegments;
  15781. serializationObject.p = torusKnot.p;
  15782. serializationObject.q = torusKnot.q;
  15783. return serializationObject;
  15784. };
  15785. var serializeMesh = function (mesh, serializationScene) {
  15786. var serializationObject = {};
  15787. serializationObject.name = mesh.name;
  15788. serializationObject.id = mesh.id;
  15789. if (BABYLON.Tags.HasTags(mesh)) {
  15790. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  15791. }
  15792. serializationObject.position = mesh.position.asArray();
  15793. if (mesh.rotationQuaternion) {
  15794. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  15795. } else if (mesh.rotation) {
  15796. serializationObject.rotation = mesh.rotation.asArray();
  15797. }
  15798. serializationObject.scaling = mesh.scaling.asArray();
  15799. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  15800. serializationObject.isEnabled = mesh.isEnabled();
  15801. serializationObject.isVisible = mesh.isVisible;
  15802. serializationObject.infiniteDistance = mesh.infiniteDistance;
  15803. serializationObject.pickable = mesh.isPickable;
  15804. serializationObject.receiveShadows = mesh.receiveShadows;
  15805. serializationObject.billboardMode = mesh.billboardMode;
  15806. serializationObject.visibility = mesh.visibility;
  15807. serializationObject.checkCollisions = mesh.checkCollisions;
  15808. if (mesh.parent) {
  15809. serializationObject.parentId = mesh.parent.id;
  15810. }
  15811. var geometry = mesh._geometry;
  15812. if (geometry) {
  15813. var geometryId = geometry.id;
  15814. serializationObject.geometryId = geometryId;
  15815. if (!mesh.getScene().getGeometryByID(geometryId)) {
  15816. serializeGeometry(geometry, serializationScene.geometries);
  15817. }
  15818. serializationObject.subMeshes = [];
  15819. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15820. var subMesh = mesh.subMeshes[subIndex];
  15821. serializationObject.subMeshes.push({
  15822. materialIndex: subMesh.materialIndex,
  15823. verticesStart: subMesh.verticesStart,
  15824. verticesCount: subMesh.verticesCount,
  15825. indexStart: subMesh.indexStart,
  15826. indexCount: subMesh.indexCount
  15827. });
  15828. }
  15829. }
  15830. if (mesh.material) {
  15831. serializationObject.materialId = mesh.material.id;
  15832. } else {
  15833. mesh.material = null;
  15834. }
  15835. if (mesh.skeleton) {
  15836. serializationObject.skeletonId = mesh.skeleton.id;
  15837. }
  15838. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  15839. serializationObject.physicsMass = mesh.getPhysicsMass();
  15840. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  15841. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  15842. switch (mesh.getPhysicsImpostor()) {
  15843. case BABYLON.PhysicsEngine.BoxImpostor:
  15844. serializationObject.physicsImpostor = 1;
  15845. break;
  15846. case BABYLON.PhysicsEngine.SphereImpostor:
  15847. serializationObject.physicsImpostor = 2;
  15848. break;
  15849. }
  15850. }
  15851. serializationObject.instances = [];
  15852. for (var index = 0; index < mesh.instances.length; index++) {
  15853. var instance = mesh.instances[index];
  15854. var serializationInstance = {
  15855. name: instance.name,
  15856. position: instance.position,
  15857. rotation: instance.rotation,
  15858. rotationQuaternion: instance.rotationQuaternion,
  15859. scaling: instance.scaling
  15860. };
  15861. serializationObject.instances.push(serializationInstance);
  15862. appendAnimations(instance, serializationInstance);
  15863. }
  15864. appendAnimations(mesh, serializationObject);
  15865. serializationObject.layerMask = mesh.layerMask;
  15866. return serializationObject;
  15867. };
  15868. var SceneSerializer = (function () {
  15869. function SceneSerializer() {
  15870. }
  15871. SceneSerializer.Serialize = function (scene) {
  15872. var serializationObject = {};
  15873. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  15874. serializationObject.autoClear = scene.autoClear;
  15875. serializationObject.clearColor = scene.clearColor.asArray();
  15876. serializationObject.ambientColor = scene.ambientColor.asArray();
  15877. serializationObject.gravity = scene.gravity.asArray();
  15878. if (scene.fogMode && scene.fogMode !== 0) {
  15879. serializationObject.fogMode = scene.fogMode;
  15880. serializationObject.fogColor = scene.fogColor.asArray();
  15881. serializationObject.fogStart = scene.fogStart;
  15882. serializationObject.fogEnd = scene.fogEnd;
  15883. serializationObject.fogDensity = scene.fogDensity;
  15884. }
  15885. serializationObject.lights = [];
  15886. for (var index = 0; index < scene.lights.length; index++) {
  15887. var light = scene.lights[index];
  15888. serializationObject.lights.push(serializeLight(light));
  15889. }
  15890. serializationObject.cameras = [];
  15891. for (index = 0; index < scene.cameras.length; index++) {
  15892. var camera = scene.cameras[index];
  15893. if (camera instanceof BABYLON.FreeCamera) {
  15894. serializationObject.cameras.push(serializeCamera(camera));
  15895. }
  15896. }
  15897. if (scene.activeCamera) {
  15898. serializationObject.activeCameraID = scene.activeCamera.id;
  15899. }
  15900. serializationObject.materials = [];
  15901. serializationObject.multiMaterials = [];
  15902. for (index = 0; index < scene.materials.length; index++) {
  15903. var material = scene.materials[index];
  15904. if (material instanceof BABYLON.StandardMaterial) {
  15905. serializationObject.materials.push(serializeMaterial(material));
  15906. } else if (material instanceof BABYLON.MultiMaterial) {
  15907. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  15908. }
  15909. }
  15910. serializationObject.skeletons = [];
  15911. for (index = 0; index < scene.skeletons.length; index++) {
  15912. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  15913. }
  15914. serializationObject.geometries = {};
  15915. serializationObject.geometries.boxes = [];
  15916. serializationObject.geometries.spheres = [];
  15917. serializationObject.geometries.cylinders = [];
  15918. serializationObject.geometries.toruses = [];
  15919. serializationObject.geometries.grounds = [];
  15920. serializationObject.geometries.planes = [];
  15921. serializationObject.geometries.torusKnots = [];
  15922. serializationObject.geometries.vertexData = [];
  15923. serializedGeometries = [];
  15924. var geometries = scene.getGeometries();
  15925. for (var index = 0; index < geometries.length; index++) {
  15926. var geometry = geometries[index];
  15927. if (geometry.isReady()) {
  15928. serializeGeometry(geometry, serializationObject.geometries);
  15929. }
  15930. }
  15931. serializationObject.meshes = [];
  15932. for (index = 0; index < scene.meshes.length; index++) {
  15933. var abstractMesh = scene.meshes[index];
  15934. if (abstractMesh instanceof BABYLON.Mesh) {
  15935. var mesh = abstractMesh;
  15936. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  15937. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  15938. }
  15939. }
  15940. }
  15941. serializationObject.particleSystems = [];
  15942. for (index = 0; index < scene.particleSystems.length; index++) {
  15943. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  15944. }
  15945. serializationObject.lensFlareSystems = [];
  15946. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  15947. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  15948. }
  15949. serializationObject.shadowGenerators = [];
  15950. for (index = 0; index < scene.lights.length; index++) {
  15951. light = scene.lights[index];
  15952. if (light.getShadowGenerator()) {
  15953. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  15954. }
  15955. }
  15956. return serializationObject;
  15957. };
  15958. return SceneSerializer;
  15959. })();
  15960. BABYLON.SceneSerializer = SceneSerializer;
  15961. })(BABYLON || (BABYLON = {}));
  15962. var BABYLON;
  15963. (function (BABYLON) {
  15964. var SceneLoader = (function () {
  15965. function SceneLoader() {
  15966. }
  15967. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  15968. get: function () {
  15969. return SceneLoader._ForceFullSceneLoadingForIncremental;
  15970. },
  15971. set: function (value) {
  15972. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  15978. get: function () {
  15979. return SceneLoader._ShowLoadingScreen;
  15980. },
  15981. set: function (value) {
  15982. SceneLoader._ShowLoadingScreen = value;
  15983. },
  15984. enumerable: true,
  15985. configurable: true
  15986. });
  15987. SceneLoader._getPluginForFilename = function (sceneFilename) {
  15988. var dotPosition = sceneFilename.lastIndexOf(".");
  15989. var queryStringPosition = sceneFilename.indexOf("?");
  15990. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  15991. for (var index = 0; index < this._registeredPlugins.length; index++) {
  15992. var plugin = this._registeredPlugins[index];
  15993. if (plugin.extensions.indexOf(extension) !== -1) {
  15994. return plugin;
  15995. }
  15996. }
  15997. return this._registeredPlugins[this._registeredPlugins.length - 1];
  15998. };
  15999. SceneLoader.RegisterPlugin = function (plugin) {
  16000. plugin.extensions = plugin.extensions.toLowerCase();
  16001. SceneLoader._registeredPlugins.push(plugin);
  16002. };
  16003. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16004. var manifestChecked = function (success) {
  16005. scene.database = database;
  16006. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16007. var importMeshFromData = function (data) {
  16008. var meshes = [];
  16009. var particleSystems = [];
  16010. var skeletons = [];
  16011. try {
  16012. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16013. if (onerror) {
  16014. onerror(scene, 'unable to load the scene');
  16015. }
  16016. return;
  16017. }
  16018. } catch (e) {
  16019. if (onerror) {
  16020. onerror(scene, e);
  16021. }
  16022. return;
  16023. }
  16024. if (onsuccess) {
  16025. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16026. onsuccess(meshes, particleSystems, skeletons);
  16027. }
  16028. };
  16029. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16030. importMeshFromData(sceneFilename.substr(5));
  16031. return;
  16032. }
  16033. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16034. importMeshFromData(data);
  16035. }, progressCallBack, database);
  16036. };
  16037. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16038. };
  16039. /**
  16040. * Load a scene
  16041. * @param rootUrl a string that defines the root url for scene and resources
  16042. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16043. * @param engine is the instance of BABYLON.Engine to use to create the scene
  16044. */
  16045. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  16046. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  16047. };
  16048. /**
  16049. * Append a scene
  16050. * @param rootUrl a string that defines the root url for scene and resources
  16051. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16052. * @param scene is the instance of BABYLON.Scene to append to
  16053. */
  16054. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16055. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  16056. var database;
  16057. if (SceneLoader.ShowLoadingScreen) {
  16058. scene.getEngine().displayLoadingUI();
  16059. }
  16060. var loadSceneFromData = function (data) {
  16061. scene.database = database;
  16062. if (!plugin.load(scene, data, rootUrl)) {
  16063. if (onerror) {
  16064. onerror(scene);
  16065. }
  16066. scene.getEngine().hideLoadingUI();
  16067. return;
  16068. }
  16069. if (onsuccess) {
  16070. onsuccess(scene);
  16071. }
  16072. if (SceneLoader.ShowLoadingScreen) {
  16073. scene.executeWhenReady(function () {
  16074. scene.getEngine().hideLoadingUI();
  16075. });
  16076. }
  16077. };
  16078. var manifestChecked = function (success) {
  16079. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  16080. };
  16081. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16082. loadSceneFromData(sceneFilename.substr(5));
  16083. return;
  16084. }
  16085. if (rootUrl.indexOf("file:") === -1) {
  16086. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16087. } else {
  16088. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  16089. }
  16090. };
  16091. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  16092. SceneLoader._ShowLoadingScreen = true;
  16093. SceneLoader._registeredPlugins = new Array();
  16094. return SceneLoader;
  16095. })();
  16096. BABYLON.SceneLoader = SceneLoader;
  16097. ;
  16098. })(BABYLON || (BABYLON = {}));
  16099. var BABYLON;
  16100. (function (BABYLON) {
  16101. (function (Internals) {
  16102. var checkColors4 = function (colors, count) {
  16103. if (colors.length === count * 3) {
  16104. var colors4 = [];
  16105. for (var index = 0; index < colors.length; index += 3) {
  16106. var newIndex = (index / 3) * 4;
  16107. colors4[newIndex] = colors[index];
  16108. colors4[newIndex + 1] = colors[index + 1];
  16109. colors4[newIndex + 2] = colors[index + 2];
  16110. colors4[newIndex + 3] = 1.0;
  16111. }
  16112. return colors4;
  16113. }
  16114. return colors;
  16115. };
  16116. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  16117. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  16118. texture.name = parsedTexture.name;
  16119. texture.hasAlpha = parsedTexture.hasAlpha;
  16120. texture.level = parsedTexture.level;
  16121. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16122. return texture;
  16123. };
  16124. var loadTexture = function (rootUrl, parsedTexture, scene) {
  16125. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16126. return null;
  16127. }
  16128. if (parsedTexture.isCube) {
  16129. return loadCubeTexture(rootUrl, parsedTexture, scene);
  16130. }
  16131. var texture;
  16132. if (parsedTexture.mirrorPlane) {
  16133. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16134. texture._waitingRenderList = parsedTexture.renderList;
  16135. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  16136. } else if (parsedTexture.isRenderTarget) {
  16137. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16138. texture._waitingRenderList = parsedTexture.renderList;
  16139. } else {
  16140. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  16141. }
  16142. texture.name = parsedTexture.name;
  16143. texture.hasAlpha = parsedTexture.hasAlpha;
  16144. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  16145. texture.level = parsedTexture.level;
  16146. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  16147. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16148. texture.uOffset = parsedTexture.uOffset;
  16149. texture.vOffset = parsedTexture.vOffset;
  16150. texture.uScale = parsedTexture.uScale;
  16151. texture.vScale = parsedTexture.vScale;
  16152. texture.uAng = parsedTexture.uAng;
  16153. texture.vAng = parsedTexture.vAng;
  16154. texture.wAng = parsedTexture.wAng;
  16155. texture.wrapU = parsedTexture.wrapU;
  16156. texture.wrapV = parsedTexture.wrapV;
  16157. if (parsedTexture.animations) {
  16158. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  16159. var parsedAnimation = parsedTexture.animations[animationIndex];
  16160. texture.animations.push(parseAnimation(parsedAnimation));
  16161. }
  16162. }
  16163. return texture;
  16164. };
  16165. var parseSkeleton = function (parsedSkeleton, scene) {
  16166. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  16167. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  16168. var parsedBone = parsedSkeleton.bones[index];
  16169. var parentBone = null;
  16170. if (parsedBone.parentBoneIndex > -1) {
  16171. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  16172. }
  16173. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  16174. if (parsedBone.animation) {
  16175. bone.animations.push(parseAnimation(parsedBone.animation));
  16176. }
  16177. }
  16178. return skeleton;
  16179. };
  16180. var parseFresnelParameters = function (parsedFresnelParameters) {
  16181. var fresnelParameters = new BABYLON.FresnelParameters();
  16182. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  16183. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  16184. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  16185. fresnelParameters.bias = parsedFresnelParameters.bias;
  16186. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  16187. return fresnelParameters;
  16188. };
  16189. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  16190. var material;
  16191. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  16192. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  16193. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  16194. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  16195. material.specularPower = parsedMaterial.specularPower;
  16196. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  16197. material.alpha = parsedMaterial.alpha;
  16198. material.id = parsedMaterial.id;
  16199. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  16200. material.backFaceCulling = parsedMaterial.backFaceCulling;
  16201. material.wireframe = parsedMaterial.wireframe;
  16202. if (parsedMaterial.diffuseTexture) {
  16203. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  16204. }
  16205. if (parsedMaterial.diffuseFresnelParameters) {
  16206. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  16207. }
  16208. if (parsedMaterial.ambientTexture) {
  16209. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  16210. }
  16211. if (parsedMaterial.opacityTexture) {
  16212. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  16213. }
  16214. if (parsedMaterial.opacityFresnelParameters) {
  16215. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  16216. }
  16217. if (parsedMaterial.reflectionTexture) {
  16218. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  16219. }
  16220. if (parsedMaterial.reflectionFresnelParameters) {
  16221. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  16222. }
  16223. if (parsedMaterial.emissiveTexture) {
  16224. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  16225. }
  16226. if (parsedMaterial.emissiveFresnelParameters) {
  16227. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  16228. }
  16229. if (parsedMaterial.specularTexture) {
  16230. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  16231. }
  16232. if (parsedMaterial.bumpTexture) {
  16233. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  16234. }
  16235. return material;
  16236. };
  16237. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  16238. for (var index = 0; index < parsedData.materials.length; index++) {
  16239. var parsedMaterial = parsedData.materials[index];
  16240. if (parsedMaterial.id === id) {
  16241. return parseMaterial(parsedMaterial, scene, rootUrl);
  16242. }
  16243. }
  16244. return null;
  16245. };
  16246. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  16247. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  16248. multiMaterial.id = parsedMultiMaterial.id;
  16249. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  16250. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16251. var subMatId = parsedMultiMaterial.materials[matIndex];
  16252. if (subMatId) {
  16253. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  16254. } else {
  16255. multiMaterial.subMaterials.push(null);
  16256. }
  16257. }
  16258. return multiMaterial;
  16259. };
  16260. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  16261. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  16262. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  16263. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  16264. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  16265. var parsedFlare = parsedLensFlareSystem.flares[index];
  16266. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  16267. }
  16268. return lensFlareSystem;
  16269. };
  16270. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  16271. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  16272. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  16273. if (parsedParticleSystem.textureName) {
  16274. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  16275. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  16276. }
  16277. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  16278. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  16279. particleSystem.minSize = parsedParticleSystem.minSize;
  16280. particleSystem.maxSize = parsedParticleSystem.maxSize;
  16281. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  16282. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  16283. particleSystem.emitter = emitter;
  16284. particleSystem.emitRate = parsedParticleSystem.emitRate;
  16285. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  16286. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  16287. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  16288. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  16289. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  16290. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  16291. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  16292. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  16293. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  16294. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  16295. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  16296. particleSystem.blendMode = parsedParticleSystem.blendMode;
  16297. particleSystem.start();
  16298. return particleSystem;
  16299. };
  16300. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  16301. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  16302. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  16303. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  16304. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  16305. shadowGenerator.getShadowMap().renderList.push(mesh);
  16306. }
  16307. if (parsedShadowGenerator.usePoissonSampling) {
  16308. shadowGenerator.usePoissonSampling = true;
  16309. } else {
  16310. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  16311. }
  16312. return shadowGenerator;
  16313. };
  16314. var parseAnimation = function (parsedAnimation) {
  16315. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  16316. var dataType = parsedAnimation.dataType;
  16317. var keys = [];
  16318. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  16319. var key = parsedAnimation.keys[index];
  16320. var data;
  16321. switch (dataType) {
  16322. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16323. data = key.values[0];
  16324. break;
  16325. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16326. data = BABYLON.Quaternion.FromArray(key.values);
  16327. break;
  16328. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16329. data = BABYLON.Matrix.FromArray(key.values);
  16330. break;
  16331. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16332. default:
  16333. data = BABYLON.Vector3.FromArray(key.values);
  16334. break;
  16335. }
  16336. keys.push({
  16337. frame: key.frame,
  16338. value: data
  16339. });
  16340. }
  16341. animation.setKeys(keys);
  16342. return animation;
  16343. };
  16344. var parseLight = function (parsedLight, scene) {
  16345. var light;
  16346. switch (parsedLight.type) {
  16347. case 0:
  16348. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  16349. break;
  16350. case 1:
  16351. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16352. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  16353. break;
  16354. case 2:
  16355. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  16356. break;
  16357. case 3:
  16358. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  16359. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  16360. break;
  16361. }
  16362. light.id = parsedLight.id;
  16363. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  16364. if (parsedLight.intensity !== undefined) {
  16365. light.intensity = parsedLight.intensity;
  16366. }
  16367. if (parsedLight.range) {
  16368. light.range = parsedLight.range;
  16369. }
  16370. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  16371. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  16372. if (parsedLight.excludedMeshesIds) {
  16373. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16374. }
  16375. if (parsedLight.parentId) {
  16376. light._waitingParentId = parsedLight.parentId;
  16377. }
  16378. if (parsedLight.includedOnlyMeshesIds) {
  16379. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16380. }
  16381. if (parsedLight.animations) {
  16382. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16383. var parsedAnimation = parsedLight.animations[animationIndex];
  16384. light.animations.push(parseAnimation(parsedAnimation));
  16385. }
  16386. }
  16387. if (parsedLight.autoAnimate) {
  16388. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  16389. }
  16390. };
  16391. var parseCamera = function (parsedCamera, scene) {
  16392. var camera;
  16393. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  16394. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  16395. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  16396. var alpha = parsedCamera.alpha;
  16397. var beta = parsedCamera.beta;
  16398. var radius = parsedCamera.radius;
  16399. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  16400. var eye_space = parsedCamera.eye_space;
  16401. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  16402. } else {
  16403. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  16404. }
  16405. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  16406. var eye_space = parsedCamera.eye_space;
  16407. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  16408. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  16409. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  16410. } else if (parsedCamera.type === "FollowCamera") {
  16411. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  16412. camera.heightOffset = parsedCamera.heightOffset;
  16413. camera.radius = parsedCamera.radius;
  16414. camera.rotationOffset = parsedCamera.rotationOffset;
  16415. if (lockedTargetMesh)
  16416. camera.target = lockedTargetMesh;
  16417. } else if (parsedCamera.type === "GamepadCamera") {
  16418. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  16419. } else if (parsedCamera.type === "OculusCamera") {
  16420. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  16421. } else if (parsedCamera.type === "TouchCamera") {
  16422. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  16423. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  16424. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  16425. } else if (parsedCamera.type === "WebVRCamera") {
  16426. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  16427. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  16428. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  16429. } else {
  16430. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  16431. }
  16432. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  16433. camera.lockedTarget = lockedTargetMesh;
  16434. }
  16435. camera.id = parsedCamera.id;
  16436. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  16437. if (parsedCamera.parentId) {
  16438. camera._waitingParentId = parsedCamera.parentId;
  16439. }
  16440. if (parsedCamera.target) {
  16441. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16442. } else {
  16443. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  16444. }
  16445. camera.fov = parsedCamera.fov;
  16446. camera.minZ = parsedCamera.minZ;
  16447. camera.maxZ = parsedCamera.maxZ;
  16448. camera.speed = parsedCamera.speed;
  16449. camera.inertia = parsedCamera.inertia;
  16450. camera.checkCollisions = parsedCamera.checkCollisions;
  16451. camera.applyGravity = parsedCamera.applyGravity;
  16452. if (parsedCamera.ellipsoid) {
  16453. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  16454. }
  16455. if (parsedCamera.animations) {
  16456. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16457. var parsedAnimation = parsedCamera.animations[animationIndex];
  16458. camera.animations.push(parseAnimation(parsedAnimation));
  16459. }
  16460. }
  16461. if (parsedCamera.autoAnimate) {
  16462. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  16463. }
  16464. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  16465. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  16466. } else {
  16467. camera.layerMask = 0xFFFFFFFF;
  16468. }
  16469. return camera;
  16470. };
  16471. var parseGeometry = function (parsedGeometry, scene) {
  16472. var id = parsedGeometry.id;
  16473. return scene.getGeometryByID(id);
  16474. };
  16475. var parseBox = function (parsedBox, scene) {
  16476. if (parseGeometry(parsedBox, scene)) {
  16477. return null;
  16478. }
  16479. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  16480. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  16481. scene.pushGeometry(box, true);
  16482. return box;
  16483. };
  16484. var parseSphere = function (parsedSphere, scene) {
  16485. if (parseGeometry(parsedSphere, scene)) {
  16486. return null;
  16487. }
  16488. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  16489. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  16490. scene.pushGeometry(sphere, true);
  16491. return sphere;
  16492. };
  16493. var parseCylinder = function (parsedCylinder, scene) {
  16494. if (parseGeometry(parsedCylinder, scene)) {
  16495. return null;
  16496. }
  16497. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  16498. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  16499. scene.pushGeometry(cylinder, true);
  16500. return cylinder;
  16501. };
  16502. var parseTorus = function (parsedTorus, scene) {
  16503. if (parseGeometry(parsedTorus, scene)) {
  16504. return null;
  16505. }
  16506. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  16507. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  16508. scene.pushGeometry(torus, true);
  16509. return torus;
  16510. };
  16511. var parseGround = function (parsedGround, scene) {
  16512. if (parseGeometry(parsedGround, scene)) {
  16513. return null;
  16514. }
  16515. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  16516. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  16517. scene.pushGeometry(ground, true);
  16518. return ground;
  16519. };
  16520. var parsePlane = function (parsedPlane, scene) {
  16521. if (parseGeometry(parsedPlane, scene)) {
  16522. return null;
  16523. }
  16524. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  16525. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  16526. scene.pushGeometry(plane, true);
  16527. return plane;
  16528. };
  16529. var parseTorusKnot = function (parsedTorusKnot, scene) {
  16530. if (parseGeometry(parsedTorusKnot, scene)) {
  16531. return null;
  16532. }
  16533. 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);
  16534. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  16535. scene.pushGeometry(torusKnot, true);
  16536. return torusKnot;
  16537. };
  16538. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  16539. if (parseGeometry(parsedVertexData, scene)) {
  16540. return null;
  16541. }
  16542. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  16543. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  16544. if (parsedVertexData.delayLoadingFile) {
  16545. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16546. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  16547. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  16548. geometry._delayInfo = [];
  16549. if (parsedVertexData.hasUVs) {
  16550. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16551. }
  16552. if (parsedVertexData.hasUVs2) {
  16553. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16554. }
  16555. if (parsedVertexData.hasColors) {
  16556. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16557. }
  16558. if (parsedVertexData.hasMatricesIndices) {
  16559. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16560. }
  16561. if (parsedVertexData.hasMatricesWeights) {
  16562. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16563. }
  16564. geometry._delayLoadingFunction = importVertexData;
  16565. } else {
  16566. importVertexData(parsedVertexData, geometry);
  16567. }
  16568. scene.pushGeometry(geometry, true);
  16569. return geometry;
  16570. };
  16571. var parseMesh = function (parsedMesh, scene, rootUrl) {
  16572. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  16573. mesh.id = parsedMesh.id;
  16574. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16575. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16576. if (parsedMesh.rotationQuaternion) {
  16577. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16578. } else if (parsedMesh.rotation) {
  16579. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16580. }
  16581. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16582. if (parsedMesh.localMatrix) {
  16583. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16584. } else if (parsedMesh.pivotMatrix) {
  16585. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16586. }
  16587. mesh.setEnabled(parsedMesh.isEnabled);
  16588. mesh.isVisible = parsedMesh.isVisible;
  16589. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16590. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16591. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16592. if (parsedMesh.pickable !== undefined) {
  16593. mesh.isPickable = parsedMesh.pickable;
  16594. }
  16595. mesh.receiveShadows = parsedMesh.receiveShadows;
  16596. mesh.billboardMode = parsedMesh.billboardMode;
  16597. if (parsedMesh.visibility !== undefined) {
  16598. mesh.visibility = parsedMesh.visibility;
  16599. }
  16600. mesh.checkCollisions = parsedMesh.checkCollisions;
  16601. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16602. if (parsedMesh.parentId) {
  16603. mesh._waitingParentId = parsedMesh.parentId;
  16604. }
  16605. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16606. if (parsedMesh.delayLoadingFile) {
  16607. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16608. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16609. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16610. if (parsedMesh._binaryInfo) {
  16611. mesh._binaryInfo = parsedMesh._binaryInfo;
  16612. }
  16613. mesh._delayInfo = [];
  16614. if (parsedMesh.hasUVs) {
  16615. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16616. }
  16617. if (parsedMesh.hasUVs2) {
  16618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16619. }
  16620. if (parsedMesh.hasColors) {
  16621. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16622. }
  16623. if (parsedMesh.hasMatricesIndices) {
  16624. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16625. }
  16626. if (parsedMesh.hasMatricesWeights) {
  16627. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16628. }
  16629. mesh._delayLoadingFunction = importGeometry;
  16630. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16631. mesh._checkDelayState();
  16632. }
  16633. } else {
  16634. importGeometry(parsedMesh, mesh);
  16635. }
  16636. if (parsedMesh.materialId) {
  16637. mesh.setMaterialByID(parsedMesh.materialId);
  16638. } else {
  16639. mesh.material = null;
  16640. }
  16641. if (parsedMesh.skeletonId > -1) {
  16642. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16643. }
  16644. if (parsedMesh.physicsImpostor) {
  16645. if (!scene.isPhysicsEnabled()) {
  16646. scene.enablePhysics();
  16647. }
  16648. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16649. }
  16650. if (parsedMesh.animations) {
  16651. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16652. var parsedAnimation = parsedMesh.animations[animationIndex];
  16653. mesh.animations.push(parseAnimation(parsedAnimation));
  16654. }
  16655. }
  16656. if (parsedMesh.autoAnimate) {
  16657. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16658. }
  16659. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16660. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16661. } else {
  16662. mesh.layerMask = 0xFFFFFFFF;
  16663. }
  16664. if (parsedMesh.instances) {
  16665. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16666. var parsedInstance = parsedMesh.instances[index];
  16667. var instance = mesh.createInstance(parsedInstance.name);
  16668. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16669. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16670. if (parsedInstance.rotationQuaternion) {
  16671. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16672. } else if (parsedInstance.rotation) {
  16673. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16674. }
  16675. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16676. instance.checkCollisions = mesh.checkCollisions;
  16677. if (parsedMesh.animations) {
  16678. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16679. parsedAnimation = parsedMesh.animations[animationIndex];
  16680. instance.animations.push(parseAnimation(parsedAnimation));
  16681. }
  16682. }
  16683. }
  16684. }
  16685. return mesh;
  16686. };
  16687. var isDescendantOf = function (mesh, names, hierarchyIds) {
  16688. names = (names instanceof Array) ? names : [names];
  16689. for (var i in names) {
  16690. if (mesh.name === names[i]) {
  16691. hierarchyIds.push(mesh.id);
  16692. return true;
  16693. }
  16694. }
  16695. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  16696. hierarchyIds.push(mesh.id);
  16697. return true;
  16698. }
  16699. return false;
  16700. };
  16701. var importVertexData = function (parsedVertexData, geometry) {
  16702. var vertexData = new BABYLON.VertexData();
  16703. var positions = parsedVertexData.positions;
  16704. if (positions) {
  16705. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  16706. }
  16707. var normals = parsedVertexData.normals;
  16708. if (normals) {
  16709. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  16710. }
  16711. var uvs = parsedVertexData.uvs;
  16712. if (uvs) {
  16713. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  16714. }
  16715. var uv2s = parsedVertexData.uv2s;
  16716. if (uv2s) {
  16717. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  16718. }
  16719. var colors = parsedVertexData.colors;
  16720. if (colors) {
  16721. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  16722. }
  16723. var matricesIndices = parsedVertexData.matricesIndices;
  16724. if (matricesIndices) {
  16725. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  16726. }
  16727. var matricesWeights = parsedVertexData.matricesWeights;
  16728. if (matricesWeights) {
  16729. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  16730. }
  16731. var indices = parsedVertexData.indices;
  16732. if (indices) {
  16733. vertexData.indices = indices;
  16734. }
  16735. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  16736. };
  16737. var importGeometry = function (parsedGeometry, mesh) {
  16738. var scene = mesh.getScene();
  16739. var geometryId = parsedGeometry.geometryId;
  16740. if (geometryId) {
  16741. var geometry = scene.getGeometryByID(geometryId);
  16742. if (geometry) {
  16743. geometry.applyToMesh(mesh);
  16744. }
  16745. } else if (parsedGeometry instanceof ArrayBuffer) {
  16746. var binaryInfo = mesh._binaryInfo;
  16747. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  16748. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  16749. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  16750. }
  16751. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  16752. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  16753. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  16754. }
  16755. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  16756. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  16757. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  16758. }
  16759. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  16760. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  16761. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  16762. }
  16763. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  16764. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  16765. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  16766. }
  16767. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  16768. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  16769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  16770. }
  16771. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  16772. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  16773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  16774. }
  16775. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  16776. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  16777. mesh.setIndices(indicesData);
  16778. }
  16779. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  16780. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  16781. mesh.subMeshes = [];
  16782. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  16783. var materialIndex = subMeshesData[(i * 5) + 0];
  16784. var verticesStart = subMeshesData[(i * 5) + 1];
  16785. var verticesCount = subMeshesData[(i * 5) + 2];
  16786. var indexStart = subMeshesData[(i * 5) + 3];
  16787. var indexCount = subMeshesData[(i * 5) + 4];
  16788. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  16789. }
  16790. }
  16791. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  16792. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  16793. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  16794. if (parsedGeometry.uvs) {
  16795. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  16796. }
  16797. if (parsedGeometry.uvs2) {
  16798. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  16799. }
  16800. if (parsedGeometry.colors) {
  16801. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  16802. }
  16803. if (parsedGeometry.matricesIndices) {
  16804. if (!parsedGeometry.matricesIndices._isExpanded) {
  16805. var floatIndices = [];
  16806. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  16807. var matricesIndex = parsedGeometry.matricesIndices[i];
  16808. floatIndices.push(matricesIndex & 0x000000FF);
  16809. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  16810. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  16811. floatIndices.push(matricesIndex >> 24);
  16812. }
  16813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  16814. } else {
  16815. delete parsedGeometry.matricesIndices._isExpanded;
  16816. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  16817. }
  16818. }
  16819. if (parsedGeometry.matricesWeights) {
  16820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  16821. }
  16822. mesh.setIndices(parsedGeometry.indices);
  16823. if (parsedGeometry.subMeshes) {
  16824. mesh.subMeshes = [];
  16825. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  16826. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  16827. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  16828. }
  16829. }
  16830. }
  16831. if (mesh._shouldGenerateFlatShading) {
  16832. mesh.convertToFlatShadedMesh();
  16833. delete mesh._shouldGenerateFlatShading;
  16834. }
  16835. mesh.computeWorldMatrix(true);
  16836. if (scene._selectionOctree) {
  16837. scene._selectionOctree.addMesh(mesh);
  16838. }
  16839. };
  16840. BABYLON.SceneLoader.RegisterPlugin({
  16841. extensions: ".babylon",
  16842. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  16843. var parsedData = JSON.parse(data);
  16844. var loadedSkeletonsIds = [];
  16845. var loadedMaterialsIds = [];
  16846. var hierarchyIds = [];
  16847. for (var index = 0; index < parsedData.meshes.length; index++) {
  16848. var parsedMesh = parsedData.meshes[index];
  16849. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  16850. if (meshesNames instanceof Array) {
  16851. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  16852. }
  16853. if (parsedMesh.materialId) {
  16854. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  16855. if (!materialFound) {
  16856. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  16857. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  16858. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  16859. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  16860. var subMatId = parsedMultiMaterial.materials[matIndex];
  16861. loadedMaterialsIds.push(subMatId);
  16862. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  16863. }
  16864. loadedMaterialsIds.push(parsedMultiMaterial.id);
  16865. parseMultiMaterial(parsedMultiMaterial, scene);
  16866. materialFound = true;
  16867. break;
  16868. }
  16869. }
  16870. }
  16871. if (!materialFound) {
  16872. loadedMaterialsIds.push(parsedMesh.materialId);
  16873. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  16874. }
  16875. }
  16876. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  16877. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  16878. if (!skeletonAlreadyLoaded) {
  16879. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  16880. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  16881. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  16882. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  16883. loadedSkeletonsIds.push(parsedSkeleton.id);
  16884. }
  16885. }
  16886. }
  16887. }
  16888. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  16889. meshes.push(mesh);
  16890. }
  16891. }
  16892. for (index = 0; index < scene.meshes.length; index++) {
  16893. var currentMesh = scene.meshes[index];
  16894. if (currentMesh._waitingParentId) {
  16895. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  16896. currentMesh._waitingParentId = undefined;
  16897. }
  16898. }
  16899. if (parsedData.particleSystems) {
  16900. for (index = 0; index < parsedData.particleSystems.length; index++) {
  16901. var parsedParticleSystem = parsedData.particleSystems[index];
  16902. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  16903. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  16904. }
  16905. }
  16906. }
  16907. return true;
  16908. },
  16909. load: function (scene, data, rootUrl) {
  16910. var parsedData = JSON.parse(data);
  16911. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  16912. scene.autoClear = parsedData.autoClear;
  16913. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  16914. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  16915. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  16916. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  16917. scene.fogMode = parsedData.fogMode;
  16918. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  16919. scene.fogStart = parsedData.fogStart;
  16920. scene.fogEnd = parsedData.fogEnd;
  16921. scene.fogDensity = parsedData.fogDensity;
  16922. }
  16923. for (var index = 0; index < parsedData.lights.length; index++) {
  16924. var parsedLight = parsedData.lights[index];
  16925. parseLight(parsedLight, scene);
  16926. }
  16927. if (parsedData.materials) {
  16928. for (index = 0; index < parsedData.materials.length; index++) {
  16929. var parsedMaterial = parsedData.materials[index];
  16930. parseMaterial(parsedMaterial, scene, rootUrl);
  16931. }
  16932. }
  16933. if (parsedData.multiMaterials) {
  16934. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  16935. var parsedMultiMaterial = parsedData.multiMaterials[index];
  16936. parseMultiMaterial(parsedMultiMaterial, scene);
  16937. }
  16938. }
  16939. if (parsedData.skeletons) {
  16940. for (index = 0; index < parsedData.skeletons.length; index++) {
  16941. var parsedSkeleton = parsedData.skeletons[index];
  16942. parseSkeleton(parsedSkeleton, scene);
  16943. }
  16944. }
  16945. var geometries = parsedData.geometries;
  16946. if (geometries) {
  16947. var boxes = geometries.boxes;
  16948. if (boxes) {
  16949. for (index = 0; index < boxes.length; index++) {
  16950. var parsedBox = boxes[index];
  16951. parseBox(parsedBox, scene);
  16952. }
  16953. }
  16954. var spheres = geometries.spheres;
  16955. if (spheres) {
  16956. for (index = 0; index < spheres.length; index++) {
  16957. var parsedSphere = spheres[index];
  16958. parseSphere(parsedSphere, scene);
  16959. }
  16960. }
  16961. var cylinders = geometries.cylinders;
  16962. if (cylinders) {
  16963. for (index = 0; index < cylinders.length; index++) {
  16964. var parsedCylinder = cylinders[index];
  16965. parseCylinder(parsedCylinder, scene);
  16966. }
  16967. }
  16968. var toruses = geometries.toruses;
  16969. if (toruses) {
  16970. for (index = 0; index < toruses.length; index++) {
  16971. var parsedTorus = toruses[index];
  16972. parseTorus(parsedTorus, scene);
  16973. }
  16974. }
  16975. var grounds = geometries.grounds;
  16976. if (grounds) {
  16977. for (index = 0; index < grounds.length; index++) {
  16978. var parsedGround = grounds[index];
  16979. parseGround(parsedGround, scene);
  16980. }
  16981. }
  16982. var planes = geometries.planes;
  16983. if (planes) {
  16984. for (index = 0; index < planes.length; index++) {
  16985. var parsedPlane = planes[index];
  16986. parsePlane(parsedPlane, scene);
  16987. }
  16988. }
  16989. var torusKnots = geometries.torusKnots;
  16990. if (torusKnots) {
  16991. for (index = 0; index < torusKnots.length; index++) {
  16992. var parsedTorusKnot = torusKnots[index];
  16993. parseTorusKnot(parsedTorusKnot, scene);
  16994. }
  16995. }
  16996. var vertexData = geometries.vertexData;
  16997. if (vertexData) {
  16998. for (index = 0; index < vertexData.length; index++) {
  16999. var parsedVertexData = vertexData[index];
  17000. parseVertexData(parsedVertexData, scene, rootUrl);
  17001. }
  17002. }
  17003. }
  17004. for (index = 0; index < parsedData.meshes.length; index++) {
  17005. var parsedMesh = parsedData.meshes[index];
  17006. parseMesh(parsedMesh, scene, rootUrl);
  17007. }
  17008. for (index = 0; index < parsedData.cameras.length; index++) {
  17009. var parsedCamera = parsedData.cameras[index];
  17010. parseCamera(parsedCamera, scene);
  17011. }
  17012. if (parsedData.activeCameraID) {
  17013. scene.setActiveCameraByID(parsedData.activeCameraID);
  17014. }
  17015. for (index = 0; index < scene.cameras.length; index++) {
  17016. var camera = scene.cameras[index];
  17017. if (camera._waitingParentId) {
  17018. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  17019. camera._waitingParentId = undefined;
  17020. }
  17021. }
  17022. for (index = 0; index < scene.lights.length; index++) {
  17023. var light = scene.lights[index];
  17024. if (light._waitingParentId) {
  17025. light.parent = scene.getLastEntryByID(light._waitingParentId);
  17026. light._waitingParentId = undefined;
  17027. }
  17028. }
  17029. for (index = 0; index < scene.meshes.length; index++) {
  17030. var mesh = scene.meshes[index];
  17031. if (mesh._waitingParentId) {
  17032. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  17033. mesh._waitingParentId = undefined;
  17034. }
  17035. }
  17036. if (parsedData.particleSystems) {
  17037. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17038. var parsedParticleSystem = parsedData.particleSystems[index];
  17039. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  17040. }
  17041. }
  17042. if (parsedData.lensFlareSystems) {
  17043. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  17044. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  17045. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  17046. }
  17047. }
  17048. if (parsedData.shadowGenerators) {
  17049. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  17050. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  17051. parseShadowGenerator(parsedShadowGenerator, scene);
  17052. }
  17053. }
  17054. return true;
  17055. }
  17056. });
  17057. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17058. var Internals = BABYLON.Internals;
  17059. })(BABYLON || (BABYLON = {}));
  17060. var BABYLON;
  17061. (function (BABYLON) {
  17062. var currentCSGMeshId = 0;
  17063. var Vertex = (function () {
  17064. function Vertex(pos, normal, uv) {
  17065. this.pos = pos;
  17066. this.normal = normal;
  17067. this.uv = uv;
  17068. }
  17069. Vertex.prototype.clone = function () {
  17070. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  17071. };
  17072. Vertex.prototype.flip = function () {
  17073. this.normal = this.normal.scale(-1);
  17074. };
  17075. Vertex.prototype.interpolate = function (other, t) {
  17076. 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));
  17077. };
  17078. return Vertex;
  17079. })();
  17080. var Plane = (function () {
  17081. function Plane(normal, w) {
  17082. this.normal = normal;
  17083. this.w = w;
  17084. }
  17085. Plane.FromPoints = function (a, b, c) {
  17086. var v0 = c.subtract(a);
  17087. var v1 = b.subtract(a);
  17088. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  17089. return null;
  17090. }
  17091. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  17092. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  17093. };
  17094. Plane.prototype.clone = function () {
  17095. return new Plane(this.normal.clone(), this.w);
  17096. };
  17097. Plane.prototype.flip = function () {
  17098. this.normal.scaleInPlace(-1);
  17099. this.w = -this.w;
  17100. };
  17101. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  17102. var COPLANAR = 0;
  17103. var FRONT = 1;
  17104. var BACK = 2;
  17105. var SPANNING = 3;
  17106. var polygonType = 0;
  17107. var types = [];
  17108. for (var i = 0; i < polygon.vertices.length; i++) {
  17109. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  17110. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  17111. polygonType |= type;
  17112. types.push(type);
  17113. }
  17114. switch (polygonType) {
  17115. case COPLANAR:
  17116. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  17117. break;
  17118. case FRONT:
  17119. front.push(polygon);
  17120. break;
  17121. case BACK:
  17122. back.push(polygon);
  17123. break;
  17124. case SPANNING:
  17125. var f = [], b = [];
  17126. for (i = 0; i < polygon.vertices.length; i++) {
  17127. var j = (i + 1) % polygon.vertices.length;
  17128. var ti = types[i], tj = types[j];
  17129. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  17130. if (ti != BACK)
  17131. f.push(vi);
  17132. if (ti != FRONT)
  17133. b.push(ti != BACK ? vi.clone() : vi);
  17134. if ((ti | tj) == SPANNING) {
  17135. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  17136. var v = vi.interpolate(vj, t);
  17137. f.push(v);
  17138. b.push(v.clone());
  17139. }
  17140. }
  17141. if (f.length >= 3) {
  17142. var poly = new Polygon(f, polygon.shared);
  17143. if (poly.plane)
  17144. front.push(poly);
  17145. }
  17146. if (b.length >= 3) {
  17147. poly = new Polygon(b, polygon.shared);
  17148. if (poly.plane)
  17149. back.push(poly);
  17150. }
  17151. break;
  17152. }
  17153. };
  17154. Plane.EPSILON = 1e-5;
  17155. return Plane;
  17156. })();
  17157. var Polygon = (function () {
  17158. function Polygon(vertices, shared) {
  17159. this.vertices = vertices;
  17160. this.shared = shared;
  17161. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  17162. }
  17163. Polygon.prototype.clone = function () {
  17164. var vertices = this.vertices.map(function (v) {
  17165. return v.clone();
  17166. });
  17167. return new Polygon(vertices, this.shared);
  17168. };
  17169. Polygon.prototype.flip = function () {
  17170. this.vertices.reverse().map(function (v) {
  17171. v.flip();
  17172. });
  17173. this.plane.flip();
  17174. };
  17175. return Polygon;
  17176. })();
  17177. var Node = (function () {
  17178. function Node(polygons) {
  17179. this.plane = null;
  17180. this.front = null;
  17181. this.back = null;
  17182. this.polygons = [];
  17183. if (polygons) {
  17184. this.build(polygons);
  17185. }
  17186. }
  17187. Node.prototype.clone = function () {
  17188. var node = new Node();
  17189. node.plane = this.plane && this.plane.clone();
  17190. node.front = this.front && this.front.clone();
  17191. node.back = this.back && this.back.clone();
  17192. node.polygons = this.polygons.map(function (p) {
  17193. return p.clone();
  17194. });
  17195. return node;
  17196. };
  17197. Node.prototype.invert = function () {
  17198. for (var i = 0; i < this.polygons.length; i++) {
  17199. this.polygons[i].flip();
  17200. }
  17201. if (this.plane) {
  17202. this.plane.flip();
  17203. }
  17204. if (this.front) {
  17205. this.front.invert();
  17206. }
  17207. if (this.back) {
  17208. this.back.invert();
  17209. }
  17210. var temp = this.front;
  17211. this.front = this.back;
  17212. this.back = temp;
  17213. };
  17214. Node.prototype.clipPolygons = function (polygons) {
  17215. if (!this.plane)
  17216. return polygons.slice();
  17217. var front = [], back = [];
  17218. for (var i = 0; i < polygons.length; i++) {
  17219. this.plane.splitPolygon(polygons[i], front, back, front, back);
  17220. }
  17221. if (this.front) {
  17222. front = this.front.clipPolygons(front);
  17223. }
  17224. if (this.back) {
  17225. back = this.back.clipPolygons(back);
  17226. } else {
  17227. back = [];
  17228. }
  17229. return front.concat(back);
  17230. };
  17231. Node.prototype.clipTo = function (bsp) {
  17232. this.polygons = bsp.clipPolygons(this.polygons);
  17233. if (this.front)
  17234. this.front.clipTo(bsp);
  17235. if (this.back)
  17236. this.back.clipTo(bsp);
  17237. };
  17238. Node.prototype.allPolygons = function () {
  17239. var polygons = this.polygons.slice();
  17240. if (this.front)
  17241. polygons = polygons.concat(this.front.allPolygons());
  17242. if (this.back)
  17243. polygons = polygons.concat(this.back.allPolygons());
  17244. return polygons;
  17245. };
  17246. Node.prototype.build = function (polygons) {
  17247. if (!polygons.length)
  17248. return;
  17249. if (!this.plane)
  17250. this.plane = polygons[0].plane.clone();
  17251. var front = [], back = [];
  17252. for (var i = 0; i < polygons.length; i++) {
  17253. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  17254. }
  17255. if (front.length) {
  17256. if (!this.front)
  17257. this.front = new Node();
  17258. this.front.build(front);
  17259. }
  17260. if (back.length) {
  17261. if (!this.back)
  17262. this.back = new Node();
  17263. this.back.build(back);
  17264. }
  17265. };
  17266. return Node;
  17267. })();
  17268. var CSG = (function () {
  17269. function CSG() {
  17270. this.polygons = new Array();
  17271. }
  17272. CSG.FromMesh = function (mesh) {
  17273. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  17274. if (mesh instanceof BABYLON.Mesh) {
  17275. mesh.computeWorldMatrix(true);
  17276. var matrix = mesh.getWorldMatrix();
  17277. var meshPosition = mesh.position.clone();
  17278. var meshRotation = mesh.rotation.clone();
  17279. var meshScaling = mesh.scaling.clone();
  17280. } else {
  17281. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  17282. }
  17283. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17284. var subMeshes = mesh.subMeshes;
  17285. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  17286. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  17287. vertices = [];
  17288. for (var j = 0; j < 3; j++) {
  17289. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  17290. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  17291. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  17292. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  17293. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  17294. vertex = new Vertex(position, normal, uv);
  17295. vertices.push(vertex);
  17296. }
  17297. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  17298. if (polygon.plane)
  17299. polygons.push(polygon);
  17300. }
  17301. }
  17302. var csg = CSG.FromPolygons(polygons);
  17303. csg.matrix = matrix;
  17304. csg.position = meshPosition;
  17305. csg.rotation = meshRotation;
  17306. csg.scaling = meshScaling;
  17307. currentCSGMeshId++;
  17308. return csg;
  17309. };
  17310. CSG.FromPolygons = function (polygons) {
  17311. var csg = new BABYLON.CSG();
  17312. csg.polygons = polygons;
  17313. return csg;
  17314. };
  17315. CSG.prototype.clone = function () {
  17316. var csg = new BABYLON.CSG();
  17317. csg.polygons = this.polygons.map(function (p) {
  17318. return p.clone();
  17319. });
  17320. csg.copyTransformAttributes(this);
  17321. return csg;
  17322. };
  17323. CSG.prototype.toPolygons = function () {
  17324. return this.polygons;
  17325. };
  17326. CSG.prototype.union = function (csg) {
  17327. var a = new Node(this.clone().polygons);
  17328. var b = new Node(csg.clone().polygons);
  17329. a.clipTo(b);
  17330. b.clipTo(a);
  17331. b.invert();
  17332. b.clipTo(a);
  17333. b.invert();
  17334. a.build(b.allPolygons());
  17335. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17336. };
  17337. CSG.prototype.unionInPlace = function (csg) {
  17338. var a = new Node(this.polygons);
  17339. var b = new Node(csg.polygons);
  17340. a.clipTo(b);
  17341. b.clipTo(a);
  17342. b.invert();
  17343. b.clipTo(a);
  17344. b.invert();
  17345. a.build(b.allPolygons());
  17346. this.polygons = a.allPolygons();
  17347. };
  17348. CSG.prototype.subtract = function (csg) {
  17349. var a = new Node(this.clone().polygons);
  17350. var b = new Node(csg.clone().polygons);
  17351. a.invert();
  17352. a.clipTo(b);
  17353. b.clipTo(a);
  17354. b.invert();
  17355. b.clipTo(a);
  17356. b.invert();
  17357. a.build(b.allPolygons());
  17358. a.invert();
  17359. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17360. };
  17361. CSG.prototype.subtractInPlace = function (csg) {
  17362. var a = new Node(this.polygons);
  17363. var b = new Node(csg.polygons);
  17364. a.invert();
  17365. a.clipTo(b);
  17366. b.clipTo(a);
  17367. b.invert();
  17368. b.clipTo(a);
  17369. b.invert();
  17370. a.build(b.allPolygons());
  17371. a.invert();
  17372. this.polygons = a.allPolygons();
  17373. };
  17374. CSG.prototype.intersect = function (csg) {
  17375. var a = new Node(this.clone().polygons);
  17376. var b = new Node(csg.clone().polygons);
  17377. a.invert();
  17378. b.clipTo(a);
  17379. b.invert();
  17380. a.clipTo(b);
  17381. b.clipTo(a);
  17382. a.build(b.allPolygons());
  17383. a.invert();
  17384. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  17385. };
  17386. CSG.prototype.intersectInPlace = function (csg) {
  17387. var a = new Node(this.polygons);
  17388. var b = new Node(csg.polygons);
  17389. a.invert();
  17390. b.clipTo(a);
  17391. b.invert();
  17392. a.clipTo(b);
  17393. b.clipTo(a);
  17394. a.build(b.allPolygons());
  17395. a.invert();
  17396. this.polygons = a.allPolygons();
  17397. };
  17398. CSG.prototype.inverse = function () {
  17399. var csg = this.clone();
  17400. csg.inverseInPlace();
  17401. return csg;
  17402. };
  17403. CSG.prototype.inverseInPlace = function () {
  17404. this.polygons.map(function (p) {
  17405. p.flip();
  17406. });
  17407. };
  17408. CSG.prototype.copyTransformAttributes = function (csg) {
  17409. this.matrix = csg.matrix;
  17410. this.position = csg.position;
  17411. this.rotation = csg.rotation;
  17412. this.scaling = csg.scaling;
  17413. return this;
  17414. };
  17415. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  17416. var matrix = this.matrix.clone();
  17417. matrix.invert();
  17418. 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;
  17419. if (keepSubMeshes) {
  17420. polygons.sort(function (a, b) {
  17421. if (a.shared.meshId === b.shared.meshId) {
  17422. return a.shared.subMeshId - b.shared.subMeshId;
  17423. } else {
  17424. return a.shared.meshId - b.shared.meshId;
  17425. }
  17426. });
  17427. }
  17428. for (var i = 0, il = polygons.length; i < il; i++) {
  17429. polygon = polygons[i];
  17430. if (!subMesh_dict[polygon.shared.meshId]) {
  17431. subMesh_dict[polygon.shared.meshId] = {};
  17432. }
  17433. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  17434. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  17435. indexStart: +Infinity,
  17436. indexEnd: -Infinity,
  17437. materialIndex: polygon.shared.materialIndex
  17438. };
  17439. }
  17440. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  17441. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  17442. polygonIndices[0] = 0;
  17443. polygonIndices[1] = j - 1;
  17444. polygonIndices[2] = j;
  17445. for (var k = 0; k < 3; k++) {
  17446. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  17447. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  17448. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  17449. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  17450. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  17451. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  17452. 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)) {
  17453. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  17454. uvs.push(uv.x, uv.y);
  17455. normals.push(normal.x, normal.y, normal.z);
  17456. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  17457. }
  17458. indices.push(vertex_idx);
  17459. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  17460. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  17461. currentIndex++;
  17462. }
  17463. }
  17464. }
  17465. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  17466. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17467. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  17468. mesh.setIndices(indices);
  17469. if (keepSubMeshes) {
  17470. var materialIndexOffset = 0, materialMaxIndex;
  17471. mesh.subMeshes.length = 0;
  17472. for (var m in subMesh_dict) {
  17473. materialMaxIndex = -1;
  17474. for (var sm in subMesh_dict[m]) {
  17475. subMesh_obj = subMesh_dict[m][sm];
  17476. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  17477. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  17478. }
  17479. materialIndexOffset += ++materialMaxIndex;
  17480. }
  17481. }
  17482. return mesh;
  17483. };
  17484. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  17485. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  17486. mesh.material = material;
  17487. mesh.position.copyFrom(this.position);
  17488. mesh.rotation.copyFrom(this.rotation);
  17489. mesh.scaling.copyFrom(this.scaling);
  17490. mesh.computeWorldMatrix(true);
  17491. return mesh;
  17492. };
  17493. return CSG;
  17494. })();
  17495. BABYLON.CSG = CSG;
  17496. })(BABYLON || (BABYLON = {}));
  17497. var __extends = this.__extends || function (d, b) {
  17498. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17499. function __() { this.constructor = d; }
  17500. __.prototype = b.prototype;
  17501. d.prototype = new __();
  17502. };
  17503. var BABYLON;
  17504. (function (BABYLON) {
  17505. var OculusDistortionCorrectionPostProcess = (function (_super) {
  17506. __extends(OculusDistortionCorrectionPostProcess, _super);
  17507. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  17508. var _this = this;
  17509. _super.call(this, name, "oculusDistortionCorrection", [
  17510. 'LensCenter',
  17511. 'Scale',
  17512. 'ScaleIn',
  17513. 'HmdWarpParam'
  17514. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  17515. this._isRightEye = isRightEye;
  17516. this._distortionFactors = cameraSettings.DistortionK;
  17517. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  17518. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  17519. this.onSizeChanged = function () {
  17520. _this.aspectRatio = _this.width * .5 / _this.height;
  17521. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  17522. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  17523. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  17524. };
  17525. this.onApply = function (effect) {
  17526. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  17527. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  17528. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  17529. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  17530. };
  17531. }
  17532. return OculusDistortionCorrectionPostProcess;
  17533. })(BABYLON.PostProcess);
  17534. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  17535. })(BABYLON || (BABYLON = {}));
  17536. var BABYLON;
  17537. (function (BABYLON) {
  17538. (function (JoystickAxis) {
  17539. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  17540. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  17541. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  17542. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  17543. var JoystickAxis = BABYLON.JoystickAxis;
  17544. var VirtualJoystick = (function () {
  17545. function VirtualJoystick(leftJoystick) {
  17546. var _this = this;
  17547. if (leftJoystick) {
  17548. this._leftJoystick = true;
  17549. } else {
  17550. this._leftJoystick = false;
  17551. }
  17552. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  17553. VirtualJoystick._globalJoystickIndex++;
  17554. this._axisTargetedByLeftAndRight = 0 /* X */;
  17555. this._axisTargetedByUpAndDown = 1 /* Y */;
  17556. this.reverseLeftRight = false;
  17557. this.reverseUpDown = false;
  17558. this._touches = new BABYLON.VirtualJoystick.Collection();
  17559. this.deltaPosition = BABYLON.Vector3.Zero();
  17560. this._joystickSensibility = 25;
  17561. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17562. this._rotationSpeed = 25;
  17563. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  17564. this._rotateOnAxisRelativeToMesh = false;
  17565. if (!VirtualJoystick.vjCanvas) {
  17566. window.addEventListener("resize", function () {
  17567. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17568. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17569. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  17570. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  17571. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  17572. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  17573. }, false);
  17574. VirtualJoystick.vjCanvas = document.createElement("canvas");
  17575. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  17576. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  17577. VirtualJoystick.vjCanvas.width = window.innerWidth;
  17578. VirtualJoystick.vjCanvas.height = window.innerHeight;
  17579. VirtualJoystick.vjCanvas.style.width = "100%";
  17580. VirtualJoystick.vjCanvas.style.height = "100%";
  17581. VirtualJoystick.vjCanvas.style.position = "absolute";
  17582. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  17583. VirtualJoystick.vjCanvas.style.top = "0px";
  17584. VirtualJoystick.vjCanvas.style.left = "0px";
  17585. VirtualJoystick.vjCanvas.style.zIndex = "5";
  17586. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  17587. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  17588. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  17589. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17590. document.body.appendChild(VirtualJoystick.vjCanvas);
  17591. }
  17592. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  17593. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  17594. this.pressed = false;
  17595. this._joystickColor = "cyan";
  17596. this._joystickPointerID = -1;
  17597. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  17598. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  17599. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  17600. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  17601. _this._onPointerDown(evt);
  17602. }, false);
  17603. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  17604. _this._onPointerMove(evt);
  17605. }, false);
  17606. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  17607. _this._onPointerUp(evt);
  17608. }, false);
  17609. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  17610. _this._onPointerUp(evt);
  17611. }, false);
  17612. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  17613. evt.preventDefault();
  17614. }, false);
  17615. requestAnimationFrame(function () {
  17616. _this._drawVirtualJoystick();
  17617. });
  17618. }
  17619. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  17620. this._joystickSensibility = newJoystickSensibility;
  17621. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  17622. };
  17623. VirtualJoystick.prototype._onPointerDown = function (e) {
  17624. var positionOnScreenCondition;
  17625. e.preventDefault();
  17626. if (this._leftJoystick === true) {
  17627. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  17628. } else {
  17629. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  17630. }
  17631. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  17632. this._joystickPointerID = e.pointerId;
  17633. this._joystickPointerStartPos.x = e.clientX;
  17634. this._joystickPointerStartPos.y = e.clientY;
  17635. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  17636. this._deltaJoystickVector.x = 0;
  17637. this._deltaJoystickVector.y = 0;
  17638. this.pressed = true;
  17639. this._touches.add(e.pointerId.toString(), e);
  17640. } else {
  17641. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  17642. this._action();
  17643. this._touches.add(e.pointerId.toString(), e);
  17644. }
  17645. }
  17646. };
  17647. VirtualJoystick.prototype._onPointerMove = function (e) {
  17648. if (this._joystickPointerID == e.pointerId) {
  17649. this._joystickPointerPos.x = e.clientX;
  17650. this._joystickPointerPos.y = e.clientY;
  17651. this._deltaJoystickVector = this._joystickPointerPos.clone();
  17652. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  17653. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  17654. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  17655. switch (this._axisTargetedByLeftAndRight) {
  17656. case 0 /* X */:
  17657. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  17658. break;
  17659. case 1 /* Y */:
  17660. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  17661. break;
  17662. case 2 /* Z */:
  17663. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  17664. break;
  17665. }
  17666. var directionUpDown = this.reverseUpDown ? 1 : -1;
  17667. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  17668. switch (this._axisTargetedByUpAndDown) {
  17669. case 0 /* X */:
  17670. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  17671. break;
  17672. case 1 /* Y */:
  17673. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  17674. break;
  17675. case 2 /* Z */:
  17676. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  17677. break;
  17678. }
  17679. } else {
  17680. if (this._touches.item(e.pointerId.toString())) {
  17681. this._touches.item(e.pointerId.toString()).x = e.clientX;
  17682. this._touches.item(e.pointerId.toString()).y = e.clientY;
  17683. }
  17684. }
  17685. };
  17686. VirtualJoystick.prototype._onPointerUp = function (e) {
  17687. this._clearCanvas();
  17688. if (this._joystickPointerID == e.pointerId) {
  17689. this._joystickPointerID = -1;
  17690. this.pressed = false;
  17691. }
  17692. this._deltaJoystickVector.x = 0;
  17693. this._deltaJoystickVector.y = 0;
  17694. this._touches.remove(e.pointerId.toString());
  17695. };
  17696. /**
  17697. * Change the color of the virtual joystick
  17698. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  17699. */
  17700. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  17701. this._joystickColor = newColor;
  17702. };
  17703. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  17704. this._action = action;
  17705. };
  17706. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  17707. switch (axis) {
  17708. case 0 /* X */:
  17709. case 1 /* Y */:
  17710. case 2 /* Z */:
  17711. this._axisTargetedByLeftAndRight = axis;
  17712. break;
  17713. default:
  17714. this._axisTargetedByLeftAndRight = 0 /* X */;
  17715. break;
  17716. }
  17717. };
  17718. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  17719. switch (axis) {
  17720. case 0 /* X */:
  17721. case 1 /* Y */:
  17722. case 2 /* Z */:
  17723. this._axisTargetedByUpAndDown = axis;
  17724. break;
  17725. default:
  17726. this._axisTargetedByUpAndDown = 1 /* Y */;
  17727. break;
  17728. }
  17729. };
  17730. VirtualJoystick.prototype._clearCanvas = function () {
  17731. if (this._leftJoystick) {
  17732. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  17733. } else {
  17734. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  17735. }
  17736. };
  17737. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  17738. var _this = this;
  17739. if (this.pressed) {
  17740. this._clearCanvas();
  17741. this._touches.forEach(function (touch) {
  17742. if (touch.pointerId === _this._joystickPointerID) {
  17743. VirtualJoystick.vjCanvasContext.beginPath();
  17744. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17745. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17746. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  17747. VirtualJoystick.vjCanvasContext.stroke();
  17748. VirtualJoystick.vjCanvasContext.beginPath();
  17749. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17750. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  17751. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  17752. VirtualJoystick.vjCanvasContext.stroke();
  17753. VirtualJoystick.vjCanvasContext.beginPath();
  17754. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  17755. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  17756. VirtualJoystick.vjCanvasContext.stroke();
  17757. } else {
  17758. VirtualJoystick.vjCanvasContext.beginPath();
  17759. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  17760. VirtualJoystick.vjCanvasContext.beginPath();
  17761. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  17762. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  17763. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  17764. VirtualJoystick.vjCanvasContext.stroke();
  17765. }
  17766. ;
  17767. });
  17768. }
  17769. requestAnimationFrame(function () {
  17770. _this._drawVirtualJoystick();
  17771. });
  17772. };
  17773. VirtualJoystick.prototype.releaseCanvas = function () {
  17774. if (VirtualJoystick.vjCanvas) {
  17775. document.body.removeChild(VirtualJoystick.vjCanvas);
  17776. VirtualJoystick.vjCanvas = null;
  17777. }
  17778. };
  17779. VirtualJoystick._globalJoystickIndex = 0;
  17780. return VirtualJoystick;
  17781. })();
  17782. BABYLON.VirtualJoystick = VirtualJoystick;
  17783. })(BABYLON || (BABYLON = {}));
  17784. var BABYLON;
  17785. (function (BABYLON) {
  17786. (function (VirtualJoystick) {
  17787. var Collection = (function () {
  17788. function Collection() {
  17789. this._count = 0;
  17790. this._collection = new Array();
  17791. }
  17792. Collection.prototype.Count = function () {
  17793. return this._count;
  17794. };
  17795. Collection.prototype.add = function (key, item) {
  17796. if (this._collection[key] != undefined) {
  17797. return undefined;
  17798. }
  17799. this._collection[key] = item;
  17800. return ++this._count;
  17801. };
  17802. Collection.prototype.remove = function (key) {
  17803. if (this._collection[key] == undefined) {
  17804. return undefined;
  17805. }
  17806. delete this._collection[key];
  17807. return --this._count;
  17808. };
  17809. Collection.prototype.item = function (key) {
  17810. return this._collection[key];
  17811. };
  17812. Collection.prototype.forEach = function (block) {
  17813. var key;
  17814. for (key in this._collection) {
  17815. if (this._collection.hasOwnProperty(key)) {
  17816. block(this._collection[key]);
  17817. }
  17818. }
  17819. };
  17820. return Collection;
  17821. })();
  17822. VirtualJoystick.Collection = Collection;
  17823. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  17824. var VirtualJoystick = BABYLON.VirtualJoystick;
  17825. })(BABYLON || (BABYLON = {}));
  17826. var __extends = this.__extends || function (d, b) {
  17827. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17828. function __() { this.constructor = d; }
  17829. __.prototype = b.prototype;
  17830. d.prototype = new __();
  17831. };
  17832. var BABYLON;
  17833. (function (BABYLON) {
  17834. var OculusRiftDevKit2013_Metric = {
  17835. HResolution: 1280,
  17836. VResolution: 800,
  17837. HScreenSize: 0.149759993,
  17838. VScreenSize: 0.0935999975,
  17839. VScreenCenter: 0.0467999987,
  17840. EyeToScreenDistance: 0.0410000011,
  17841. LensSeparationDistance: 0.0635000020,
  17842. InterpupillaryDistance: 0.0640000030,
  17843. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17844. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17845. PostProcessScaleFactor: 1.714605507808412,
  17846. LensCenterOffset: 0.151976421
  17847. };
  17848. var _OculusInnerCamera = (function (_super) {
  17849. __extends(_OculusInnerCamera, _super);
  17850. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  17851. _super.call(this, name, position, scene);
  17852. this._workMatrix = new BABYLON.Matrix();
  17853. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17854. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17855. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17856. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17857. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17858. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17859. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17860. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17861. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17862. }
  17863. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  17864. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17865. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17866. return this._projectionMatrix;
  17867. };
  17868. _OculusInnerCamera.prototype._getViewMatrix = function () {
  17869. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17870. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17871. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17872. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17873. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17874. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17875. return this._viewMatrix;
  17876. };
  17877. return _OculusInnerCamera;
  17878. })(BABYLON.FreeCamera);
  17879. var OculusCamera = (function (_super) {
  17880. __extends(OculusCamera, _super);
  17881. function OculusCamera(name, position, scene) {
  17882. _super.call(this, name, position, scene);
  17883. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  17884. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  17885. this.subCameras.push(this._leftCamera);
  17886. this.subCameras.push(this._rightCamera);
  17887. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17888. }
  17889. OculusCamera.prototype._update = function () {
  17890. this._leftCamera.position.copyFrom(this.position);
  17891. this._rightCamera.position.copyFrom(this.position);
  17892. this._updateCamera(this._leftCamera);
  17893. this._updateCamera(this._rightCamera);
  17894. _super.prototype._update.call(this);
  17895. };
  17896. OculusCamera.prototype._updateCamera = function (camera) {
  17897. camera.minZ = this.minZ;
  17898. camera.maxZ = this.maxZ;
  17899. camera.rotation.x = this.rotation.x;
  17900. camera.rotation.y = this.rotation.y;
  17901. camera.rotation.z = this.rotation.z;
  17902. };
  17903. OculusCamera.prototype._onOrientationEvent = function (evt) {
  17904. var yaw = evt.alpha / 180 * Math.PI;
  17905. var pitch = evt.beta / 180 * Math.PI;
  17906. var roll = evt.gamma / 180 * Math.PI;
  17907. if (!this._offsetOrientation) {
  17908. this._offsetOrientation = {
  17909. yaw: yaw,
  17910. pitch: pitch,
  17911. roll: roll
  17912. };
  17913. return;
  17914. } else {
  17915. this.rotation.y += yaw - this._offsetOrientation.yaw;
  17916. this.rotation.x += pitch - this._offsetOrientation.pitch;
  17917. this.rotation.z += this._offsetOrientation.roll - roll;
  17918. this._offsetOrientation.yaw = yaw;
  17919. this._offsetOrientation.pitch = pitch;
  17920. this._offsetOrientation.roll = roll;
  17921. }
  17922. };
  17923. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  17924. _super.prototype.attachControl.call(this, element, noPreventDefault);
  17925. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17926. };
  17927. OculusCamera.prototype.detachControl = function (element) {
  17928. _super.prototype.detachControl.call(this, element);
  17929. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17930. };
  17931. return OculusCamera;
  17932. })(BABYLON.FreeCamera);
  17933. BABYLON.OculusCamera = OculusCamera;
  17934. })(BABYLON || (BABYLON = {}));
  17935. var __extends = this.__extends || function (d, b) {
  17936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17937. function __() { this.constructor = d; }
  17938. __.prototype = b.prototype;
  17939. d.prototype = new __();
  17940. };
  17941. var BABYLON;
  17942. (function (BABYLON) {
  17943. var OculusRiftDevKit2013_Metric = {
  17944. HResolution: 1280,
  17945. VResolution: 800,
  17946. HScreenSize: 0.149759993,
  17947. VScreenSize: 0.0935999975,
  17948. VScreenCenter: 0.0467999987,
  17949. EyeToScreenDistance: 0.0410000011,
  17950. LensSeparationDistance: 0.0635000020,
  17951. InterpupillaryDistance: 0.0640000030,
  17952. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  17953. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  17954. PostProcessScaleFactor: 1.714605507808412,
  17955. LensCenterOffset: 0.151976421
  17956. };
  17957. var _OculusInnerGamepadCamera = (function (_super) {
  17958. __extends(_OculusInnerGamepadCamera, _super);
  17959. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  17960. _super.call(this, name, position, scene);
  17961. this._workMatrix = new BABYLON.Matrix();
  17962. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  17963. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  17964. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  17965. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  17966. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  17967. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  17968. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  17969. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  17970. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  17971. }
  17972. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  17973. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  17974. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  17975. return this._projectionMatrix;
  17976. };
  17977. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  17978. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17979. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17980. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  17981. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17982. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  17983. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  17984. return this._viewMatrix;
  17985. };
  17986. return _OculusInnerGamepadCamera;
  17987. })(BABYLON.FreeCamera);
  17988. var OculusGamepadCamera = (function (_super) {
  17989. __extends(OculusGamepadCamera, _super);
  17990. function OculusGamepadCamera(name, position, scene) {
  17991. var _this = this;
  17992. _super.call(this, name, position, scene);
  17993. this.angularSensibility = 200;
  17994. this.moveSensibility = 75;
  17995. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  17996. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  17997. this.subCameras.push(this._leftCamera);
  17998. this.subCameras.push(this._rightCamera);
  17999. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18000. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  18001. _this._onNewGameConnected(gamepad);
  18002. });
  18003. }
  18004. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  18005. if (gamepad.index === 0) {
  18006. this._gamepad = gamepad;
  18007. }
  18008. };
  18009. OculusGamepadCamera.prototype._update = function () {
  18010. this._leftCamera.position.copyFrom(this.position);
  18011. this._rightCamera.position.copyFrom(this.position);
  18012. this._updateCamera(this._leftCamera);
  18013. this._updateCamera(this._rightCamera);
  18014. _super.prototype._update.call(this);
  18015. };
  18016. OculusGamepadCamera.prototype._checkInputs = function () {
  18017. if (!this._gamepad) {
  18018. return;
  18019. }
  18020. var LSValues = this._gamepad.leftStick;
  18021. var normalizedLX = LSValues.x / this.moveSensibility;
  18022. var normalizedLY = LSValues.y / this.moveSensibility;
  18023. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  18024. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  18025. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18026. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  18027. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18028. };
  18029. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  18030. camera.minZ = this.minZ;
  18031. camera.maxZ = this.maxZ;
  18032. camera.rotation.x = this.rotation.x;
  18033. camera.rotation.y = this.rotation.y;
  18034. camera.rotation.z = this.rotation.z;
  18035. };
  18036. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  18037. var yaw = evt.alpha / 180 * Math.PI;
  18038. var pitch = evt.beta / 180 * Math.PI;
  18039. var roll = evt.gamma / 180 * Math.PI;
  18040. if (!this._offsetOrientation) {
  18041. this._offsetOrientation = {
  18042. yaw: yaw,
  18043. pitch: pitch,
  18044. roll: roll
  18045. };
  18046. return;
  18047. } else {
  18048. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18049. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18050. this.rotation.z += this._offsetOrientation.roll - roll;
  18051. this._offsetOrientation.yaw = yaw;
  18052. this._offsetOrientation.pitch = pitch;
  18053. this._offsetOrientation.roll = roll;
  18054. }
  18055. };
  18056. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  18057. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18058. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18059. };
  18060. OculusGamepadCamera.prototype.detachControl = function (element) {
  18061. _super.prototype.detachControl.call(this, element);
  18062. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18063. };
  18064. OculusGamepadCamera.prototype.dispose = function () {
  18065. this._gamepads.dispose();
  18066. _super.prototype.dispose.call(this);
  18067. };
  18068. return OculusGamepadCamera;
  18069. })(BABYLON.FreeCamera);
  18070. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  18071. })(BABYLON || (BABYLON = {}));
  18072. var __extends = this.__extends || function (d, b) {
  18073. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18074. function __() { this.constructor = d; }
  18075. __.prototype = b.prototype;
  18076. d.prototype = new __();
  18077. };
  18078. var BABYLON;
  18079. (function (BABYLON) {
  18080. var VirtualJoysticksCamera = (function (_super) {
  18081. __extends(VirtualJoysticksCamera, _super);
  18082. function VirtualJoysticksCamera(name, position, scene) {
  18083. _super.call(this, name, position, scene);
  18084. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  18085. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  18086. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  18087. this._leftjoystick.setJoystickSensibility(0.15);
  18088. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  18089. this._rightjoystick.setAxisForUpDown(0 /* X */);
  18090. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  18091. this._rightjoystick.reverseUpDown = true;
  18092. this._rightjoystick.setJoystickSensibility(0.05);
  18093. this._rightjoystick.setJoystickColor("yellow");
  18094. }
  18095. VirtualJoysticksCamera.prototype._checkInputs = function () {
  18096. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18097. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  18098. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18099. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  18100. if (!this._leftjoystick.pressed) {
  18101. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  18102. }
  18103. if (!this._rightjoystick.pressed) {
  18104. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  18105. }
  18106. };
  18107. VirtualJoysticksCamera.prototype.dispose = function () {
  18108. this._leftjoystick.releaseCanvas();
  18109. _super.prototype.dispose.call(this);
  18110. };
  18111. return VirtualJoysticksCamera;
  18112. })(BABYLON.FreeCamera);
  18113. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  18114. })(BABYLON || (BABYLON = {}));
  18115. var __extends = this.__extends || function (d, b) {
  18116. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18117. function __() { this.constructor = d; }
  18118. __.prototype = b.prototype;
  18119. d.prototype = new __();
  18120. };
  18121. var BABYLON;
  18122. (function (BABYLON) {
  18123. var ShaderMaterial = (function (_super) {
  18124. __extends(ShaderMaterial, _super);
  18125. function ShaderMaterial(name, scene, shaderPath, options) {
  18126. _super.call(this, name, scene);
  18127. this._textures = new Array();
  18128. this._floats = new Array();
  18129. this._floatsArrays = {};
  18130. this._colors3 = new Array();
  18131. this._colors4 = new Array();
  18132. this._vectors2 = new Array();
  18133. this._vectors3 = new Array();
  18134. this._matrices = new Array();
  18135. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  18136. this._shaderPath = shaderPath;
  18137. options.needAlphaBlending = options.needAlphaBlending || false;
  18138. options.needAlphaTesting = options.needAlphaTesting || false;
  18139. options.attributes = options.attributes || ["position", "normal", "uv"];
  18140. options.uniforms = options.uniforms || ["worldViewProjection"];
  18141. options.samplers = options.samplers || [];
  18142. this._options = options;
  18143. }
  18144. ShaderMaterial.prototype.needAlphaBlending = function () {
  18145. return this._options.needAlphaBlending;
  18146. };
  18147. ShaderMaterial.prototype.needAlphaTesting = function () {
  18148. return this._options.needAlphaTesting;
  18149. };
  18150. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  18151. if (this._options.uniforms.indexOf(uniformName) === -1) {
  18152. this._options.uniforms.push(uniformName);
  18153. }
  18154. };
  18155. ShaderMaterial.prototype.setTexture = function (name, texture) {
  18156. if (this._options.samplers.indexOf(name) === -1) {
  18157. this._options.samplers.push(name);
  18158. }
  18159. this._textures[name] = texture;
  18160. return this;
  18161. };
  18162. ShaderMaterial.prototype.setFloat = function (name, value) {
  18163. this._checkUniform(name);
  18164. this._floats[name] = value;
  18165. return this;
  18166. };
  18167. ShaderMaterial.prototype.setFloats = function (name, value) {
  18168. this._checkUniform(name);
  18169. this._floatsArrays[name] = value;
  18170. return this;
  18171. };
  18172. ShaderMaterial.prototype.setColor3 = function (name, value) {
  18173. this._checkUniform(name);
  18174. this._colors3[name] = value;
  18175. return this;
  18176. };
  18177. ShaderMaterial.prototype.setColor4 = function (name, value) {
  18178. this._checkUniform(name);
  18179. this._colors4[name] = value;
  18180. return this;
  18181. };
  18182. ShaderMaterial.prototype.setVector2 = function (name, value) {
  18183. this._checkUniform(name);
  18184. this._vectors2[name] = value;
  18185. return this;
  18186. };
  18187. ShaderMaterial.prototype.setVector3 = function (name, value) {
  18188. this._checkUniform(name);
  18189. this._vectors3[name] = value;
  18190. return this;
  18191. };
  18192. ShaderMaterial.prototype.setMatrix = function (name, value) {
  18193. this._checkUniform(name);
  18194. this._matrices[name] = value;
  18195. return this;
  18196. };
  18197. ShaderMaterial.prototype.isReady = function () {
  18198. var engine = this.getScene().getEngine();
  18199. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  18200. if (!this._effect.isReady()) {
  18201. return false;
  18202. }
  18203. return true;
  18204. };
  18205. ShaderMaterial.prototype.bind = function (world) {
  18206. if (this._options.uniforms.indexOf("world") !== -1) {
  18207. this._effect.setMatrix("world", world);
  18208. }
  18209. if (this._options.uniforms.indexOf("view") !== -1) {
  18210. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  18211. }
  18212. if (this._options.uniforms.indexOf("worldView") !== -1) {
  18213. world.multiplyToRef(this.getScene().getViewMatrix(), this._cachedWorldViewMatrix);
  18214. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  18215. }
  18216. if (this._options.uniforms.indexOf("projection") !== -1) {
  18217. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  18218. }
  18219. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  18220. this._effect.setMatrix("worldViewProjection", world.multiply(this.getScene().getTransformMatrix()));
  18221. }
  18222. for (var name in this._textures) {
  18223. this._effect.setTexture(name, this._textures[name]);
  18224. }
  18225. for (name in this._floats) {
  18226. this._effect.setFloat(name, this._floats[name]);
  18227. }
  18228. for (name in this._floatsArrays) {
  18229. this._effect.setArray(name, this._floatsArrays[name]);
  18230. }
  18231. for (name in this._colors3) {
  18232. this._effect.setColor3(name, this._colors3[name]);
  18233. }
  18234. for (name in this._colors4) {
  18235. var color = this._colors4[name];
  18236. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18237. }
  18238. for (name in this._vectors2) {
  18239. this._effect.setVector2(name, this._vectors2[name]);
  18240. }
  18241. for (name in this._vectors3) {
  18242. this._effect.setVector3(name, this._vectors3[name]);
  18243. }
  18244. for (name in this._matrices) {
  18245. this._effect.setMatrix(name, this._matrices[name]);
  18246. }
  18247. };
  18248. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  18249. for (var name in this._textures) {
  18250. this._textures[name].dispose();
  18251. }
  18252. this._textures = [];
  18253. _super.prototype.dispose.call(this, forceDisposeEffect);
  18254. };
  18255. return ShaderMaterial;
  18256. })(BABYLON.Material);
  18257. BABYLON.ShaderMaterial = ShaderMaterial;
  18258. })(BABYLON || (BABYLON = {}));
  18259. var BABYLON;
  18260. (function (BABYLON) {
  18261. var VertexData = (function () {
  18262. function VertexData() {
  18263. }
  18264. VertexData.prototype.set = function (data, kind) {
  18265. switch (kind) {
  18266. case BABYLON.VertexBuffer.PositionKind:
  18267. this.positions = data;
  18268. break;
  18269. case BABYLON.VertexBuffer.NormalKind:
  18270. this.normals = data;
  18271. break;
  18272. case BABYLON.VertexBuffer.UVKind:
  18273. this.uvs = data;
  18274. break;
  18275. case BABYLON.VertexBuffer.UV2Kind:
  18276. this.uv2s = data;
  18277. break;
  18278. case BABYLON.VertexBuffer.ColorKind:
  18279. this.colors = data;
  18280. break;
  18281. case BABYLON.VertexBuffer.MatricesIndicesKind:
  18282. this.matricesIndices = data;
  18283. break;
  18284. case BABYLON.VertexBuffer.MatricesWeightsKind:
  18285. this.matricesWeights = data;
  18286. break;
  18287. }
  18288. };
  18289. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  18290. this._applyTo(mesh, updatable);
  18291. };
  18292. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  18293. this._applyTo(geometry, updatable);
  18294. };
  18295. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  18296. this._update(mesh);
  18297. };
  18298. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  18299. this._update(geometry);
  18300. };
  18301. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  18302. if (this.positions) {
  18303. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  18304. }
  18305. if (this.normals) {
  18306. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  18307. }
  18308. if (this.uvs) {
  18309. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  18310. }
  18311. if (this.uv2s) {
  18312. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  18313. }
  18314. if (this.colors) {
  18315. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  18316. }
  18317. if (this.matricesIndices) {
  18318. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  18319. }
  18320. if (this.matricesWeights) {
  18321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  18322. }
  18323. if (this.indices) {
  18324. meshOrGeometry.setIndices(this.indices);
  18325. }
  18326. };
  18327. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  18328. if (this.positions) {
  18329. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  18330. }
  18331. if (this.normals) {
  18332. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  18333. }
  18334. if (this.uvs) {
  18335. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  18336. }
  18337. if (this.uv2s) {
  18338. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  18339. }
  18340. if (this.colors) {
  18341. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  18342. }
  18343. if (this.matricesIndices) {
  18344. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  18345. }
  18346. if (this.matricesWeights) {
  18347. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  18348. }
  18349. if (this.indices) {
  18350. meshOrGeometry.setIndices(this.indices);
  18351. }
  18352. };
  18353. VertexData.prototype.transform = function (matrix) {
  18354. var transformed = BABYLON.Vector3.Zero();
  18355. if (this.positions) {
  18356. var position = BABYLON.Vector3.Zero();
  18357. for (var index = 0; index < this.positions.length; index += 3) {
  18358. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  18359. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  18360. this.positions[index] = transformed.x;
  18361. this.positions[index + 1] = transformed.y;
  18362. this.positions[index + 2] = transformed.z;
  18363. }
  18364. }
  18365. if (this.normals) {
  18366. var normal = BABYLON.Vector3.Zero();
  18367. for (index = 0; index < this.normals.length; index += 3) {
  18368. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  18369. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  18370. this.normals[index] = transformed.x;
  18371. this.normals[index + 1] = transformed.y;
  18372. this.normals[index + 2] = transformed.z;
  18373. }
  18374. }
  18375. };
  18376. VertexData.prototype.merge = function (other) {
  18377. if (other.indices) {
  18378. if (!this.indices) {
  18379. this.indices = [];
  18380. }
  18381. var offset = this.positions ? this.positions.length / 3 : 0;
  18382. for (var index = 0; index < other.indices.length; index++) {
  18383. this.indices.push(other.indices[index] + offset);
  18384. }
  18385. }
  18386. if (other.positions) {
  18387. if (!this.positions) {
  18388. this.positions = [];
  18389. }
  18390. for (index = 0; index < other.positions.length; index++) {
  18391. this.positions.push(other.positions[index]);
  18392. }
  18393. }
  18394. if (other.normals) {
  18395. if (!this.normals) {
  18396. this.normals = [];
  18397. }
  18398. for (index = 0; index < other.normals.length; index++) {
  18399. this.normals.push(other.normals[index]);
  18400. }
  18401. }
  18402. if (other.uvs) {
  18403. if (!this.uvs) {
  18404. this.uvs = [];
  18405. }
  18406. for (index = 0; index < other.uvs.length; index++) {
  18407. this.uvs.push(other.uvs[index]);
  18408. }
  18409. }
  18410. if (other.uv2s) {
  18411. if (!this.uv2s) {
  18412. this.uv2s = [];
  18413. }
  18414. for (index = 0; index < other.uv2s.length; index++) {
  18415. this.uv2s.push(other.uv2s[index]);
  18416. }
  18417. }
  18418. if (other.matricesIndices) {
  18419. if (!this.matricesIndices) {
  18420. this.matricesIndices = [];
  18421. }
  18422. for (index = 0; index < other.matricesIndices.length; index++) {
  18423. this.matricesIndices.push(other.matricesIndices[index]);
  18424. }
  18425. }
  18426. if (other.matricesWeights) {
  18427. if (!this.matricesWeights) {
  18428. this.matricesWeights = [];
  18429. }
  18430. for (index = 0; index < other.matricesWeights.length; index++) {
  18431. this.matricesWeights.push(other.matricesWeights[index]);
  18432. }
  18433. }
  18434. if (other.colors) {
  18435. if (!this.colors) {
  18436. this.colors = [];
  18437. }
  18438. for (index = 0; index < other.colors.length; index++) {
  18439. this.colors.push(other.colors[index]);
  18440. }
  18441. }
  18442. };
  18443. VertexData.ExtractFromMesh = function (mesh) {
  18444. return VertexData._ExtractFrom(mesh);
  18445. };
  18446. VertexData.ExtractFromGeometry = function (geometry) {
  18447. return VertexData._ExtractFrom(geometry);
  18448. };
  18449. VertexData._ExtractFrom = function (meshOrGeometry) {
  18450. var result = new BABYLON.VertexData();
  18451. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18452. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18453. }
  18454. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18455. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18456. }
  18457. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18458. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18459. }
  18460. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18461. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18462. }
  18463. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18464. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18465. }
  18466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18467. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18468. }
  18469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18470. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18471. }
  18472. result.indices = meshOrGeometry.getIndices();
  18473. return result;
  18474. };
  18475. VertexData.CreateBox = function (size) {
  18476. var normalsSource = [
  18477. new BABYLON.Vector3(0, 0, 1),
  18478. new BABYLON.Vector3(0, 0, -1),
  18479. new BABYLON.Vector3(1, 0, 0),
  18480. new BABYLON.Vector3(-1, 0, 0),
  18481. new BABYLON.Vector3(0, 1, 0),
  18482. new BABYLON.Vector3(0, -1, 0)
  18483. ];
  18484. var indices = [];
  18485. var positions = [];
  18486. var normals = [];
  18487. var uvs = [];
  18488. size = size || 1;
  18489. for (var index = 0; index < normalsSource.length; index++) {
  18490. var normal = normalsSource[index];
  18491. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  18492. var side2 = BABYLON.Vector3.Cross(normal, side1);
  18493. var verticesLength = positions.length / 3;
  18494. indices.push(verticesLength);
  18495. indices.push(verticesLength + 1);
  18496. indices.push(verticesLength + 2);
  18497. indices.push(verticesLength);
  18498. indices.push(verticesLength + 2);
  18499. indices.push(verticesLength + 3);
  18500. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  18501. positions.push(vertex.x, vertex.y, vertex.z);
  18502. normals.push(normal.x, normal.y, normal.z);
  18503. uvs.push(1.0, 1.0);
  18504. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  18505. positions.push(vertex.x, vertex.y, vertex.z);
  18506. normals.push(normal.x, normal.y, normal.z);
  18507. uvs.push(0.0, 1.0);
  18508. vertex = normal.add(side1).add(side2).scale(size / 2);
  18509. positions.push(vertex.x, vertex.y, vertex.z);
  18510. normals.push(normal.x, normal.y, normal.z);
  18511. uvs.push(0.0, 0.0);
  18512. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  18513. positions.push(vertex.x, vertex.y, vertex.z);
  18514. normals.push(normal.x, normal.y, normal.z);
  18515. uvs.push(1.0, 0.0);
  18516. }
  18517. var vertexData = new BABYLON.VertexData();
  18518. vertexData.indices = indices;
  18519. vertexData.positions = positions;
  18520. vertexData.normals = normals;
  18521. vertexData.uvs = uvs;
  18522. return vertexData;
  18523. };
  18524. VertexData.CreateSphere = function (segments, diameter) {
  18525. segments = segments || 32;
  18526. diameter = diameter || 1;
  18527. var radius = diameter / 2;
  18528. var totalZRotationSteps = 2 + segments;
  18529. var totalYRotationSteps = 2 * totalZRotationSteps;
  18530. var indices = [];
  18531. var positions = [];
  18532. var normals = [];
  18533. var uvs = [];
  18534. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  18535. var normalizedZ = zRotationStep / totalZRotationSteps;
  18536. var angleZ = (normalizedZ * Math.PI);
  18537. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  18538. var normalizedY = yRotationStep / totalYRotationSteps;
  18539. var angleY = normalizedY * Math.PI * 2;
  18540. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  18541. var rotationY = BABYLON.Matrix.RotationY(angleY);
  18542. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  18543. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  18544. var vertex = complete.scale(radius);
  18545. var normal = BABYLON.Vector3.Normalize(vertex);
  18546. positions.push(vertex.x, vertex.y, vertex.z);
  18547. normals.push(normal.x, normal.y, normal.z);
  18548. uvs.push(normalizedZ, normalizedY);
  18549. }
  18550. if (zRotationStep > 0) {
  18551. var verticesCount = positions.length / 3;
  18552. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  18553. indices.push((firstIndex));
  18554. indices.push((firstIndex + 1));
  18555. indices.push(firstIndex + totalYRotationSteps + 1);
  18556. indices.push((firstIndex + totalYRotationSteps + 1));
  18557. indices.push((firstIndex + 1));
  18558. indices.push((firstIndex + totalYRotationSteps + 2));
  18559. }
  18560. }
  18561. }
  18562. var vertexData = new BABYLON.VertexData();
  18563. vertexData.indices = indices;
  18564. vertexData.positions = positions;
  18565. vertexData.normals = normals;
  18566. vertexData.uvs = uvs;
  18567. return vertexData;
  18568. };
  18569. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  18570. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  18571. var radiusTop = diameterTop / 2;
  18572. var radiusBottom = diameterBottom / 2;
  18573. var indices = [];
  18574. var positions = [];
  18575. var normals = [];
  18576. var uvs = [];
  18577. height = height || 1;
  18578. diameterTop = diameterTop || 0.5;
  18579. diameterBottom = diameterBottom || 1;
  18580. tessellation = tessellation || 16;
  18581. subdivisions = subdivisions || 1;
  18582. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  18583. var getCircleVector = function (i) {
  18584. var angle = (i * 2.0 * Math.PI / tessellation);
  18585. var dx = Math.cos(angle);
  18586. var dz = Math.sin(angle);
  18587. return new BABYLON.Vector3(dx, 0, dz);
  18588. };
  18589. var createCylinderCap = function (isTop) {
  18590. var radius = isTop ? radiusTop : radiusBottom;
  18591. if (radius == 0) {
  18592. return;
  18593. }
  18594. var vbase = positions.length / 3;
  18595. var offset = new BABYLON.Vector3(0, height / 2, 0);
  18596. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  18597. if (!isTop) {
  18598. offset.scaleInPlace(-1);
  18599. textureScale.x = -textureScale.x;
  18600. }
  18601. for (i = 0; i < tessellation; i++) {
  18602. var circleVector = getCircleVector(i);
  18603. var position = circleVector.scale(radius).add(offset);
  18604. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  18605. positions.push(position.x, position.y, position.z);
  18606. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18607. }
  18608. for (var i = 0; i < tessellation - 2; i++) {
  18609. if (!isTop) {
  18610. indices.push(vbase);
  18611. indices.push(vbase + (i + 2) % tessellation);
  18612. indices.push(vbase + (i + 1) % tessellation);
  18613. } else {
  18614. indices.push(vbase);
  18615. indices.push(vbase + (i + 1) % tessellation);
  18616. indices.push(vbase + (i + 2) % tessellation);
  18617. }
  18618. }
  18619. };
  18620. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  18621. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  18622. var stride = tessellation + 1;
  18623. for (var i = 0; i <= tessellation; i++) {
  18624. var circleVector = getCircleVector(i);
  18625. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  18626. var position, radius = radiusBottom;
  18627. for (var s = 0; s <= subdivisions; s++) {
  18628. position = circleVector.scale(radius);
  18629. position.addInPlace(base.add(offset.scale(s)));
  18630. textureCoordinate.y += 1 / subdivisions;
  18631. radius += (radiusTop - radiusBottom) / subdivisions;
  18632. positions.push(position.x, position.y, position.z);
  18633. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18634. }
  18635. }
  18636. subdivisions += 1;
  18637. for (var s = 0; s < subdivisions - 1; s++) {
  18638. for (var i = 0; i <= tessellation; i++) {
  18639. indices.push(i * subdivisions + s);
  18640. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18641. indices.push(i * subdivisions + (s + 1));
  18642. indices.push(i * subdivisions + (s + 1));
  18643. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  18644. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  18645. }
  18646. }
  18647. createCylinderCap(true);
  18648. createCylinderCap(false);
  18649. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18650. var vertexData = new BABYLON.VertexData();
  18651. vertexData.indices = indices;
  18652. vertexData.positions = positions;
  18653. vertexData.normals = normals;
  18654. vertexData.uvs = uvs;
  18655. return vertexData;
  18656. };
  18657. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  18658. var indices = [];
  18659. var positions = [];
  18660. var normals = [];
  18661. var uvs = [];
  18662. diameter = diameter || 1;
  18663. thickness = thickness || 0.5;
  18664. tessellation = tessellation || 16;
  18665. var stride = tessellation + 1;
  18666. for (var i = 0; i <= tessellation; i++) {
  18667. var u = i / tessellation;
  18668. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  18669. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  18670. for (var j = 0; j <= tessellation; j++) {
  18671. var v = 1 - j / tessellation;
  18672. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  18673. var dx = Math.cos(innerAngle);
  18674. var dy = Math.sin(innerAngle);
  18675. var normal = new BABYLON.Vector3(dx, dy, 0);
  18676. var position = normal.scale(thickness / 2);
  18677. var textureCoordinate = new BABYLON.Vector2(u, v);
  18678. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  18679. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  18680. positions.push(position.x, position.y, position.z);
  18681. normals.push(normal.x, normal.y, normal.z);
  18682. uvs.push(textureCoordinate.x, textureCoordinate.y);
  18683. var nextI = (i + 1) % stride;
  18684. var nextJ = (j + 1) % stride;
  18685. indices.push(i * stride + j);
  18686. indices.push(i * stride + nextJ);
  18687. indices.push(nextI * stride + j);
  18688. indices.push(i * stride + nextJ);
  18689. indices.push(nextI * stride + nextJ);
  18690. indices.push(nextI * stride + j);
  18691. }
  18692. }
  18693. var vertexData = new BABYLON.VertexData();
  18694. vertexData.indices = indices;
  18695. vertexData.positions = positions;
  18696. vertexData.normals = normals;
  18697. vertexData.uvs = uvs;
  18698. return vertexData;
  18699. };
  18700. VertexData.CreateLines = function (points) {
  18701. var indices = [];
  18702. var positions = [];
  18703. for (var index = 0; index < points.length; index++) {
  18704. positions.push(points[index].x, points[index].y, points[index].z);
  18705. if (index > 0) {
  18706. indices.push(index - 1);
  18707. indices.push(index);
  18708. }
  18709. }
  18710. var vertexData = new BABYLON.VertexData();
  18711. vertexData.indices = indices;
  18712. vertexData.positions = positions;
  18713. return vertexData;
  18714. };
  18715. VertexData.CreateGround = function (width, height, subdivisions) {
  18716. var indices = [];
  18717. var positions = [];
  18718. var normals = [];
  18719. var uvs = [];
  18720. var row, col;
  18721. width = width || 1;
  18722. height = height || 1;
  18723. subdivisions = subdivisions || 1;
  18724. for (row = 0; row <= subdivisions; row++) {
  18725. for (col = 0; col <= subdivisions; col++) {
  18726. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18727. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18728. positions.push(position.x, position.y, position.z);
  18729. normals.push(normal.x, normal.y, normal.z);
  18730. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18731. }
  18732. }
  18733. for (row = 0; row < subdivisions; row++) {
  18734. for (col = 0; col < subdivisions; col++) {
  18735. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18736. indices.push(col + 1 + row * (subdivisions + 1));
  18737. indices.push(col + row * (subdivisions + 1));
  18738. indices.push(col + (row + 1) * (subdivisions + 1));
  18739. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18740. indices.push(col + row * (subdivisions + 1));
  18741. }
  18742. }
  18743. var vertexData = new BABYLON.VertexData();
  18744. vertexData.indices = indices;
  18745. vertexData.positions = positions;
  18746. vertexData.normals = normals;
  18747. vertexData.uvs = uvs;
  18748. return vertexData;
  18749. };
  18750. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  18751. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  18752. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  18753. var indices = [];
  18754. var positions = [];
  18755. var normals = [];
  18756. var uvs = [];
  18757. var row, col, tileRow, tileCol;
  18758. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  18759. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  18760. precision.w = (precision.w < 1) ? 1 : precision.w;
  18761. precision.h = (precision.h < 1) ? 1 : precision.h;
  18762. var tileSize = {
  18763. 'w': (xmax - xmin) / subdivisions.w,
  18764. 'h': (zmax - zmin) / subdivisions.h
  18765. };
  18766. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  18767. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  18768. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  18769. }
  18770. }
  18771. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  18772. var base = positions.length / 3;
  18773. var rowLength = precision.w + 1;
  18774. for (row = 0; row < precision.h; row++) {
  18775. for (col = 0; col < precision.w; col++) {
  18776. var square = [
  18777. base + col + row * rowLength,
  18778. base + (col + 1) + row * rowLength,
  18779. base + (col + 1) + (row + 1) * rowLength,
  18780. base + col + (row + 1) * rowLength
  18781. ];
  18782. indices.push(square[1]);
  18783. indices.push(square[2]);
  18784. indices.push(square[3]);
  18785. indices.push(square[0]);
  18786. indices.push(square[1]);
  18787. indices.push(square[3]);
  18788. }
  18789. }
  18790. var position = BABYLON.Vector3.Zero();
  18791. var normal = new BABYLON.Vector3(0, 1.0, 0);
  18792. for (row = 0; row <= precision.h; row++) {
  18793. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  18794. for (col = 0; col <= precision.w; col++) {
  18795. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  18796. position.y = 0;
  18797. positions.push(position.x, position.y, position.z);
  18798. normals.push(normal.x, normal.y, normal.z);
  18799. uvs.push(col / precision.w, row / precision.h);
  18800. }
  18801. }
  18802. }
  18803. var vertexData = new BABYLON.VertexData();
  18804. vertexData.indices = indices;
  18805. vertexData.positions = positions;
  18806. vertexData.normals = normals;
  18807. vertexData.uvs = uvs;
  18808. return vertexData;
  18809. };
  18810. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  18811. var indices = [];
  18812. var positions = [];
  18813. var normals = [];
  18814. var uvs = [];
  18815. var row, col;
  18816. for (row = 0; row <= subdivisions; row++) {
  18817. for (col = 0; col <= subdivisions; col++) {
  18818. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  18819. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  18820. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  18821. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  18822. var r = buffer[pos] / 255.0;
  18823. var g = buffer[pos + 1] / 255.0;
  18824. var b = buffer[pos + 2] / 255.0;
  18825. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18826. position.y = minHeight + (maxHeight - minHeight) * gradient;
  18827. positions.push(position.x, position.y, position.z);
  18828. normals.push(0, 0, 0);
  18829. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  18830. }
  18831. }
  18832. for (row = 0; row < subdivisions; row++) {
  18833. for (col = 0; col < subdivisions; col++) {
  18834. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18835. indices.push(col + 1 + row * (subdivisions + 1));
  18836. indices.push(col + row * (subdivisions + 1));
  18837. indices.push(col + (row + 1) * (subdivisions + 1));
  18838. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  18839. indices.push(col + row * (subdivisions + 1));
  18840. }
  18841. }
  18842. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18843. var vertexData = new BABYLON.VertexData();
  18844. vertexData.indices = indices;
  18845. vertexData.positions = positions;
  18846. vertexData.normals = normals;
  18847. vertexData.uvs = uvs;
  18848. return vertexData;
  18849. };
  18850. VertexData.CreatePlane = function (size) {
  18851. var indices = [];
  18852. var positions = [];
  18853. var normals = [];
  18854. var uvs = [];
  18855. size = size || 1;
  18856. var halfSize = size / 2.0;
  18857. positions.push(-halfSize, -halfSize, 0);
  18858. normals.push(0, 0, -1.0);
  18859. uvs.push(0.0, 0.0);
  18860. positions.push(halfSize, -halfSize, 0);
  18861. normals.push(0, 0, -1.0);
  18862. uvs.push(1.0, 0.0);
  18863. positions.push(halfSize, halfSize, 0);
  18864. normals.push(0, 0, -1.0);
  18865. uvs.push(1.0, 1.0);
  18866. positions.push(-halfSize, halfSize, 0);
  18867. normals.push(0, 0, -1.0);
  18868. uvs.push(0.0, 1.0);
  18869. indices.push(0);
  18870. indices.push(1);
  18871. indices.push(2);
  18872. indices.push(0);
  18873. indices.push(2);
  18874. indices.push(3);
  18875. var vertexData = new BABYLON.VertexData();
  18876. vertexData.indices = indices;
  18877. vertexData.positions = positions;
  18878. vertexData.normals = normals;
  18879. vertexData.uvs = uvs;
  18880. return vertexData;
  18881. };
  18882. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  18883. var indices = [];
  18884. var positions = [];
  18885. var normals = [];
  18886. var uvs = [];
  18887. radius = radius || 2;
  18888. tube = tube || 0.5;
  18889. radialSegments = radialSegments || 32;
  18890. tubularSegments = tubularSegments || 32;
  18891. p = p || 2;
  18892. q = q || 3;
  18893. var getPos = function (angle) {
  18894. var cu = Math.cos(angle);
  18895. var su = Math.sin(angle);
  18896. var quOverP = q / p * angle;
  18897. var cs = Math.cos(quOverP);
  18898. var tx = radius * (2 + cs) * 0.5 * cu;
  18899. var ty = radius * (2 + cs) * su * 0.5;
  18900. var tz = radius * Math.sin(quOverP) * 0.5;
  18901. return new BABYLON.Vector3(tx, ty, tz);
  18902. };
  18903. for (var i = 0; i <= radialSegments; i++) {
  18904. var modI = i % radialSegments;
  18905. var u = modI / radialSegments * 2 * p * Math.PI;
  18906. var p1 = getPos(u);
  18907. var p2 = getPos(u + 0.01);
  18908. var tang = p2.subtract(p1);
  18909. var n = p2.add(p1);
  18910. var bitan = BABYLON.Vector3.Cross(tang, n);
  18911. n = BABYLON.Vector3.Cross(bitan, tang);
  18912. bitan.normalize();
  18913. n.normalize();
  18914. for (var j = 0; j < tubularSegments; j++) {
  18915. var modJ = j % tubularSegments;
  18916. var v = modJ / tubularSegments * 2 * Math.PI;
  18917. var cx = -tube * Math.cos(v);
  18918. var cy = tube * Math.sin(v);
  18919. positions.push(p1.x + cx * n.x + cy * bitan.x);
  18920. positions.push(p1.y + cx * n.y + cy * bitan.y);
  18921. positions.push(p1.z + cx * n.z + cy * bitan.z);
  18922. uvs.push(i / radialSegments);
  18923. uvs.push(j / tubularSegments);
  18924. }
  18925. }
  18926. for (i = 0; i < radialSegments; i++) {
  18927. for (j = 0; j < tubularSegments; j++) {
  18928. var jNext = (j + 1) % tubularSegments;
  18929. var a = i * tubularSegments + j;
  18930. var b = (i + 1) * tubularSegments + j;
  18931. var c = (i + 1) * tubularSegments + jNext;
  18932. var d = i * tubularSegments + jNext;
  18933. indices.push(d);
  18934. indices.push(b);
  18935. indices.push(a);
  18936. indices.push(d);
  18937. indices.push(c);
  18938. indices.push(b);
  18939. }
  18940. }
  18941. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18942. var vertexData = new BABYLON.VertexData();
  18943. vertexData.indices = indices;
  18944. vertexData.positions = positions;
  18945. vertexData.normals = normals;
  18946. vertexData.uvs = uvs;
  18947. return vertexData;
  18948. };
  18949. VertexData.ComputeNormals = function (positions, indices, normals) {
  18950. var positionVectors = [];
  18951. var facesOfVertices = [];
  18952. var index;
  18953. for (index = 0; index < positions.length; index += 3) {
  18954. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  18955. positionVectors.push(vector3);
  18956. facesOfVertices.push([]);
  18957. }
  18958. var facesNormals = [];
  18959. for (index = 0; index < indices.length / 3; index++) {
  18960. var i1 = indices[index * 3];
  18961. var i2 = indices[index * 3 + 1];
  18962. var i3 = indices[index * 3 + 2];
  18963. var p1 = positionVectors[i1];
  18964. var p2 = positionVectors[i2];
  18965. var p3 = positionVectors[i3];
  18966. var p1p2 = p1.subtract(p2);
  18967. var p3p2 = p3.subtract(p2);
  18968. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18969. facesOfVertices[i1].push(index);
  18970. facesOfVertices[i2].push(index);
  18971. facesOfVertices[i3].push(index);
  18972. }
  18973. for (index = 0; index < positionVectors.length; index++) {
  18974. var faces = facesOfVertices[index];
  18975. var normal = BABYLON.Vector3.Zero();
  18976. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  18977. normal.addInPlace(facesNormals[faces[faceIndex]]);
  18978. }
  18979. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  18980. normals[index * 3] = normal.x;
  18981. normals[index * 3 + 1] = normal.y;
  18982. normals[index * 3 + 2] = normal.z;
  18983. }
  18984. };
  18985. return VertexData;
  18986. })();
  18987. BABYLON.VertexData = VertexData;
  18988. })(BABYLON || (BABYLON = {}));
  18989. var __extends = this.__extends || function (d, b) {
  18990. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18991. function __() { this.constructor = d; }
  18992. __.prototype = b.prototype;
  18993. d.prototype = new __();
  18994. };
  18995. var BABYLON;
  18996. (function (BABYLON) {
  18997. var buildCamera = function (that, name) {
  18998. that._leftCamera.isIntermediate = true;
  18999. that.subCameras.push(that._leftCamera);
  19000. that.subCameras.push(that._rightCamera);
  19001. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  19002. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  19003. that._anaglyphPostProcess.onApply = function (effect) {
  19004. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  19005. };
  19006. that._update();
  19007. };
  19008. var AnaglyphArcRotateCamera = (function (_super) {
  19009. __extends(AnaglyphArcRotateCamera, _super);
  19010. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  19011. _super.call(this, name, alpha, beta, radius, target, scene);
  19012. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19013. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  19014. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  19015. buildCamera(this, name);
  19016. }
  19017. AnaglyphArcRotateCamera.prototype._update = function () {
  19018. this._updateCamera(this._leftCamera);
  19019. this._updateCamera(this._rightCamera);
  19020. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  19021. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  19022. _super.prototype._update.call(this);
  19023. };
  19024. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  19025. camera.beta = this.beta;
  19026. camera.radius = this.radius;
  19027. camera.minZ = this.minZ;
  19028. camera.maxZ = this.maxZ;
  19029. camera.fov = this.fov;
  19030. camera.target = this.target;
  19031. };
  19032. return AnaglyphArcRotateCamera;
  19033. })(BABYLON.ArcRotateCamera);
  19034. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  19035. var AnaglyphFreeCamera = (function (_super) {
  19036. __extends(AnaglyphFreeCamera, _super);
  19037. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  19038. _super.call(this, name, position, scene);
  19039. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19040. this._transformMatrix = new BABYLON.Matrix();
  19041. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  19042. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  19043. buildCamera(this, name);
  19044. }
  19045. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  19046. var target = this.getTarget();
  19047. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  19048. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  19049. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  19050. };
  19051. AnaglyphFreeCamera.prototype._update = function () {
  19052. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  19053. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  19054. this._updateCamera(this._leftCamera);
  19055. this._updateCamera(this._rightCamera);
  19056. _super.prototype._update.call(this);
  19057. };
  19058. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  19059. camera.minZ = this.minZ;
  19060. camera.maxZ = this.maxZ;
  19061. camera.fov = this.fov;
  19062. camera.viewport = this.viewport;
  19063. camera.setTarget(this.getTarget());
  19064. };
  19065. return AnaglyphFreeCamera;
  19066. })(BABYLON.FreeCamera);
  19067. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  19068. })(BABYLON || (BABYLON = {}));
  19069. var __extends = this.__extends || function (d, b) {
  19070. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19071. function __() { this.constructor = d; }
  19072. __.prototype = b.prototype;
  19073. d.prototype = new __();
  19074. };
  19075. var BABYLON;
  19076. (function (BABYLON) {
  19077. var AnaglyphPostProcess = (function (_super) {
  19078. __extends(AnaglyphPostProcess, _super);
  19079. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19080. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  19081. }
  19082. return AnaglyphPostProcess;
  19083. })(BABYLON.PostProcess);
  19084. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  19085. })(BABYLON || (BABYLON = {}));
  19086. var BABYLON;
  19087. (function (BABYLON) {
  19088. var Tags = (function () {
  19089. function Tags() {
  19090. }
  19091. Tags.EnableFor = function (obj) {
  19092. obj._tags = obj._tags || {};
  19093. obj.hasTags = function () {
  19094. return Tags.HasTags(obj);
  19095. };
  19096. obj.addTags = function (tagsString) {
  19097. return Tags.AddTagsTo(obj, tagsString);
  19098. };
  19099. obj.removeTags = function (tagsString) {
  19100. return Tags.RemoveTagsFrom(obj, tagsString);
  19101. };
  19102. obj.matchesTagsQuery = function (tagsQuery) {
  19103. return Tags.MatchesQuery(obj, tagsQuery);
  19104. };
  19105. };
  19106. Tags.DisableFor = function (obj) {
  19107. delete obj._tags;
  19108. delete obj.hasTags;
  19109. delete obj.addTags;
  19110. delete obj.removeTags;
  19111. delete obj.matchesTagsQuery;
  19112. };
  19113. Tags.HasTags = function (obj) {
  19114. if (!obj._tags) {
  19115. return false;
  19116. }
  19117. return !BABYLON.Tools.IsEmpty(obj._tags);
  19118. };
  19119. Tags.GetTags = function (obj) {
  19120. if (!obj._tags) {
  19121. return null;
  19122. }
  19123. return obj._tags;
  19124. };
  19125. Tags.AddTagsTo = function (obj, tagsString) {
  19126. if (!tagsString) {
  19127. return;
  19128. }
  19129. var tags = tagsString.split(" ");
  19130. for (var t in tags) {
  19131. Tags._AddTagTo(obj, tags[t]);
  19132. }
  19133. };
  19134. Tags._AddTagTo = function (obj, tag) {
  19135. tag = tag.trim();
  19136. if (tag === "" || tag === "true" || tag === "false") {
  19137. return;
  19138. }
  19139. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  19140. return;
  19141. }
  19142. Tags.EnableFor(obj);
  19143. obj._tags[tag] = true;
  19144. };
  19145. Tags.RemoveTagsFrom = function (obj, tagsString) {
  19146. if (!Tags.HasTags(obj)) {
  19147. return;
  19148. }
  19149. var tags = tagsString.split(" ");
  19150. for (var t in tags) {
  19151. Tags._RemoveTagFrom(obj, tags[t]);
  19152. }
  19153. };
  19154. Tags._RemoveTagFrom = function (obj, tag) {
  19155. delete obj._tags[tag];
  19156. };
  19157. Tags.MatchesQuery = function (obj, tagsQuery) {
  19158. if (tagsQuery === undefined) {
  19159. return true;
  19160. }
  19161. if (tagsQuery === "") {
  19162. return Tags.HasTags(obj);
  19163. }
  19164. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  19165. return Tags.HasTags(obj) && obj._tags[r];
  19166. });
  19167. };
  19168. return Tags;
  19169. })();
  19170. BABYLON.Tags = Tags;
  19171. })(BABYLON || (BABYLON = {}));
  19172. var BABYLON;
  19173. (function (BABYLON) {
  19174. (function (Internals) {
  19175. var AndOrNotEvaluator = (function () {
  19176. function AndOrNotEvaluator() {
  19177. }
  19178. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  19179. if (!query.match(/\([^\(\)]*\)/g)) {
  19180. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  19181. } else {
  19182. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  19183. r = r.slice(1, r.length - 1);
  19184. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  19185. });
  19186. }
  19187. if (query === "true") {
  19188. return true;
  19189. }
  19190. if (query === "false") {
  19191. return false;
  19192. }
  19193. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  19194. };
  19195. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  19196. evaluateCallback = evaluateCallback || (function (r) {
  19197. return r === "true" ? true : false;
  19198. });
  19199. var result;
  19200. var or = parenthesisContent.split("||");
  19201. for (var i in or) {
  19202. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  19203. var and = ori.split("&&");
  19204. if (and.length > 1) {
  19205. for (var j = 0; j < and.length; ++j) {
  19206. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  19207. if (andj !== "true" && andj !== "false") {
  19208. if (andj[0] === "!") {
  19209. result = !evaluateCallback(andj.substring(1));
  19210. } else {
  19211. result = evaluateCallback(andj);
  19212. }
  19213. } else {
  19214. result = andj === "true" ? true : false;
  19215. }
  19216. if (!result) {
  19217. ori = "false";
  19218. break;
  19219. }
  19220. }
  19221. }
  19222. if (result || ori === "true") {
  19223. result = true;
  19224. break;
  19225. }
  19226. if (ori !== "true" && ori !== "false") {
  19227. if (ori[0] === "!") {
  19228. result = !evaluateCallback(ori.substring(1));
  19229. } else {
  19230. result = evaluateCallback(ori);
  19231. }
  19232. } else {
  19233. result = ori === "true" ? true : false;
  19234. }
  19235. }
  19236. return result ? "true" : "false";
  19237. };
  19238. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  19239. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  19240. r = r.replace(/[\s]/g, function () {
  19241. return "";
  19242. });
  19243. return r.length % 2 ? "!" : "";
  19244. });
  19245. booleanString = booleanString.trim();
  19246. if (booleanString === "!true") {
  19247. booleanString = "false";
  19248. } else if (booleanString === "!false") {
  19249. booleanString = "true";
  19250. }
  19251. return booleanString;
  19252. };
  19253. return AndOrNotEvaluator;
  19254. })();
  19255. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  19256. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19257. var Internals = BABYLON.Internals;
  19258. })(BABYLON || (BABYLON = {}));
  19259. var BABYLON;
  19260. (function (BABYLON) {
  19261. var PostProcessRenderPass = (function () {
  19262. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  19263. this._enabled = true;
  19264. this._refCount = 0;
  19265. this._name = name;
  19266. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  19267. this.setRenderList(renderList);
  19268. this._renderTexture.onBeforeRender = beforeRender;
  19269. this._renderTexture.onAfterRender = afterRender;
  19270. this._scene = scene;
  19271. this._renderList = renderList;
  19272. }
  19273. PostProcessRenderPass.prototype._incRefCount = function () {
  19274. if (this._refCount === 0) {
  19275. this._scene.customRenderTargets.push(this._renderTexture);
  19276. }
  19277. return ++this._refCount;
  19278. };
  19279. PostProcessRenderPass.prototype._decRefCount = function () {
  19280. this._refCount--;
  19281. if (this._refCount <= 0) {
  19282. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  19283. }
  19284. return this._refCount;
  19285. };
  19286. PostProcessRenderPass.prototype._update = function () {
  19287. this.setRenderList(this._renderList);
  19288. };
  19289. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  19290. this._renderTexture.renderList = renderList;
  19291. };
  19292. PostProcessRenderPass.prototype.getRenderTexture = function () {
  19293. return this._renderTexture;
  19294. };
  19295. return PostProcessRenderPass;
  19296. })();
  19297. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  19298. })(BABYLON || (BABYLON = {}));
  19299. var BABYLON;
  19300. (function (BABYLON) {
  19301. var PostProcessRenderEffect = (function () {
  19302. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  19303. this._engine = engine;
  19304. this._name = name;
  19305. this._singleInstance = singleInstance || true;
  19306. this._getPostProcess = getPostProcess;
  19307. this._cameras = [];
  19308. this._postProcesses = [];
  19309. this._indicesForCamera = [];
  19310. this._renderPasses = [];
  19311. this._renderEffectAsPasses = [];
  19312. }
  19313. PostProcessRenderEffect.prototype._update = function () {
  19314. for (var renderPassName in this._renderPasses) {
  19315. this._renderPasses[renderPassName]._update();
  19316. }
  19317. };
  19318. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  19319. this._renderPasses[renderPass._name] = renderPass;
  19320. this._linkParameters();
  19321. };
  19322. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  19323. delete this._renderPasses[renderPass._name];
  19324. this._linkParameters();
  19325. };
  19326. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  19327. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  19328. this._linkParameters();
  19329. };
  19330. PostProcessRenderEffect.prototype.getPass = function (passName) {
  19331. for (var renderPassName in this._renderPasses) {
  19332. if (renderPassName === passName) {
  19333. return this._renderPasses[passName];
  19334. }
  19335. }
  19336. };
  19337. PostProcessRenderEffect.prototype.emptyPasses = function () {
  19338. this._renderPasses.length = 0;
  19339. this._linkParameters();
  19340. };
  19341. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  19342. var cameraKey;
  19343. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19344. for (var i = 0; i < _cam.length; i++) {
  19345. var camera = _cam[i];
  19346. var cameraName = camera.name;
  19347. if (this._singleInstance) {
  19348. cameraKey = 0;
  19349. } else {
  19350. cameraKey = cameraName;
  19351. }
  19352. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  19353. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  19354. if (!this._indicesForCamera[cameraName]) {
  19355. this._indicesForCamera[cameraName] = [];
  19356. }
  19357. this._indicesForCamera[cameraName].push(index);
  19358. if (this._cameras.indexOf(camera) === -1) {
  19359. this._cameras[cameraName] = camera;
  19360. }
  19361. for (var passName in this._renderPasses) {
  19362. this._renderPasses[passName]._incRefCount();
  19363. }
  19364. }
  19365. this._linkParameters();
  19366. };
  19367. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  19368. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19369. for (var i = 0; i < _cam.length; i++) {
  19370. var camera = _cam[i];
  19371. var cameraName = camera.name;
  19372. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19373. var index = this._cameras.indexOf(cameraName);
  19374. this._indicesForCamera.splice(index, 1);
  19375. this._cameras.splice(index, 1);
  19376. for (var passName in this._renderPasses) {
  19377. this._renderPasses[passName]._decRefCount();
  19378. }
  19379. }
  19380. };
  19381. PostProcessRenderEffect.prototype._enable = function (cameras) {
  19382. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19383. for (var i = 0; i < _cam.length; i++) {
  19384. var camera = _cam[i];
  19385. var cameraName = camera.name;
  19386. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  19387. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  19388. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  19389. }
  19390. }
  19391. for (var passName in this._renderPasses) {
  19392. this._renderPasses[passName]._incRefCount();
  19393. }
  19394. }
  19395. };
  19396. PostProcessRenderEffect.prototype._disable = function (cameras) {
  19397. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19398. for (var i = 0; i < _cam.length; i++) {
  19399. var camera = _cam[i];
  19400. var cameraName = camera.Name;
  19401. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  19402. for (var passName in this._renderPasses) {
  19403. this._renderPasses[passName]._decRefCount();
  19404. }
  19405. }
  19406. };
  19407. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  19408. if (this._singleInstance) {
  19409. return this._postProcesses[0];
  19410. } else {
  19411. return this._postProcesses[camera.name];
  19412. }
  19413. };
  19414. PostProcessRenderEffect.prototype._linkParameters = function () {
  19415. var _this = this;
  19416. for (var index in this._postProcesses) {
  19417. if (this.applyParameters) {
  19418. this.applyParameters(this._postProcesses[index]);
  19419. }
  19420. this._postProcesses[index].onBeforeRender = function (effect) {
  19421. _this._linkTextures(effect);
  19422. };
  19423. }
  19424. };
  19425. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  19426. for (var renderPassName in this._renderPasses) {
  19427. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  19428. }
  19429. for (var renderEffectName in this._renderEffectAsPasses) {
  19430. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  19431. }
  19432. };
  19433. return PostProcessRenderEffect;
  19434. })();
  19435. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  19436. })(BABYLON || (BABYLON = {}));
  19437. var BABYLON;
  19438. (function (BABYLON) {
  19439. var PostProcessRenderPipeline = (function () {
  19440. function PostProcessRenderPipeline(engine, name) {
  19441. this._engine = engine;
  19442. this._name = name;
  19443. this._renderEffects = [];
  19444. this._renderEffectsForIsolatedPass = [];
  19445. this._cameras = [];
  19446. }
  19447. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  19448. this._renderEffects[renderEffect._name] = renderEffect;
  19449. };
  19450. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  19451. var renderEffects = this._renderEffects[renderEffectName];
  19452. if (!renderEffects) {
  19453. return;
  19454. }
  19455. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19456. };
  19457. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  19458. var renderEffects = this._renderEffects[renderEffectName];
  19459. if (!renderEffects) {
  19460. return;
  19461. }
  19462. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  19463. };
  19464. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  19465. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19466. var indicesToDelete = [];
  19467. for (var i = 0; i < _cam.length; i++) {
  19468. var camera = _cam[i];
  19469. var cameraName = camera.name;
  19470. if (this._cameras.indexOf(camera) === -1) {
  19471. this._cameras[cameraName] = camera;
  19472. } else if (unique) {
  19473. indicesToDelete.push(i);
  19474. }
  19475. }
  19476. for (var i = 0; i < indicesToDelete.length; i++) {
  19477. cameras.splice(indicesToDelete[i], 1);
  19478. }
  19479. for (var renderEffectName in this._renderEffects) {
  19480. this._renderEffects[renderEffectName]._attachCameras(_cam);
  19481. }
  19482. };
  19483. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  19484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19485. for (var renderEffectName in this._renderEffects) {
  19486. this._renderEffects[renderEffectName]._detachCameras(_cam);
  19487. }
  19488. for (var i = 0; i < _cam.length; i++) {
  19489. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  19490. }
  19491. };
  19492. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  19493. var _this = this;
  19494. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19495. var pass = null;
  19496. for (var renderEffectName in this._renderEffects) {
  19497. pass = this._renderEffects[renderEffectName].getPass(passName);
  19498. if (pass != null) {
  19499. break;
  19500. }
  19501. }
  19502. if (pass === null) {
  19503. return;
  19504. }
  19505. for (var renderEffectName in this._renderEffects) {
  19506. this._renderEffects[renderEffectName]._disable(_cam);
  19507. }
  19508. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  19509. for (var i = 0; i < _cam.length; i++) {
  19510. var camera = _cam[i];
  19511. var cameraName = camera.name;
  19512. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19513. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19514. });
  19515. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  19516. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  19517. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  19518. }
  19519. };
  19520. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  19521. var _this = this;
  19522. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  19523. for (var i = 0; i < _cam.length; i++) {
  19524. var camera = _cam[i];
  19525. var cameraName = camera.name;
  19526. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  19527. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  19528. });
  19529. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  19530. }
  19531. for (var renderEffectName in this._renderEffects) {
  19532. this._renderEffects[renderEffectName]._enable(_cam);
  19533. }
  19534. };
  19535. PostProcessRenderPipeline.prototype._update = function () {
  19536. for (var renderEffectName in this._renderEffects) {
  19537. this._renderEffects[renderEffectName]._update();
  19538. }
  19539. for (var i = 0; i < this._cameras.length; i++) {
  19540. var cameraName = this._cameras[i].name;
  19541. if (this._renderEffectsForIsolatedPass[cameraName]) {
  19542. this._renderEffectsForIsolatedPass[cameraName]._update();
  19543. }
  19544. }
  19545. };
  19546. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  19547. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  19548. return PostProcessRenderPipeline;
  19549. })();
  19550. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  19551. })(BABYLON || (BABYLON = {}));
  19552. var BABYLON;
  19553. (function (BABYLON) {
  19554. var PostProcessRenderPipelineManager = (function () {
  19555. function PostProcessRenderPipelineManager() {
  19556. this._renderPipelines = new Array();
  19557. }
  19558. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  19559. this._renderPipelines[renderPipeline._name] = renderPipeline;
  19560. };
  19561. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  19562. var renderPipeline = this._renderPipelines[renderPipelineName];
  19563. if (!renderPipeline) {
  19564. return;
  19565. }
  19566. renderPipeline._attachCameras(cameras, unique);
  19567. };
  19568. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  19569. var renderPipeline = this._renderPipelines[renderPipelineName];
  19570. if (!renderPipeline) {
  19571. return;
  19572. }
  19573. renderPipeline._detachCameras(cameras);
  19574. };
  19575. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19576. var renderPipeline = this._renderPipelines[renderPipelineName];
  19577. if (!renderPipeline) {
  19578. return;
  19579. }
  19580. renderPipeline._enableEffect(renderEffectName, cameras);
  19581. };
  19582. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  19583. var renderPipeline = this._renderPipelines[renderPipelineName];
  19584. if (!renderPipeline) {
  19585. return;
  19586. }
  19587. renderPipeline._disableEffect(renderEffectName, cameras);
  19588. };
  19589. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  19590. var renderPipeline = this._renderPipelines[renderPipelineName];
  19591. if (!renderPipeline) {
  19592. return;
  19593. }
  19594. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  19595. };
  19596. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  19597. var renderPipeline = this._renderPipelines[renderPipelineName];
  19598. if (!renderPipeline) {
  19599. return;
  19600. }
  19601. renderPipeline._disableDisplayOnlyPass(cameras);
  19602. };
  19603. PostProcessRenderPipelineManager.prototype.update = function () {
  19604. for (var renderPipelineName in this._renderPipelines) {
  19605. this._renderPipelines[renderPipelineName]._update();
  19606. }
  19607. };
  19608. return PostProcessRenderPipelineManager;
  19609. })();
  19610. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  19611. })(BABYLON || (BABYLON = {}));
  19612. var __extends = this.__extends || function (d, b) {
  19613. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19614. function __() { this.constructor = d; }
  19615. __.prototype = b.prototype;
  19616. d.prototype = new __();
  19617. };
  19618. var BABYLON;
  19619. (function (BABYLON) {
  19620. var DisplayPassPostProcess = (function (_super) {
  19621. __extends(DisplayPassPostProcess, _super);
  19622. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  19623. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  19624. }
  19625. return DisplayPassPostProcess;
  19626. })(BABYLON.PostProcess);
  19627. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  19628. })(BABYLON || (BABYLON = {}));
  19629. var BABYLON;
  19630. (function (BABYLON) {
  19631. var BoundingBoxRenderer = (function () {
  19632. function BoundingBoxRenderer(scene) {
  19633. this.frontColor = new BABYLON.Color3(1, 1, 1);
  19634. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  19635. this.showBackLines = true;
  19636. this.renderList = new BABYLON.SmartArray(32);
  19637. this._scene = scene;
  19638. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  19639. attributes: ["position"],
  19640. uniforms: ["worldViewProjection", "color"]
  19641. });
  19642. var engine = this._scene.getEngine();
  19643. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  19644. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  19645. 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]);
  19646. }
  19647. BoundingBoxRenderer.prototype.reset = function () {
  19648. this.renderList.reset();
  19649. };
  19650. BoundingBoxRenderer.prototype.render = function () {
  19651. if (this.renderList.length == 0 || !this._colorShader.isReady()) {
  19652. return;
  19653. }
  19654. var engine = this._scene.getEngine();
  19655. engine.setDepthWrite(false);
  19656. this._colorShader._preBind();
  19657. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  19658. var boundingBox = this.renderList.data[boundingBoxIndex];
  19659. var min = boundingBox.minimum;
  19660. var max = boundingBox.maximum;
  19661. var diff = max.subtract(min);
  19662. var median = min.add(diff.scale(0.5));
  19663. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  19664. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  19665. if (this.showBackLines) {
  19666. engine.setDepthFunctionToGreaterOrEqual();
  19667. this._colorShader.setColor4("color", this.backColor.toColor4());
  19668. this._colorShader.bind(worldMatrix);
  19669. engine.draw(false, 0, 24);
  19670. }
  19671. engine.setDepthFunctionToLess();
  19672. this._colorShader.setColor4("color", this.frontColor.toColor4());
  19673. this._colorShader.bind(worldMatrix);
  19674. engine.draw(false, 0, 24);
  19675. }
  19676. this._colorShader.unbind();
  19677. engine.setDepthFunctionToLessOrEqual();
  19678. engine.setDepthWrite(true);
  19679. };
  19680. BoundingBoxRenderer.prototype.dispose = function () {
  19681. this._colorShader.dispose();
  19682. this._vb.dispose();
  19683. this._scene.getEngine()._releaseBuffer(this._ib);
  19684. };
  19685. return BoundingBoxRenderer;
  19686. })();
  19687. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  19688. })(BABYLON || (BABYLON = {}));
  19689. /**
  19690. * Based on jsTGALoader - Javascript loader for TGA file
  19691. * By Vincent Thibault
  19692. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  19693. */
  19694. var BABYLON;
  19695. (function (BABYLON) {
  19696. (function (Internals) {
  19697. var TGATools = (function () {
  19698. function TGATools() {
  19699. }
  19700. TGATools.GetTGAHeader = function (data) {
  19701. var offset = 0;
  19702. var header = {
  19703. id_length: data[offset++],
  19704. colormap_type: data[offset++],
  19705. image_type: data[offset++],
  19706. colormap_index: data[offset++] | data[offset++] << 8,
  19707. colormap_length: data[offset++] | data[offset++] << 8,
  19708. colormap_size: data[offset++],
  19709. origin: [
  19710. data[offset++] | data[offset++] << 8,
  19711. data[offset++] | data[offset++] << 8
  19712. ],
  19713. width: data[offset++] | data[offset++] << 8,
  19714. height: data[offset++] | data[offset++] << 8,
  19715. pixel_size: data[offset++],
  19716. flags: data[offset++]
  19717. };
  19718. return header;
  19719. };
  19720. TGATools.UploadContent = function (gl, data) {
  19721. if (data.length < 19) {
  19722. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  19723. return;
  19724. }
  19725. var offset = 18;
  19726. var header = TGATools.GetTGAHeader(data);
  19727. if (header.id_length + offset > data.length) {
  19728. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  19729. return;
  19730. }
  19731. offset += header.id_length;
  19732. var use_rle = false;
  19733. var use_pal = false;
  19734. var use_rgb = false;
  19735. var use_grey = false;
  19736. switch (header.image_type) {
  19737. case TGATools._TYPE_RLE_INDEXED:
  19738. use_rle = true;
  19739. case TGATools._TYPE_INDEXED:
  19740. use_pal = true;
  19741. break;
  19742. case TGATools._TYPE_RLE_RGB:
  19743. use_rle = true;
  19744. case TGATools._TYPE_RGB:
  19745. use_rgb = true;
  19746. break;
  19747. case TGATools._TYPE_RLE_GREY:
  19748. use_rle = true;
  19749. case TGATools._TYPE_GREY:
  19750. use_grey = true;
  19751. break;
  19752. }
  19753. var pixel_data;
  19754. var numAlphaBits = header.flags & 0xf;
  19755. var pixel_size = header.pixel_size >> 3;
  19756. var pixel_total = header.width * header.height * pixel_size;
  19757. var palettes;
  19758. if (use_pal) {
  19759. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  19760. }
  19761. if (use_rle) {
  19762. pixel_data = new Uint8Array(pixel_total);
  19763. var c, count, i;
  19764. var localOffset = 0;
  19765. var pixels = new Uint8Array(pixel_size);
  19766. while (offset < pixel_total && localOffset < pixel_total) {
  19767. c = data[offset++];
  19768. count = (c & 0x7f) + 1;
  19769. if (c & 0x80) {
  19770. for (i = 0; i < pixel_size; ++i) {
  19771. pixels[i] = data[offset++];
  19772. }
  19773. for (i = 0; i < count; ++i) {
  19774. pixel_data.set(pixels, localOffset + i * pixel_size);
  19775. }
  19776. localOffset += pixel_size * count;
  19777. } else {
  19778. count *= pixel_size;
  19779. for (i = 0; i < count; ++i) {
  19780. pixel_data[localOffset + i] = data[offset++];
  19781. }
  19782. localOffset += count;
  19783. }
  19784. }
  19785. } else {
  19786. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  19787. }
  19788. var x_start, y_start, x_step, y_step, y_end, x_end;
  19789. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  19790. default:
  19791. case TGATools._ORIGIN_UL:
  19792. x_start = 0;
  19793. x_step = 1;
  19794. x_end = header.width;
  19795. y_start = 0;
  19796. y_step = 1;
  19797. y_end = header.height;
  19798. break;
  19799. case TGATools._ORIGIN_BL:
  19800. x_start = 0;
  19801. x_step = 1;
  19802. x_end = header.width;
  19803. y_start = header.height - 1;
  19804. y_step = -1;
  19805. y_end = -1;
  19806. break;
  19807. case TGATools._ORIGIN_UR:
  19808. x_start = header.width - 1;
  19809. x_step = -1;
  19810. x_end = -1;
  19811. y_start = 0;
  19812. y_step = 1;
  19813. y_end = header.height;
  19814. break;
  19815. case TGATools._ORIGIN_BR:
  19816. x_start = header.width - 1;
  19817. x_step = -1;
  19818. x_end = -1;
  19819. y_start = header.height - 1;
  19820. y_step = -1;
  19821. y_end = -1;
  19822. break;
  19823. }
  19824. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  19825. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  19826. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  19827. };
  19828. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19829. var image = pixel_data, colormap = palettes;
  19830. var width = header.width, height = header.height;
  19831. var color, i = 0, x, y;
  19832. var imageData = new Uint8Array(width * height * 4);
  19833. for (y = y_start; y !== y_end; y += y_step) {
  19834. for (x = x_start; x !== x_end; x += x_step, i++) {
  19835. color = image[i];
  19836. imageData[(x + width * y) * 4 + 3] = 255;
  19837. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  19838. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  19839. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  19840. }
  19841. }
  19842. return imageData;
  19843. };
  19844. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19845. var image = pixel_data;
  19846. var width = header.width, height = header.height;
  19847. var color, i = 0, x, y;
  19848. var imageData = new Uint8Array(width * height * 4);
  19849. for (y = y_start; y !== y_end; y += y_step) {
  19850. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19851. color = image[i + 0] + (image[i + 1] << 8);
  19852. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  19853. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  19854. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  19855. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  19856. }
  19857. }
  19858. return imageData;
  19859. };
  19860. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19861. var image = pixel_data;
  19862. var width = header.width, height = header.height;
  19863. var i = 0, x, y;
  19864. var imageData = new Uint8Array(width * height * 4);
  19865. for (y = y_start; y !== y_end; y += y_step) {
  19866. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  19867. imageData[(x + width * y) * 4 + 3] = 255;
  19868. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19869. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19870. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19871. }
  19872. }
  19873. return imageData;
  19874. };
  19875. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19876. var image = pixel_data;
  19877. var width = header.width, height = header.height;
  19878. var i = 0, x, y;
  19879. var imageData = new Uint8Array(width * height * 4);
  19880. for (y = y_start; y !== y_end; y += y_step) {
  19881. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  19882. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19883. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  19884. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  19885. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  19886. }
  19887. }
  19888. return imageData;
  19889. };
  19890. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19891. var image = pixel_data;
  19892. var width = header.width, height = header.height;
  19893. var color, i = 0, x, y;
  19894. var imageData = new Uint8Array(width * height * 4);
  19895. for (y = y_start; y !== y_end; y += y_step) {
  19896. for (x = x_start; x !== x_end; x += x_step, i++) {
  19897. color = image[i];
  19898. imageData[(x + width * y) * 4 + 0] = color;
  19899. imageData[(x + width * y) * 4 + 1] = color;
  19900. imageData[(x + width * y) * 4 + 2] = color;
  19901. imageData[(x + width * y) * 4 + 3] = 255;
  19902. }
  19903. }
  19904. return imageData;
  19905. };
  19906. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  19907. var image = pixel_data;
  19908. var width = header.width, height = header.height;
  19909. var i = 0, x, y;
  19910. var imageData = new Uint8Array(width * height * 4);
  19911. for (y = y_start; y !== y_end; y += y_step) {
  19912. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  19913. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  19914. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  19915. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  19916. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  19917. }
  19918. }
  19919. return imageData;
  19920. };
  19921. TGATools._TYPE_NO_DATA = 0;
  19922. TGATools._TYPE_INDEXED = 1;
  19923. TGATools._TYPE_RGB = 2;
  19924. TGATools._TYPE_GREY = 3;
  19925. TGATools._TYPE_RLE_INDEXED = 9;
  19926. TGATools._TYPE_RLE_RGB = 10;
  19927. TGATools._TYPE_RLE_GREY = 11;
  19928. TGATools._ORIGIN_MASK = 0x30;
  19929. TGATools._ORIGIN_SHIFT = 0x04;
  19930. TGATools._ORIGIN_BL = 0x00;
  19931. TGATools._ORIGIN_BR = 0x01;
  19932. TGATools._ORIGIN_UL = 0x02;
  19933. TGATools._ORIGIN_UR = 0x03;
  19934. return TGATools;
  19935. })();
  19936. Internals.TGATools = TGATools;
  19937. })(BABYLON.Internals || (BABYLON.Internals = {}));
  19938. var Internals = BABYLON.Internals;
  19939. })(BABYLON || (BABYLON = {}));
  19940. var BABYLON;
  19941. (function (BABYLON) {
  19942. (function (Internals) {
  19943. var DDS_MAGIC = 0x20534444;
  19944. 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;
  19945. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  19946. 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;
  19947. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  19948. function FourCCToInt32(value) {
  19949. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  19950. }
  19951. function Int32ToFourCC(value) {
  19952. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  19953. }
  19954. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  19955. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  19956. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  19957. var headerLengthInt = 31;
  19958. var off_magic = 0;
  19959. var off_size = 1;
  19960. var off_flags = 2;
  19961. var off_height = 3;
  19962. var off_width = 4;
  19963. var off_mipmapCount = 7;
  19964. var off_pfFlags = 20;
  19965. var off_pfFourCC = 21;
  19966. var off_RGBbpp = 22;
  19967. var off_RMask = 23;
  19968. var off_GMask = 24;
  19969. var off_BMask = 25;
  19970. var off_AMask = 26;
  19971. var off_caps1 = 27;
  19972. var off_caps2 = 28;
  19973. ;
  19974. var DDSTools = (function () {
  19975. function DDSTools() {
  19976. }
  19977. DDSTools.GetDDSInfo = function (arrayBuffer) {
  19978. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  19979. var mipmapCount = 1;
  19980. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  19981. mipmapCount = Math.max(1, header[off_mipmapCount]);
  19982. }
  19983. return {
  19984. width: header[off_width],
  19985. height: header[off_height],
  19986. mipmapCount: mipmapCount,
  19987. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  19988. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  19989. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  19990. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  19991. };
  19992. };
  19993. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  19994. var byteArray = new Uint8Array(dataLength);
  19995. var srcData = new Uint8Array(arrayBuffer);
  19996. var index = 0;
  19997. for (var y = height - 1; y >= 0; y--) {
  19998. for (var x = 0; x < width; x++) {
  19999. var srcPos = dataOffset + (x + y * width) * 4;
  20000. byteArray[index + 2] = srcData[srcPos];
  20001. byteArray[index + 1] = srcData[srcPos + 1];
  20002. byteArray[index] = srcData[srcPos + 2];
  20003. byteArray[index + 3] = srcData[srcPos + 3];
  20004. index += 4;
  20005. }
  20006. }
  20007. return byteArray;
  20008. };
  20009. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20010. var byteArray = new Uint8Array(dataLength);
  20011. var srcData = new Uint8Array(arrayBuffer);
  20012. var index = 0;
  20013. for (var y = height - 1; y >= 0; y--) {
  20014. for (var x = 0; x < width; x++) {
  20015. var srcPos = dataOffset + (x + y * width) * 3;
  20016. byteArray[index + 2] = srcData[srcPos];
  20017. byteArray[index + 1] = srcData[srcPos + 1];
  20018. byteArray[index] = srcData[srcPos + 2];
  20019. index += 3;
  20020. }
  20021. }
  20022. return byteArray;
  20023. };
  20024. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20025. var byteArray = new Uint8Array(dataLength);
  20026. var srcData = new Uint8Array(arrayBuffer);
  20027. var index = 0;
  20028. for (var y = height - 1; y >= 0; y--) {
  20029. for (var x = 0; x < width; x++) {
  20030. var srcPos = dataOffset + (x + y * width);
  20031. byteArray[index] = srcData[srcPos];
  20032. index++;
  20033. }
  20034. }
  20035. return byteArray;
  20036. };
  20037. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  20038. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  20039. if (header[off_magic] != DDS_MAGIC) {
  20040. BABYLON.Tools.Error("Invalid magic number in DDS header");
  20041. return;
  20042. }
  20043. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  20044. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  20045. return;
  20046. }
  20047. if (info.isFourCC) {
  20048. fourCC = header[off_pfFourCC];
  20049. switch (fourCC) {
  20050. case FOURCC_DXT1:
  20051. blockBytes = 8;
  20052. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  20053. break;
  20054. case FOURCC_DXT3:
  20055. blockBytes = 16;
  20056. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  20057. break;
  20058. case FOURCC_DXT5:
  20059. blockBytes = 16;
  20060. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  20061. break;
  20062. default:
  20063. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  20064. return;
  20065. }
  20066. }
  20067. mipmapCount = 1;
  20068. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  20069. mipmapCount = Math.max(1, header[off_mipmapCount]);
  20070. }
  20071. var bpp = header[off_RGBbpp];
  20072. for (var face = 0; face < faces; face++) {
  20073. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  20074. width = header[off_width];
  20075. height = header[off_height];
  20076. dataOffset = header[off_size] + 4;
  20077. for (i = 0; i < mipmapCount; ++i) {
  20078. if (info.isRGB) {
  20079. if (bpp == 24) {
  20080. dataLength = width * height * 3;
  20081. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20082. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  20083. } else {
  20084. dataLength = width * height * 4;
  20085. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20086. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  20087. }
  20088. } else if (info.isLuminance) {
  20089. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  20090. var unpaddedRowSize = width;
  20091. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  20092. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  20093. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  20094. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  20095. } else {
  20096. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  20097. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  20098. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  20099. }
  20100. dataOffset += dataLength;
  20101. width *= 0.5;
  20102. height *= 0.5;
  20103. width = Math.max(1.0, width);
  20104. height = Math.max(1.0, height);
  20105. }
  20106. }
  20107. };
  20108. return DDSTools;
  20109. })();
  20110. Internals.DDSTools = DDSTools;
  20111. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20112. var Internals = BABYLON.Internals;
  20113. })(BABYLON || (BABYLON = {}));
  20114. var BABYLON;
  20115. (function (BABYLON) {
  20116. var SmartArray = (function () {
  20117. function SmartArray(capacity) {
  20118. this.length = 0;
  20119. this._duplicateId = 0;
  20120. this.data = new Array(capacity);
  20121. this._id = SmartArray._GlobalId++;
  20122. }
  20123. SmartArray.prototype.push = function (value) {
  20124. this.data[this.length++] = value;
  20125. if (this.length > this.data.length) {
  20126. this.data.length *= 2;
  20127. }
  20128. if (!value.__smartArrayFlags) {
  20129. value.__smartArrayFlags = {};
  20130. }
  20131. value.__smartArrayFlags[this._id] = this._duplicateId;
  20132. };
  20133. SmartArray.prototype.pushNoDuplicate = function (value) {
  20134. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  20135. return;
  20136. }
  20137. this.push(value);
  20138. };
  20139. SmartArray.prototype.sort = function (compareFn) {
  20140. this.data.sort(compareFn);
  20141. };
  20142. SmartArray.prototype.reset = function () {
  20143. this.length = 0;
  20144. this._duplicateId++;
  20145. };
  20146. SmartArray.prototype.concat = function (array) {
  20147. if (array.length === 0) {
  20148. return;
  20149. }
  20150. if (this.length + array.length > this.data.length) {
  20151. this.data.length = (this.length + array.length) * 2;
  20152. }
  20153. for (var index = 0; index < array.length; index++) {
  20154. this.data[this.length++] = (array.data || array)[index];
  20155. }
  20156. };
  20157. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  20158. if (array.length === 0) {
  20159. return;
  20160. }
  20161. if (this.length + array.length > this.data.length) {
  20162. this.data.length = (this.length + array.length) * 2;
  20163. }
  20164. for (var index = 0; index < array.length; index++) {
  20165. var item = (array.data || array)[index];
  20166. this.pushNoDuplicate(item);
  20167. }
  20168. };
  20169. SmartArray.prototype.indexOf = function (value) {
  20170. var position = this.data.indexOf(value);
  20171. if (position >= this.length) {
  20172. return -1;
  20173. }
  20174. return position;
  20175. };
  20176. SmartArray._GlobalId = 0;
  20177. return SmartArray;
  20178. })();
  20179. BABYLON.SmartArray = SmartArray;
  20180. })(BABYLON || (BABYLON = {}));
  20181. var BABYLON;
  20182. (function (BABYLON) {
  20183. var CannonJSPlugin = (function () {
  20184. function CannonJSPlugin() {
  20185. this._registeredMeshes = [];
  20186. this._physicsMaterials = [];
  20187. this.updateBodyPosition = function (mesh) {
  20188. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20189. var registeredMesh = this._registeredMeshes[index];
  20190. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  20191. var body = registeredMesh.body;
  20192. var center = mesh.getBoundingInfo().boundingBox.center;
  20193. body.position.set(center.x, center.z, center.y);
  20194. body.quaternion.x = mesh.rotationQuaternion.x;
  20195. body.quaternion.z = mesh.rotationQuaternion.y;
  20196. body.quaternion.y = mesh.rotationQuaternion.z;
  20197. body.quaternion.w = -mesh.rotationQuaternion.w;
  20198. return;
  20199. }
  20200. }
  20201. };
  20202. }
  20203. CannonJSPlugin.prototype.initialize = function (iterations) {
  20204. if (typeof iterations === "undefined") { iterations = 10; }
  20205. this._world = new CANNON.World();
  20206. this._world.broadphase = new CANNON.NaiveBroadphase();
  20207. this._world.solver.iterations = iterations;
  20208. };
  20209. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  20210. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  20211. };
  20212. CannonJSPlugin.prototype.runOneStep = function (delta) {
  20213. this._world.step(delta);
  20214. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20215. var registeredMesh = this._registeredMeshes[index];
  20216. if (registeredMesh.isChild) {
  20217. continue;
  20218. }
  20219. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  20220. var deltaPos = registeredMesh.delta;
  20221. if (deltaPos) {
  20222. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  20223. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  20224. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  20225. } else {
  20226. registeredMesh.mesh.position.x = bodyX;
  20227. registeredMesh.mesh.position.y = bodyZ;
  20228. registeredMesh.mesh.position.z = bodyY;
  20229. }
  20230. if (!registeredMesh.mesh.rotationQuaternion) {
  20231. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20232. }
  20233. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  20234. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  20235. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  20236. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  20237. }
  20238. };
  20239. CannonJSPlugin.prototype.setGravity = function (gravity) {
  20240. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  20241. };
  20242. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  20243. this.unregisterMesh(mesh);
  20244. mesh.computeWorldMatrix(true);
  20245. switch (impostor) {
  20246. case BABYLON.PhysicsEngine.SphereImpostor:
  20247. var bbox = mesh.getBoundingInfo().boundingBox;
  20248. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  20249. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  20250. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  20251. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  20252. case BABYLON.PhysicsEngine.BoxImpostor:
  20253. bbox = mesh.getBoundingInfo().boundingBox;
  20254. var min = bbox.minimumWorld;
  20255. var max = bbox.maximumWorld;
  20256. var box = max.subtract(min).scale(0.5);
  20257. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  20258. case BABYLON.PhysicsEngine.PlaneImpostor:
  20259. return this._createPlane(mesh, options);
  20260. case BABYLON.PhysicsEngine.MeshImpostor:
  20261. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20262. var rawFaces = mesh.getIndices();
  20263. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  20264. }
  20265. return null;
  20266. };
  20267. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  20268. var shape = new CANNON.Sphere(radius);
  20269. if (!options) {
  20270. return shape;
  20271. }
  20272. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20273. };
  20274. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  20275. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  20276. if (!options) {
  20277. return shape;
  20278. }
  20279. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20280. };
  20281. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  20282. var shape = new CANNON.Plane();
  20283. if (!options) {
  20284. return shape;
  20285. }
  20286. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20287. };
  20288. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  20289. var verts = [], faces = [];
  20290. mesh.computeWorldMatrix(true);
  20291. for (var i = 0; i < rawVerts.length; i += 3) {
  20292. var transformed = BABYLON.Vector3.Zero();
  20293. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  20294. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  20295. }
  20296. for (var j = 0; j < rawFaces.length; j += 3) {
  20297. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  20298. }
  20299. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  20300. if (!options) {
  20301. return shape;
  20302. }
  20303. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  20304. };
  20305. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  20306. var index;
  20307. var mat;
  20308. for (index = 0; index < this._physicsMaterials.length; index++) {
  20309. mat = this._physicsMaterials[index];
  20310. if (mat.friction === friction && mat.restitution === restitution) {
  20311. return mat;
  20312. }
  20313. }
  20314. var currentMat = new CANNON.Material();
  20315. currentMat.friction = friction;
  20316. currentMat.restitution = restitution;
  20317. this._physicsMaterials.push(currentMat);
  20318. for (index = 0; index < this._physicsMaterials.length; index++) {
  20319. mat = this._physicsMaterials[index];
  20320. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  20321. contactMaterial.contactEquationStiffness = 1e10;
  20322. contactMaterial.contactEquationRegularizationTime = 10;
  20323. this._world.addContactMaterial(contactMaterial);
  20324. }
  20325. return currentMat;
  20326. };
  20327. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  20328. var initialRotation = null;
  20329. if (mesh.rotationQuaternion) {
  20330. initialRotation = mesh.rotationQuaternion.clone();
  20331. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  20332. }
  20333. var bbox = mesh.getBoundingInfo().boundingBox;
  20334. var deltaPosition = mesh.position.subtract(bbox.center);
  20335. var material = this._addMaterial(friction, restitution);
  20336. var body = new CANNON.RigidBody(mass, shape, material);
  20337. if (initialRotation) {
  20338. body.quaternion.x = initialRotation.x;
  20339. body.quaternion.z = initialRotation.y;
  20340. body.quaternion.y = initialRotation.z;
  20341. body.quaternion.w = -initialRotation.w;
  20342. }
  20343. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  20344. this._world.add(body);
  20345. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  20346. return body;
  20347. };
  20348. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  20349. var compoundShape = new CANNON.Compound();
  20350. for (var index = 0; index < parts.length; index++) {
  20351. var mesh = parts[index].mesh;
  20352. var shape = this.registerMesh(mesh, parts[index].impostor);
  20353. if (index == 0) {
  20354. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  20355. } else {
  20356. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  20357. }
  20358. }
  20359. var initialMesh = parts[0].mesh;
  20360. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  20361. body.parts = parts;
  20362. return body;
  20363. };
  20364. CannonJSPlugin.prototype._unbindBody = function (body) {
  20365. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20366. var registeredMesh = this._registeredMeshes[index];
  20367. if (registeredMesh.body === body) {
  20368. registeredMesh.body = null;
  20369. registeredMesh.delta = 0;
  20370. }
  20371. }
  20372. };
  20373. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  20374. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20375. var registeredMesh = this._registeredMeshes[index];
  20376. if (registeredMesh.mesh === mesh) {
  20377. if (registeredMesh.body) {
  20378. this._world.remove(registeredMesh.body);
  20379. this._unbindBody(registeredMesh.body);
  20380. }
  20381. this._registeredMeshes.splice(index, 1);
  20382. return;
  20383. }
  20384. }
  20385. };
  20386. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  20387. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  20388. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  20389. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20390. var registeredMesh = this._registeredMeshes[index];
  20391. if (registeredMesh.mesh === mesh) {
  20392. registeredMesh.body.applyImpulse(impulse, worldPoint);
  20393. return;
  20394. }
  20395. }
  20396. };
  20397. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  20398. var body1 = null, body2 = null;
  20399. for (var index = 0; index < this._registeredMeshes.length; index++) {
  20400. var registeredMesh = this._registeredMeshes[index];
  20401. if (registeredMesh.mesh === mesh1) {
  20402. body1 = registeredMesh.body;
  20403. } else if (registeredMesh.mesh === mesh2) {
  20404. body2 = registeredMesh.body;
  20405. }
  20406. }
  20407. if (!body1 || !body2) {
  20408. return false;
  20409. }
  20410. 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));
  20411. this._world.addConstraint(constraint);
  20412. return true;
  20413. };
  20414. CannonJSPlugin.prototype.dispose = function () {
  20415. while (this._registeredMeshes.length) {
  20416. this.unregisterMesh(this._registeredMeshes[0].mesh);
  20417. }
  20418. };
  20419. CannonJSPlugin.prototype.isSupported = function () {
  20420. return window.CANNON !== undefined;
  20421. };
  20422. return CannonJSPlugin;
  20423. })();
  20424. BABYLON.CannonJSPlugin = CannonJSPlugin;
  20425. })(BABYLON || (BABYLON = {}));
  20426. var __extends = this.__extends || function (d, b) {
  20427. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20428. function __() { this.constructor = d; }
  20429. __.prototype = b.prototype;
  20430. d.prototype = new __();
  20431. };
  20432. var BABYLON;
  20433. (function (BABYLON) {
  20434. var Condition = (function () {
  20435. function Condition(actionManager) {
  20436. this._actionManager = actionManager;
  20437. }
  20438. Condition.prototype.isValid = function () {
  20439. return true;
  20440. };
  20441. Condition.prototype._getProperty = function (propertyPath) {
  20442. return this._actionManager._getProperty(propertyPath);
  20443. };
  20444. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  20445. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20446. };
  20447. return Condition;
  20448. })();
  20449. BABYLON.Condition = Condition;
  20450. var ValueCondition = (function (_super) {
  20451. __extends(ValueCondition, _super);
  20452. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  20453. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  20454. _super.call(this, actionManager);
  20455. this.propertyPath = propertyPath;
  20456. this.value = value;
  20457. this.operator = operator;
  20458. this._target = this._getEffectiveTarget(target, this.propertyPath);
  20459. this._property = this._getProperty(this.propertyPath);
  20460. }
  20461. Object.defineProperty(ValueCondition, "IsEqual", {
  20462. get: function () {
  20463. return ValueCondition._IsEqual;
  20464. },
  20465. enumerable: true,
  20466. configurable: true
  20467. });
  20468. Object.defineProperty(ValueCondition, "IsDifferent", {
  20469. get: function () {
  20470. return ValueCondition._IsDifferent;
  20471. },
  20472. enumerable: true,
  20473. configurable: true
  20474. });
  20475. Object.defineProperty(ValueCondition, "IsGreater", {
  20476. get: function () {
  20477. return ValueCondition._IsGreater;
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(ValueCondition, "IsLesser", {
  20483. get: function () {
  20484. return ValueCondition._IsLesser;
  20485. },
  20486. enumerable: true,
  20487. configurable: true
  20488. });
  20489. ValueCondition.prototype.isValid = function () {
  20490. switch (this.operator) {
  20491. case ValueCondition.IsGreater:
  20492. return this._target[this._property] > this.value;
  20493. case ValueCondition.IsLesser:
  20494. return this._target[this._property] < this.value;
  20495. case ValueCondition.IsEqual:
  20496. case ValueCondition.IsDifferent:
  20497. var check;
  20498. if (this.value.equals) {
  20499. check = this.value.equals(this._target[this._property]);
  20500. } else {
  20501. check = this.value === this._target[this._property];
  20502. }
  20503. return this.operator === ValueCondition.IsEqual ? check : !check;
  20504. }
  20505. return false;
  20506. };
  20507. ValueCondition._IsEqual = 0;
  20508. ValueCondition._IsDifferent = 1;
  20509. ValueCondition._IsGreater = 2;
  20510. ValueCondition._IsLesser = 3;
  20511. return ValueCondition;
  20512. })(Condition);
  20513. BABYLON.ValueCondition = ValueCondition;
  20514. var PredicateCondition = (function (_super) {
  20515. __extends(PredicateCondition, _super);
  20516. function PredicateCondition(actionManager, predicate) {
  20517. _super.call(this, actionManager);
  20518. this.predicate = predicate;
  20519. }
  20520. PredicateCondition.prototype.isValid = function () {
  20521. return this.predicate();
  20522. };
  20523. return PredicateCondition;
  20524. })(Condition);
  20525. BABYLON.PredicateCondition = PredicateCondition;
  20526. var StateCondition = (function (_super) {
  20527. __extends(StateCondition, _super);
  20528. function StateCondition(actionManager, target, value) {
  20529. _super.call(this, actionManager);
  20530. this.value = value;
  20531. this._target = target;
  20532. }
  20533. StateCondition.prototype.isValid = function () {
  20534. return this._target.state === this.value;
  20535. };
  20536. return StateCondition;
  20537. })(Condition);
  20538. BABYLON.StateCondition = StateCondition;
  20539. })(BABYLON || (BABYLON = {}));
  20540. var BABYLON;
  20541. (function (BABYLON) {
  20542. var Action = (function () {
  20543. function Action(triggerOptions, condition) {
  20544. this.triggerOptions = triggerOptions;
  20545. if (triggerOptions.parameter) {
  20546. this.trigger = triggerOptions.trigger;
  20547. this._triggerParameter = triggerOptions.parameter;
  20548. } else {
  20549. this.trigger = triggerOptions;
  20550. }
  20551. this._nextActiveAction = this;
  20552. this._condition = condition;
  20553. }
  20554. Action.prototype._prepare = function () {
  20555. };
  20556. Action.prototype.getTriggerParameter = function () {
  20557. return this._triggerParameter;
  20558. };
  20559. Action.prototype._executeCurrent = function (evt) {
  20560. if (this._condition) {
  20561. var currentRenderId = this._actionManager.getScene().getRenderId();
  20562. if (this._condition._evaluationId === currentRenderId) {
  20563. if (!this._condition._currentResult) {
  20564. return;
  20565. }
  20566. } else {
  20567. this._condition._evaluationId = currentRenderId;
  20568. if (!this._condition.isValid()) {
  20569. this._condition._currentResult = false;
  20570. return;
  20571. }
  20572. this._condition._currentResult = true;
  20573. }
  20574. }
  20575. this._nextActiveAction.execute(evt);
  20576. if (this._nextActiveAction._child) {
  20577. if (!this._nextActiveAction._child._actionManager) {
  20578. this._nextActiveAction._child._actionManager = this._actionManager;
  20579. }
  20580. this._nextActiveAction = this._nextActiveAction._child;
  20581. } else {
  20582. this._nextActiveAction = this;
  20583. }
  20584. };
  20585. Action.prototype.execute = function (evt) {
  20586. };
  20587. Action.prototype.then = function (action) {
  20588. this._child = action;
  20589. action._actionManager = this._actionManager;
  20590. action._prepare();
  20591. return action;
  20592. };
  20593. Action.prototype._getProperty = function (propertyPath) {
  20594. return this._actionManager._getProperty(propertyPath);
  20595. };
  20596. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  20597. return this._actionManager._getEffectiveTarget(target, propertyPath);
  20598. };
  20599. return Action;
  20600. })();
  20601. BABYLON.Action = Action;
  20602. })(BABYLON || (BABYLON = {}));
  20603. var BABYLON;
  20604. (function (BABYLON) {
  20605. var ActionEvent = (function () {
  20606. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  20607. this.source = source;
  20608. this.pointerX = pointerX;
  20609. this.pointerY = pointerY;
  20610. this.meshUnderPointer = meshUnderPointer;
  20611. this.sourceEvent = sourceEvent;
  20612. }
  20613. ActionEvent.CreateNew = function (source) {
  20614. var scene = source.getScene();
  20615. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer);
  20616. };
  20617. ActionEvent.CreateNewFromScene = function (scene, evt) {
  20618. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  20619. };
  20620. return ActionEvent;
  20621. })();
  20622. BABYLON.ActionEvent = ActionEvent;
  20623. var ActionManager = (function () {
  20624. function ActionManager(scene) {
  20625. this.actions = new Array();
  20626. this._scene = scene;
  20627. scene._actionManagers.push(this);
  20628. }
  20629. Object.defineProperty(ActionManager, "NothingTrigger", {
  20630. get: function () {
  20631. return ActionManager._NothingTrigger;
  20632. },
  20633. enumerable: true,
  20634. configurable: true
  20635. });
  20636. Object.defineProperty(ActionManager, "OnPickTrigger", {
  20637. get: function () {
  20638. return ActionManager._OnPickTrigger;
  20639. },
  20640. enumerable: true,
  20641. configurable: true
  20642. });
  20643. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  20644. get: function () {
  20645. return ActionManager._OnLeftPickTrigger;
  20646. },
  20647. enumerable: true,
  20648. configurable: true
  20649. });
  20650. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  20651. get: function () {
  20652. return ActionManager._OnRightPickTrigger;
  20653. },
  20654. enumerable: true,
  20655. configurable: true
  20656. });
  20657. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  20658. get: function () {
  20659. return ActionManager._OnCenterPickTrigger;
  20660. },
  20661. enumerable: true,
  20662. configurable: true
  20663. });
  20664. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  20665. get: function () {
  20666. return ActionManager._OnPointerOverTrigger;
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  20672. get: function () {
  20673. return ActionManager._OnPointerOutTrigger;
  20674. },
  20675. enumerable: true,
  20676. configurable: true
  20677. });
  20678. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  20679. get: function () {
  20680. return ActionManager._OnEveryFrameTrigger;
  20681. },
  20682. enumerable: true,
  20683. configurable: true
  20684. });
  20685. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  20686. get: function () {
  20687. return ActionManager._OnIntersectionEnterTrigger;
  20688. },
  20689. enumerable: true,
  20690. configurable: true
  20691. });
  20692. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  20693. get: function () {
  20694. return ActionManager._OnIntersectionExitTrigger;
  20695. },
  20696. enumerable: true,
  20697. configurable: true
  20698. });
  20699. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  20700. get: function () {
  20701. return ActionManager._OnKeyDownTrigger;
  20702. },
  20703. enumerable: true,
  20704. configurable: true
  20705. });
  20706. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  20707. get: function () {
  20708. return ActionManager._OnKeyUpTrigger;
  20709. },
  20710. enumerable: true,
  20711. configurable: true
  20712. });
  20713. ActionManager.prototype.dispose = function () {
  20714. var index = this._scene._actionManagers.indexOf(this);
  20715. if (index > -1) {
  20716. this._scene._actionManagers.splice(index, 1);
  20717. }
  20718. };
  20719. ActionManager.prototype.getScene = function () {
  20720. return this._scene;
  20721. };
  20722. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  20723. for (var index = 0; index < this.actions.length; index++) {
  20724. var action = this.actions[index];
  20725. if (triggers.indexOf(action.trigger) > -1) {
  20726. return true;
  20727. }
  20728. }
  20729. return false;
  20730. };
  20731. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  20732. get: function () {
  20733. for (var index = 0; index < this.actions.length; index++) {
  20734. var action = this.actions[index];
  20735. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  20736. return true;
  20737. }
  20738. }
  20739. return false;
  20740. },
  20741. enumerable: true,
  20742. configurable: true
  20743. });
  20744. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  20745. get: function () {
  20746. for (var index = 0; index < this.actions.length; index++) {
  20747. var action = this.actions[index];
  20748. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  20749. return true;
  20750. }
  20751. }
  20752. return false;
  20753. },
  20754. enumerable: true,
  20755. configurable: true
  20756. });
  20757. ActionManager.prototype.registerAction = function (action) {
  20758. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  20759. if (this.getScene().actionManager !== this) {
  20760. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  20761. return null;
  20762. }
  20763. }
  20764. this.actions.push(action);
  20765. action._actionManager = this;
  20766. action._prepare();
  20767. return action;
  20768. };
  20769. ActionManager.prototype.processTrigger = function (trigger, evt) {
  20770. for (var index = 0; index < this.actions.length; index++) {
  20771. var action = this.actions[index];
  20772. if (action.trigger === trigger) {
  20773. if (trigger == ActionManager.OnKeyUpTrigger || trigger == ActionManager.OnKeyDownTrigger) {
  20774. var parameter = action.getTriggerParameter();
  20775. if (parameter) {
  20776. if (evt.sourceEvent.key !== parameter) {
  20777. continue;
  20778. }
  20779. }
  20780. }
  20781. action._executeCurrent(evt);
  20782. }
  20783. }
  20784. };
  20785. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  20786. var properties = propertyPath.split(".");
  20787. for (var index = 0; index < properties.length - 1; index++) {
  20788. target = target[properties[index]];
  20789. }
  20790. return target;
  20791. };
  20792. ActionManager.prototype._getProperty = function (propertyPath) {
  20793. var properties = propertyPath.split(".");
  20794. return properties[properties.length - 1];
  20795. };
  20796. ActionManager._NothingTrigger = 0;
  20797. ActionManager._OnPickTrigger = 1;
  20798. ActionManager._OnLeftPickTrigger = 2;
  20799. ActionManager._OnRightPickTrigger = 3;
  20800. ActionManager._OnCenterPickTrigger = 4;
  20801. ActionManager._OnPointerOverTrigger = 5;
  20802. ActionManager._OnPointerOutTrigger = 6;
  20803. ActionManager._OnEveryFrameTrigger = 7;
  20804. ActionManager._OnIntersectionEnterTrigger = 8;
  20805. ActionManager._OnIntersectionExitTrigger = 9;
  20806. ActionManager._OnKeyDownTrigger = 10;
  20807. ActionManager._OnKeyUpTrigger = 11;
  20808. return ActionManager;
  20809. })();
  20810. BABYLON.ActionManager = ActionManager;
  20811. })(BABYLON || (BABYLON = {}));
  20812. var __extends = this.__extends || function (d, b) {
  20813. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20814. function __() { this.constructor = d; }
  20815. __.prototype = b.prototype;
  20816. d.prototype = new __();
  20817. };
  20818. var BABYLON;
  20819. (function (BABYLON) {
  20820. var InterpolateValueAction = (function (_super) {
  20821. __extends(InterpolateValueAction, _super);
  20822. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  20823. if (typeof duration === "undefined") { duration = 1000; }
  20824. _super.call(this, triggerOptions, condition);
  20825. this.propertyPath = propertyPath;
  20826. this.value = value;
  20827. this.duration = duration;
  20828. this.stopOtherAnimations = stopOtherAnimations;
  20829. this._target = target;
  20830. }
  20831. InterpolateValueAction.prototype._prepare = function () {
  20832. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20833. this._property = this._getProperty(this.propertyPath);
  20834. };
  20835. InterpolateValueAction.prototype.execute = function () {
  20836. var scene = this._actionManager.getScene();
  20837. var keys = [
  20838. {
  20839. frame: 0,
  20840. value: this._target[this._property]
  20841. }, {
  20842. frame: 100,
  20843. value: this.value
  20844. }
  20845. ];
  20846. var dataType;
  20847. if (typeof this.value === "number") {
  20848. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  20849. } else if (this.value instanceof BABYLON.Color3) {
  20850. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  20851. } else if (this.value instanceof BABYLON.Vector3) {
  20852. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  20853. } else if (this.value instanceof BABYLON.Matrix) {
  20854. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  20855. } else if (this.value instanceof BABYLON.Quaternion) {
  20856. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  20857. } else {
  20858. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  20859. return;
  20860. }
  20861. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  20862. animation.setKeys(keys);
  20863. if (this.stopOtherAnimations) {
  20864. scene.stopAnimation(this._target);
  20865. }
  20866. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  20867. };
  20868. return InterpolateValueAction;
  20869. })(BABYLON.Action);
  20870. BABYLON.InterpolateValueAction = InterpolateValueAction;
  20871. })(BABYLON || (BABYLON = {}));
  20872. var __extends = this.__extends || function (d, b) {
  20873. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20874. function __() { this.constructor = d; }
  20875. __.prototype = b.prototype;
  20876. d.prototype = new __();
  20877. };
  20878. var BABYLON;
  20879. (function (BABYLON) {
  20880. var SwitchBooleanAction = (function (_super) {
  20881. __extends(SwitchBooleanAction, _super);
  20882. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  20883. _super.call(this, triggerOptions, condition);
  20884. this.propertyPath = propertyPath;
  20885. this._target = target;
  20886. }
  20887. SwitchBooleanAction.prototype._prepare = function () {
  20888. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20889. this._property = this._getProperty(this.propertyPath);
  20890. };
  20891. SwitchBooleanAction.prototype.execute = function () {
  20892. this._target[this._property] = !this._target[this._property];
  20893. };
  20894. return SwitchBooleanAction;
  20895. })(BABYLON.Action);
  20896. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  20897. var SetStateAction = (function (_super) {
  20898. __extends(SetStateAction, _super);
  20899. function SetStateAction(triggerOptions, target, value, condition) {
  20900. _super.call(this, triggerOptions, condition);
  20901. this.value = value;
  20902. this._target = target;
  20903. }
  20904. SetStateAction.prototype.execute = function () {
  20905. this._target.state = this.value;
  20906. };
  20907. return SetStateAction;
  20908. })(BABYLON.Action);
  20909. BABYLON.SetStateAction = SetStateAction;
  20910. var SetValueAction = (function (_super) {
  20911. __extends(SetValueAction, _super);
  20912. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  20913. _super.call(this, triggerOptions, condition);
  20914. this.propertyPath = propertyPath;
  20915. this.value = value;
  20916. this._target = target;
  20917. }
  20918. SetValueAction.prototype._prepare = function () {
  20919. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20920. this._property = this._getProperty(this.propertyPath);
  20921. };
  20922. SetValueAction.prototype.execute = function () {
  20923. this._target[this._property] = this.value;
  20924. };
  20925. return SetValueAction;
  20926. })(BABYLON.Action);
  20927. BABYLON.SetValueAction = SetValueAction;
  20928. var IncrementValueAction = (function (_super) {
  20929. __extends(IncrementValueAction, _super);
  20930. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  20931. _super.call(this, triggerOptions, condition);
  20932. this.propertyPath = propertyPath;
  20933. this.value = value;
  20934. this._target = target;
  20935. }
  20936. IncrementValueAction.prototype._prepare = function () {
  20937. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  20938. this._property = this._getProperty(this.propertyPath);
  20939. if (typeof this._target[this._property] !== "number") {
  20940. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  20941. }
  20942. };
  20943. IncrementValueAction.prototype.execute = function () {
  20944. this._target[this._property] += this.value;
  20945. };
  20946. return IncrementValueAction;
  20947. })(BABYLON.Action);
  20948. BABYLON.IncrementValueAction = IncrementValueAction;
  20949. var PlayAnimationAction = (function (_super) {
  20950. __extends(PlayAnimationAction, _super);
  20951. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  20952. _super.call(this, triggerOptions, condition);
  20953. this.from = from;
  20954. this.to = to;
  20955. this.loop = loop;
  20956. this._target = target;
  20957. }
  20958. PlayAnimationAction.prototype._prepare = function () {
  20959. };
  20960. PlayAnimationAction.prototype.execute = function () {
  20961. var scene = this._actionManager.getScene();
  20962. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  20963. };
  20964. return PlayAnimationAction;
  20965. })(BABYLON.Action);
  20966. BABYLON.PlayAnimationAction = PlayAnimationAction;
  20967. var StopAnimationAction = (function (_super) {
  20968. __extends(StopAnimationAction, _super);
  20969. function StopAnimationAction(triggerOptions, target, condition) {
  20970. _super.call(this, triggerOptions, condition);
  20971. this._target = target;
  20972. }
  20973. StopAnimationAction.prototype._prepare = function () {
  20974. };
  20975. StopAnimationAction.prototype.execute = function () {
  20976. var scene = this._actionManager.getScene();
  20977. scene.stopAnimation(this._target);
  20978. };
  20979. return StopAnimationAction;
  20980. })(BABYLON.Action);
  20981. BABYLON.StopAnimationAction = StopAnimationAction;
  20982. var DoNothingAction = (function (_super) {
  20983. __extends(DoNothingAction, _super);
  20984. function DoNothingAction(triggerOptions, condition) {
  20985. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  20986. _super.call(this, triggerOptions, condition);
  20987. }
  20988. DoNothingAction.prototype.execute = function () {
  20989. };
  20990. return DoNothingAction;
  20991. })(BABYLON.Action);
  20992. BABYLON.DoNothingAction = DoNothingAction;
  20993. var CombineAction = (function (_super) {
  20994. __extends(CombineAction, _super);
  20995. function CombineAction(triggerOptions, children, condition) {
  20996. _super.call(this, triggerOptions, condition);
  20997. this.children = children;
  20998. }
  20999. CombineAction.prototype._prepare = function () {
  21000. for (var index = 0; index < this.children.length; index++) {
  21001. this.children[index]._actionManager = this._actionManager;
  21002. this.children[index]._prepare();
  21003. }
  21004. };
  21005. CombineAction.prototype.execute = function (evt) {
  21006. for (var index = 0; index < this.children.length; index++) {
  21007. this.children[index].execute(evt);
  21008. }
  21009. };
  21010. return CombineAction;
  21011. })(BABYLON.Action);
  21012. BABYLON.CombineAction = CombineAction;
  21013. var ExecuteCodeAction = (function (_super) {
  21014. __extends(ExecuteCodeAction, _super);
  21015. function ExecuteCodeAction(triggerOptions, func, condition) {
  21016. _super.call(this, triggerOptions, condition);
  21017. this.func = func;
  21018. }
  21019. ExecuteCodeAction.prototype.execute = function (evt) {
  21020. this.func(evt);
  21021. };
  21022. return ExecuteCodeAction;
  21023. })(BABYLON.Action);
  21024. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  21025. var SetParentAction = (function (_super) {
  21026. __extends(SetParentAction, _super);
  21027. function SetParentAction(triggerOptions, target, parent, condition) {
  21028. _super.call(this, triggerOptions, condition);
  21029. this._target = target;
  21030. this._parent = parent;
  21031. }
  21032. SetParentAction.prototype._prepare = function () {
  21033. };
  21034. SetParentAction.prototype.execute = function () {
  21035. if (this._target.parent === this._parent) {
  21036. return;
  21037. }
  21038. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  21039. invertParentWorldMatrix.invert();
  21040. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  21041. this._target.parent = this._parent;
  21042. };
  21043. return SetParentAction;
  21044. })(BABYLON.Action);
  21045. BABYLON.SetParentAction = SetParentAction;
  21046. })(BABYLON || (BABYLON = {}));
  21047. var __extends = this.__extends || function (d, b) {
  21048. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21049. function __() { this.constructor = d; }
  21050. __.prototype = b.prototype;
  21051. d.prototype = new __();
  21052. };
  21053. var BABYLON;
  21054. (function (BABYLON) {
  21055. var Geometry = (function () {
  21056. function Geometry(id, scene, vertexData, updatable, mesh) {
  21057. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21058. this._totalVertices = 0;
  21059. this._indices = [];
  21060. this.id = id;
  21061. this._engine = scene.getEngine();
  21062. this._meshes = [];
  21063. this._scene = scene;
  21064. if (vertexData) {
  21065. this.setAllVerticesData(vertexData, updatable);
  21066. } else {
  21067. this._totalVertices = 0;
  21068. this._indices = [];
  21069. }
  21070. if (mesh) {
  21071. this.applyToMesh(mesh);
  21072. }
  21073. }
  21074. Geometry.prototype.getScene = function () {
  21075. return this._scene;
  21076. };
  21077. Geometry.prototype.getEngine = function () {
  21078. return this._engine;
  21079. };
  21080. Geometry.prototype.isReady = function () {
  21081. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  21082. };
  21083. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  21084. vertexData.applyToGeometry(this, updatable);
  21085. };
  21086. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21087. this._vertexBuffers = this._vertexBuffers || {};
  21088. if (this._vertexBuffers[kind]) {
  21089. this._vertexBuffers[kind].dispose();
  21090. }
  21091. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  21092. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21093. stride = this._vertexBuffers[kind].getStrideSize();
  21094. this._totalVertices = data.length / stride;
  21095. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  21096. var meshes = this._meshes;
  21097. var numOfMeshes = meshes.length;
  21098. for (var index = 0; index < numOfMeshes; index++) {
  21099. var mesh = meshes[index];
  21100. mesh._resetPointsArrayCache();
  21101. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21102. mesh._createGlobalSubMesh();
  21103. mesh.computeWorldMatrix(true);
  21104. }
  21105. }
  21106. };
  21107. Geometry.prototype.updateVerticesDataDirectly = function (kind, data) {
  21108. var vertexBuffer = this.getVertexBuffer(kind);
  21109. if (!vertexBuffer) {
  21110. return;
  21111. }
  21112. vertexBuffer.updateDirectly(data);
  21113. };
  21114. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  21115. var vertexBuffer = this.getVertexBuffer(kind);
  21116. if (!vertexBuffer) {
  21117. return;
  21118. }
  21119. vertexBuffer.update(data);
  21120. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21121. var extend;
  21122. if (updateExtends) {
  21123. var stride = vertexBuffer.getStrideSize();
  21124. this._totalVertices = data.length / stride;
  21125. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  21126. }
  21127. var meshes = this._meshes;
  21128. var numOfMeshes = meshes.length;
  21129. for (var index = 0; index < numOfMeshes; index++) {
  21130. var mesh = meshes[index];
  21131. mesh._resetPointsArrayCache();
  21132. if (updateExtends) {
  21133. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21134. }
  21135. }
  21136. }
  21137. };
  21138. Geometry.prototype.getTotalVertices = function () {
  21139. if (!this.isReady()) {
  21140. return 0;
  21141. }
  21142. return this._totalVertices;
  21143. };
  21144. Geometry.prototype.getVerticesData = function (kind) {
  21145. var vertexBuffer = this.getVertexBuffer(kind);
  21146. if (!vertexBuffer) {
  21147. return null;
  21148. }
  21149. return vertexBuffer.getData();
  21150. };
  21151. Geometry.prototype.getVertexBuffer = function (kind) {
  21152. if (!this.isReady()) {
  21153. return null;
  21154. }
  21155. return this._vertexBuffers[kind];
  21156. };
  21157. Geometry.prototype.getVertexBuffers = function () {
  21158. if (!this.isReady()) {
  21159. return null;
  21160. }
  21161. return this._vertexBuffers;
  21162. };
  21163. Geometry.prototype.isVerticesDataPresent = function (kind) {
  21164. if (!this._vertexBuffers) {
  21165. if (this._delayInfo) {
  21166. return this._delayInfo.indexOf(kind) !== -1;
  21167. }
  21168. return false;
  21169. }
  21170. return this._vertexBuffers[kind] !== undefined;
  21171. };
  21172. Geometry.prototype.getVerticesDataKinds = function () {
  21173. var result = [];
  21174. if (!this._vertexBuffers && this._delayInfo) {
  21175. for (var kind in this._delayInfo) {
  21176. result.push(kind);
  21177. }
  21178. } else {
  21179. for (kind in this._vertexBuffers) {
  21180. result.push(kind);
  21181. }
  21182. }
  21183. return result;
  21184. };
  21185. Geometry.prototype.setIndices = function (indices) {
  21186. if (this._indexBuffer) {
  21187. this._engine._releaseBuffer(this._indexBuffer);
  21188. }
  21189. this._indices = indices;
  21190. if (this._meshes.length !== 0 && this._indices) {
  21191. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  21192. }
  21193. var meshes = this._meshes;
  21194. var numOfMeshes = meshes.length;
  21195. for (var index = 0; index < numOfMeshes; index++) {
  21196. meshes[index]._createGlobalSubMesh();
  21197. }
  21198. };
  21199. Geometry.prototype.getTotalIndices = function () {
  21200. if (!this.isReady()) {
  21201. return 0;
  21202. }
  21203. return this._indices.length;
  21204. };
  21205. Geometry.prototype.getIndices = function () {
  21206. if (!this.isReady()) {
  21207. return null;
  21208. }
  21209. return this._indices;
  21210. };
  21211. Geometry.prototype.getIndexBuffer = function () {
  21212. if (!this.isReady()) {
  21213. return null;
  21214. }
  21215. return this._indexBuffer;
  21216. };
  21217. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  21218. var meshes = this._meshes;
  21219. var index = meshes.indexOf(mesh);
  21220. if (index === -1) {
  21221. return;
  21222. }
  21223. for (var kind in this._vertexBuffers) {
  21224. this._vertexBuffers[kind].dispose();
  21225. }
  21226. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  21227. this._indexBuffer = null;
  21228. }
  21229. meshes.splice(index, 1);
  21230. mesh._geometry = null;
  21231. if (meshes.length == 0 && shouldDispose) {
  21232. this.dispose();
  21233. }
  21234. };
  21235. Geometry.prototype.applyToMesh = function (mesh) {
  21236. if (mesh._geometry === this) {
  21237. return;
  21238. }
  21239. var previousGeometry = mesh._geometry;
  21240. if (previousGeometry) {
  21241. previousGeometry.releaseForMesh(mesh);
  21242. }
  21243. var meshes = this._meshes;
  21244. mesh._geometry = this;
  21245. this._scene.pushGeometry(this);
  21246. meshes.push(mesh);
  21247. if (this.isReady()) {
  21248. this._applyToMesh(mesh);
  21249. } else {
  21250. mesh._boundingInfo = this._boundingInfo;
  21251. }
  21252. };
  21253. Geometry.prototype._applyToMesh = function (mesh) {
  21254. var numOfMeshes = this._meshes.length;
  21255. for (var kind in this._vertexBuffers) {
  21256. if (numOfMeshes === 1) {
  21257. this._vertexBuffers[kind].create();
  21258. }
  21259. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  21260. if (kind === BABYLON.VertexBuffer.PositionKind) {
  21261. mesh._resetPointsArrayCache();
  21262. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  21263. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21264. mesh._createGlobalSubMesh();
  21265. }
  21266. }
  21267. if (numOfMeshes === 1 && this._indices) {
  21268. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  21269. }
  21270. if (this._indexBuffer) {
  21271. this._indexBuffer.references = numOfMeshes;
  21272. }
  21273. };
  21274. Geometry.prototype.load = function (scene, onLoaded) {
  21275. var _this = this;
  21276. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21277. return;
  21278. }
  21279. if (this.isReady()) {
  21280. if (onLoaded) {
  21281. onLoaded();
  21282. }
  21283. return;
  21284. }
  21285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21286. scene._addPendingData(this);
  21287. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21288. _this._delayLoadingFunction(JSON.parse(data), _this);
  21289. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21290. _this._delayInfo = [];
  21291. scene._removePendingData(_this);
  21292. var meshes = _this._meshes;
  21293. var numOfMeshes = meshes.length;
  21294. for (var index = 0; index < numOfMeshes; index++) {
  21295. _this._applyToMesh(meshes[index]);
  21296. }
  21297. if (onLoaded) {
  21298. onLoaded();
  21299. }
  21300. }, function () {
  21301. }, scene.database);
  21302. };
  21303. Geometry.prototype.dispose = function () {
  21304. var meshes = this._meshes;
  21305. var numOfMeshes = meshes.length;
  21306. for (var index = 0; index < numOfMeshes; index++) {
  21307. this.releaseForMesh(meshes[index]);
  21308. }
  21309. this._meshes = [];
  21310. for (var kind in this._vertexBuffers) {
  21311. this._vertexBuffers[kind].dispose();
  21312. }
  21313. this._vertexBuffers = [];
  21314. this._totalVertices = 0;
  21315. if (this._indexBuffer) {
  21316. this._engine._releaseBuffer(this._indexBuffer);
  21317. }
  21318. this._indexBuffer = null;
  21319. this._indices = [];
  21320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21321. this.delayLoadingFile = null;
  21322. this._delayLoadingFunction = null;
  21323. this._delayInfo = [];
  21324. this._boundingInfo = null;
  21325. var geometries = this._scene.getGeometries();
  21326. index = geometries.indexOf(this);
  21327. if (index > -1) {
  21328. geometries.splice(index, 1);
  21329. }
  21330. };
  21331. Geometry.prototype.copy = function (id) {
  21332. var vertexData = new BABYLON.VertexData();
  21333. vertexData.indices = [];
  21334. var indices = this.getIndices();
  21335. for (var index = 0; index < indices.length; index++) {
  21336. vertexData.indices.push(indices[index]);
  21337. }
  21338. var updatable = false;
  21339. var stopChecking = false;
  21340. for (var kind in this._vertexBuffers) {
  21341. vertexData.set(this.getVerticesData(kind), kind);
  21342. if (!stopChecking) {
  21343. updatable = this.getVertexBuffer(kind).isUpdatable();
  21344. stopChecking = !updatable;
  21345. }
  21346. }
  21347. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  21348. geometry.delayLoadState = this.delayLoadState;
  21349. geometry.delayLoadingFile = this.delayLoadingFile;
  21350. geometry._delayLoadingFunction = this._delayLoadingFunction;
  21351. for (kind in this._delayInfo) {
  21352. geometry._delayInfo = geometry._delayInfo || [];
  21353. geometry._delayInfo.push(kind);
  21354. }
  21355. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  21356. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21357. return geometry;
  21358. };
  21359. Geometry.ExtractFromMesh = function (mesh, id) {
  21360. var geometry = mesh._geometry;
  21361. if (!geometry) {
  21362. return null;
  21363. }
  21364. return geometry.copy(id);
  21365. };
  21366. Geometry.RandomId = function () {
  21367. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  21368. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  21369. return v.toString(16);
  21370. });
  21371. };
  21372. return Geometry;
  21373. })();
  21374. BABYLON.Geometry = Geometry;
  21375. (function (Geometry) {
  21376. (function (Primitives) {
  21377. var _Primitive = (function (_super) {
  21378. __extends(_Primitive, _super);
  21379. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  21380. this._beingRegenerated = true;
  21381. this._canBeRegenerated = canBeRegenerated;
  21382. _super.call(this, id, scene, vertexData, false, mesh);
  21383. this._beingRegenerated = false;
  21384. }
  21385. _Primitive.prototype.canBeRegenerated = function () {
  21386. return this._canBeRegenerated;
  21387. };
  21388. _Primitive.prototype.regenerate = function () {
  21389. if (!this._canBeRegenerated) {
  21390. return;
  21391. }
  21392. this._beingRegenerated = true;
  21393. this.setAllVerticesData(this._regenerateVertexData(), false);
  21394. this._beingRegenerated = false;
  21395. };
  21396. _Primitive.prototype.asNewGeometry = function (id) {
  21397. return _super.prototype.copy.call(this, id);
  21398. };
  21399. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  21400. if (!this._beingRegenerated) {
  21401. return;
  21402. }
  21403. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  21404. };
  21405. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  21406. if (!this._beingRegenerated) {
  21407. return;
  21408. }
  21409. _super.prototype.setVerticesData.call(this, kind, data, false);
  21410. };
  21411. _Primitive.prototype._regenerateVertexData = function () {
  21412. throw new Error("Abstract method");
  21413. };
  21414. _Primitive.prototype.copy = function (id) {
  21415. throw new Error("Must be overriden in sub-classes.");
  21416. };
  21417. return _Primitive;
  21418. })(Geometry);
  21419. Primitives._Primitive = _Primitive;
  21420. var Box = (function (_super) {
  21421. __extends(Box, _super);
  21422. function Box(id, scene, size, canBeRegenerated, mesh) {
  21423. this.size = size;
  21424. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21425. }
  21426. Box.prototype._regenerateVertexData = function () {
  21427. return BABYLON.VertexData.CreateBox(this.size);
  21428. };
  21429. Box.prototype.copy = function (id) {
  21430. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21431. };
  21432. return Box;
  21433. })(_Primitive);
  21434. Primitives.Box = Box;
  21435. var Sphere = (function (_super) {
  21436. __extends(Sphere, _super);
  21437. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  21438. this.segments = segments;
  21439. this.diameter = diameter;
  21440. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21441. }
  21442. Sphere.prototype._regenerateVertexData = function () {
  21443. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  21444. };
  21445. Sphere.prototype.copy = function (id) {
  21446. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  21447. };
  21448. return Sphere;
  21449. })(_Primitive);
  21450. Primitives.Sphere = Sphere;
  21451. var Cylinder = (function (_super) {
  21452. __extends(Cylinder, _super);
  21453. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  21454. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  21455. this.height = height;
  21456. this.diameterTop = diameterTop;
  21457. this.diameterBottom = diameterBottom;
  21458. this.tessellation = tessellation;
  21459. this.subdivisions = subdivisions;
  21460. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21461. }
  21462. Cylinder.prototype._regenerateVertexData = function () {
  21463. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  21464. };
  21465. Cylinder.prototype.copy = function (id) {
  21466. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  21467. };
  21468. return Cylinder;
  21469. })(_Primitive);
  21470. Primitives.Cylinder = Cylinder;
  21471. var Torus = (function (_super) {
  21472. __extends(Torus, _super);
  21473. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  21474. this.diameter = diameter;
  21475. this.thickness = thickness;
  21476. this.tessellation = tessellation;
  21477. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21478. }
  21479. Torus.prototype._regenerateVertexData = function () {
  21480. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  21481. };
  21482. Torus.prototype.copy = function (id) {
  21483. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  21484. };
  21485. return Torus;
  21486. })(_Primitive);
  21487. Primitives.Torus = Torus;
  21488. var Ground = (function (_super) {
  21489. __extends(Ground, _super);
  21490. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  21491. this.width = width;
  21492. this.height = height;
  21493. this.subdivisions = subdivisions;
  21494. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21495. }
  21496. Ground.prototype._regenerateVertexData = function () {
  21497. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  21498. };
  21499. Ground.prototype.copy = function (id) {
  21500. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  21501. };
  21502. return Ground;
  21503. })(_Primitive);
  21504. Primitives.Ground = Ground;
  21505. var TiledGround = (function (_super) {
  21506. __extends(TiledGround, _super);
  21507. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  21508. this.xmin = xmin;
  21509. this.zmin = zmin;
  21510. this.xmax = xmax;
  21511. this.zmax = zmax;
  21512. this.subdivisions = subdivisions;
  21513. this.precision = precision;
  21514. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21515. }
  21516. TiledGround.prototype._regenerateVertexData = function () {
  21517. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  21518. };
  21519. TiledGround.prototype.copy = function (id) {
  21520. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  21521. };
  21522. return TiledGround;
  21523. })(_Primitive);
  21524. Primitives.TiledGround = TiledGround;
  21525. var Plane = (function (_super) {
  21526. __extends(Plane, _super);
  21527. function Plane(id, scene, size, canBeRegenerated, mesh) {
  21528. this.size = size;
  21529. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21530. }
  21531. Plane.prototype._regenerateVertexData = function () {
  21532. return BABYLON.VertexData.CreatePlane(this.size);
  21533. };
  21534. Plane.prototype.copy = function (id) {
  21535. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  21536. };
  21537. return Plane;
  21538. })(_Primitive);
  21539. Primitives.Plane = Plane;
  21540. var TorusKnot = (function (_super) {
  21541. __extends(TorusKnot, _super);
  21542. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  21543. this.radius = radius;
  21544. this.tube = tube;
  21545. this.radialSegments = radialSegments;
  21546. this.tubularSegments = tubularSegments;
  21547. this.p = p;
  21548. this.q = q;
  21549. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  21550. }
  21551. TorusKnot.prototype._regenerateVertexData = function () {
  21552. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  21553. };
  21554. TorusKnot.prototype.copy = function (id) {
  21555. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  21556. };
  21557. return TorusKnot;
  21558. })(_Primitive);
  21559. Primitives.TorusKnot = TorusKnot;
  21560. })(Geometry.Primitives || (Geometry.Primitives = {}));
  21561. var Primitives = Geometry.Primitives;
  21562. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  21563. var Geometry = BABYLON.Geometry;
  21564. })(BABYLON || (BABYLON = {}));
  21565. var __extends = this.__extends || function (d, b) {
  21566. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21567. function __() { this.constructor = d; }
  21568. __.prototype = b.prototype;
  21569. d.prototype = new __();
  21570. };
  21571. var BABYLON;
  21572. (function (BABYLON) {
  21573. var Gamepads = (function () {
  21574. function Gamepads(ongamedpadconnected) {
  21575. var _this = this;
  21576. this.babylonGamepads = [];
  21577. this.oneGamepadConnected = false;
  21578. this.isMonitoring = false;
  21579. this.gamepadEventSupported = 'GamepadEvent' in window;
  21580. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  21581. 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=";
  21582. this._callbackGamepadConnected = ongamedpadconnected;
  21583. if (this.gamepadSupportAvailable) {
  21584. if (this.gamepadEventSupported) {
  21585. window.addEventListener('gamepadconnected', function (evt) {
  21586. _this._onGamepadConnected(evt);
  21587. }, false);
  21588. window.addEventListener('gamepaddisconnected', function (evt) {
  21589. _this._onGamepadDisconnected(evt);
  21590. }, false);
  21591. } else {
  21592. this._startMonitoringGamepads();
  21593. }
  21594. if (!this.oneGamepadConnected) {
  21595. this._insertGamepadDOMInstructions();
  21596. }
  21597. } else {
  21598. this._insertGamepadDOMNotSupported();
  21599. }
  21600. }
  21601. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  21602. Gamepads.gamepadDOMInfo = document.createElement("div");
  21603. var buttonAImage = document.createElement("img");
  21604. buttonAImage.src = this.buttonADataURL;
  21605. var spanMessage = document.createElement("span");
  21606. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  21607. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  21608. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21609. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21610. Gamepads.gamepadDOMInfo.style.width = "100%";
  21611. Gamepads.gamepadDOMInfo.style.height = "48px";
  21612. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21613. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21614. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21615. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21616. buttonAImage.style.position = "relative";
  21617. buttonAImage.style.bottom = "8px";
  21618. spanMessage.style.position = "relative";
  21619. spanMessage.style.fontSize = "32px";
  21620. spanMessage.style.bottom = "32px";
  21621. spanMessage.style.color = "green";
  21622. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21623. };
  21624. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  21625. Gamepads.gamepadDOMInfo = document.createElement("div");
  21626. var spanMessage = document.createElement("span");
  21627. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  21628. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  21629. Gamepads.gamepadDOMInfo.style.position = "absolute";
  21630. Gamepads.gamepadDOMInfo.style.width = "100%";
  21631. Gamepads.gamepadDOMInfo.style.height = "40px";
  21632. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  21633. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  21634. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  21635. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  21636. spanMessage.style.position = "relative";
  21637. spanMessage.style.fontSize = "32px";
  21638. spanMessage.style.color = "red";
  21639. document.body.appendChild(Gamepads.gamepadDOMInfo);
  21640. };
  21641. Gamepads.prototype.dispose = function () {
  21642. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21643. };
  21644. Gamepads.prototype._onGamepadConnected = function (evt) {
  21645. var newGamepad = this._addNewGamepad(evt.gamepad);
  21646. if (this._callbackGamepadConnected)
  21647. this._callbackGamepadConnected(newGamepad);
  21648. this._startMonitoringGamepads();
  21649. };
  21650. Gamepads.prototype._addNewGamepad = function (gamepad) {
  21651. if (!this.oneGamepadConnected) {
  21652. this.oneGamepadConnected = true;
  21653. if (Gamepads.gamepadDOMInfo) {
  21654. document.body.removeChild(Gamepads.gamepadDOMInfo);
  21655. Gamepads.gamepadDOMInfo = null;
  21656. }
  21657. }
  21658. var newGamepad;
  21659. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  21660. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  21661. } else {
  21662. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  21663. }
  21664. this.babylonGamepads.push(newGamepad);
  21665. return newGamepad;
  21666. };
  21667. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  21668. for (var i in this.babylonGamepads) {
  21669. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  21670. this.babylonGamepads.splice(i, 1);
  21671. break;
  21672. }
  21673. }
  21674. if (this.babylonGamepads.length == 0) {
  21675. this._stopMonitoringGamepads();
  21676. }
  21677. };
  21678. Gamepads.prototype._startMonitoringGamepads = function () {
  21679. if (!this.isMonitoring) {
  21680. this.isMonitoring = true;
  21681. this._checkGamepadsStatus();
  21682. }
  21683. };
  21684. Gamepads.prototype._stopMonitoringGamepads = function () {
  21685. this.isMonitoring = false;
  21686. };
  21687. Gamepads.prototype._checkGamepadsStatus = function () {
  21688. var _this = this;
  21689. this._updateGamepadObjects();
  21690. for (var i in this.babylonGamepads) {
  21691. this.babylonGamepads[i].update();
  21692. }
  21693. if (this.isMonitoring) {
  21694. if (window.requestAnimationFrame) {
  21695. window.requestAnimationFrame(function () {
  21696. _this._checkGamepadsStatus();
  21697. });
  21698. } else if (window.mozRequestAnimationFrame) {
  21699. window.mozRequestAnimationFrame(function () {
  21700. _this._checkGamepadsStatus();
  21701. });
  21702. } else if (window.webkitRequestAnimationFrame) {
  21703. window.webkitRequestAnimationFrame(function () {
  21704. _this._checkGamepadsStatus();
  21705. });
  21706. }
  21707. }
  21708. };
  21709. Gamepads.prototype._updateGamepadObjects = function () {
  21710. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  21711. for (var i = 0; i < gamepads.length; i++) {
  21712. if (gamepads[i]) {
  21713. if (!(gamepads[i].index in this.babylonGamepads)) {
  21714. var newGamepad = this._addNewGamepad(gamepads[i]);
  21715. if (this._callbackGamepadConnected) {
  21716. this._callbackGamepadConnected(newGamepad);
  21717. }
  21718. } else {
  21719. this.babylonGamepads[i].browserGamepad = gamepads[i];
  21720. }
  21721. }
  21722. }
  21723. };
  21724. return Gamepads;
  21725. })();
  21726. BABYLON.Gamepads = Gamepads;
  21727. var StickValues = (function () {
  21728. function StickValues(x, y) {
  21729. this.x = x;
  21730. this.y = y;
  21731. }
  21732. return StickValues;
  21733. })();
  21734. BABYLON.StickValues = StickValues;
  21735. var Gamepad = (function () {
  21736. function Gamepad(id, index, browserGamepad) {
  21737. this.id = id;
  21738. this.index = index;
  21739. this.browserGamepad = browserGamepad;
  21740. if (this.browserGamepad.axes.length >= 2) {
  21741. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21742. }
  21743. if (this.browserGamepad.axes.length >= 4) {
  21744. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21745. }
  21746. }
  21747. Gamepad.prototype.onleftstickchanged = function (callback) {
  21748. this._onleftstickchanged = callback;
  21749. };
  21750. Gamepad.prototype.onrightstickchanged = function (callback) {
  21751. this._onrightstickchanged = callback;
  21752. };
  21753. Object.defineProperty(Gamepad.prototype, "leftStick", {
  21754. get: function () {
  21755. return this._leftStick;
  21756. },
  21757. set: function (newValues) {
  21758. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  21759. this._onleftstickchanged(newValues);
  21760. }
  21761. this._leftStick = newValues;
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Object.defineProperty(Gamepad.prototype, "rightStick", {
  21767. get: function () {
  21768. return this._rightStick;
  21769. },
  21770. set: function (newValues) {
  21771. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  21772. this._onrightstickchanged(newValues);
  21773. }
  21774. this._rightStick = newValues;
  21775. },
  21776. enumerable: true,
  21777. configurable: true
  21778. });
  21779. Gamepad.prototype.update = function () {
  21780. if (this._leftStick) {
  21781. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  21782. }
  21783. if (this._rightStick) {
  21784. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  21785. }
  21786. };
  21787. return Gamepad;
  21788. })();
  21789. BABYLON.Gamepad = Gamepad;
  21790. var GenericPad = (function (_super) {
  21791. __extends(GenericPad, _super);
  21792. function GenericPad(id, index, gamepad) {
  21793. _super.call(this, id, index, gamepad);
  21794. this.id = id;
  21795. this.index = index;
  21796. this.gamepad = gamepad;
  21797. this._buttons = new Array(gamepad.buttons.length);
  21798. }
  21799. GenericPad.prototype.onbuttondown = function (callback) {
  21800. this._onbuttondown = callback;
  21801. };
  21802. GenericPad.prototype.onbuttonup = function (callback) {
  21803. this._onbuttonup = callback;
  21804. };
  21805. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  21806. if (newValue !== currentValue) {
  21807. if (this._onbuttondown && newValue === 1) {
  21808. this._onbuttondown(buttonIndex);
  21809. }
  21810. if (this._onbuttonup && newValue === 0) {
  21811. this._onbuttonup(buttonIndex);
  21812. }
  21813. }
  21814. return newValue;
  21815. };
  21816. GenericPad.prototype.update = function () {
  21817. _super.prototype.update.call(this);
  21818. for (var index = 0; index < this._buttons.length; index++) {
  21819. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  21820. }
  21821. };
  21822. return GenericPad;
  21823. })(Gamepad);
  21824. BABYLON.GenericPad = GenericPad;
  21825. (function (Xbox360Button) {
  21826. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  21827. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  21828. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  21829. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  21830. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  21831. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  21832. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  21833. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  21834. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  21835. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  21836. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  21837. var Xbox360Button = BABYLON.Xbox360Button;
  21838. (function (Xbox360Dpad) {
  21839. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  21840. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  21841. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  21842. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  21843. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  21844. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  21845. var Xbox360Pad = (function (_super) {
  21846. __extends(Xbox360Pad, _super);
  21847. function Xbox360Pad() {
  21848. _super.apply(this, arguments);
  21849. this._leftTrigger = 0;
  21850. this._rightTrigger = 0;
  21851. this._buttonA = 0;
  21852. this._buttonB = 0;
  21853. this._buttonX = 0;
  21854. this._buttonY = 0;
  21855. this._buttonBack = 0;
  21856. this._buttonStart = 0;
  21857. this._buttonLB = 0;
  21858. this._buttonRB = 0;
  21859. this._buttonLeftStick = 0;
  21860. this._buttonRightStick = 0;
  21861. this._dPadUp = 0;
  21862. this._dPadDown = 0;
  21863. this._dPadLeft = 0;
  21864. this._dPadRight = 0;
  21865. }
  21866. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  21867. this._onlefttriggerchanged = callback;
  21868. };
  21869. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  21870. this._onrighttriggerchanged = callback;
  21871. };
  21872. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  21873. get: function () {
  21874. return this._leftTrigger;
  21875. },
  21876. set: function (newValue) {
  21877. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  21878. this._onlefttriggerchanged(newValue);
  21879. }
  21880. this._leftTrigger = newValue;
  21881. },
  21882. enumerable: true,
  21883. configurable: true
  21884. });
  21885. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  21886. get: function () {
  21887. return this._rightTrigger;
  21888. },
  21889. set: function (newValue) {
  21890. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  21891. this._onrighttriggerchanged(newValue);
  21892. }
  21893. this._rightTrigger = newValue;
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Xbox360Pad.prototype.onbuttondown = function (callback) {
  21899. this._onbuttondown = callback;
  21900. };
  21901. Xbox360Pad.prototype.onbuttonup = function (callback) {
  21902. this._onbuttonup = callback;
  21903. };
  21904. Xbox360Pad.prototype.ondpaddown = function (callback) {
  21905. this._ondpaddown = callback;
  21906. };
  21907. Xbox360Pad.prototype.ondpadup = function (callback) {
  21908. this._ondpadup = callback;
  21909. };
  21910. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  21911. if (newValue !== currentValue) {
  21912. if (this._onbuttondown && newValue === 1) {
  21913. this._onbuttondown(buttonType);
  21914. }
  21915. if (this._onbuttonup && newValue === 0) {
  21916. this._onbuttonup(buttonType);
  21917. }
  21918. }
  21919. return newValue;
  21920. };
  21921. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  21922. if (newValue !== currentValue) {
  21923. if (this._ondpaddown && newValue === 1) {
  21924. this._ondpaddown(buttonType);
  21925. }
  21926. if (this._ondpadup && newValue === 0) {
  21927. this._ondpadup(buttonType);
  21928. }
  21929. }
  21930. return newValue;
  21931. };
  21932. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  21933. get: function () {
  21934. return this._buttonA;
  21935. },
  21936. set: function (value) {
  21937. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  21943. get: function () {
  21944. return this._buttonB;
  21945. },
  21946. set: function (value) {
  21947. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  21953. get: function () {
  21954. return this._buttonX;
  21955. },
  21956. set: function (value) {
  21957. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  21958. },
  21959. enumerable: true,
  21960. configurable: true
  21961. });
  21962. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  21963. get: function () {
  21964. return this._buttonY;
  21965. },
  21966. set: function (value) {
  21967. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  21973. get: function () {
  21974. return this._buttonStart;
  21975. },
  21976. set: function (value) {
  21977. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  21978. },
  21979. enumerable: true,
  21980. configurable: true
  21981. });
  21982. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  21983. get: function () {
  21984. return this._buttonBack;
  21985. },
  21986. set: function (value) {
  21987. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  21993. get: function () {
  21994. return this._buttonLB;
  21995. },
  21996. set: function (value) {
  21997. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  22003. get: function () {
  22004. return this._buttonRB;
  22005. },
  22006. set: function (value) {
  22007. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  22013. get: function () {
  22014. return this._buttonLeftStick;
  22015. },
  22016. set: function (value) {
  22017. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  22018. },
  22019. enumerable: true,
  22020. configurable: true
  22021. });
  22022. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  22023. get: function () {
  22024. return this._buttonRightStick;
  22025. },
  22026. set: function (value) {
  22027. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  22028. },
  22029. enumerable: true,
  22030. configurable: true
  22031. });
  22032. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  22033. get: function () {
  22034. return this._dPadUp;
  22035. },
  22036. set: function (value) {
  22037. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  22043. get: function () {
  22044. return this._dPadDown;
  22045. },
  22046. set: function (value) {
  22047. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  22053. get: function () {
  22054. return this._dPadLeft;
  22055. },
  22056. set: function (value) {
  22057. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  22063. get: function () {
  22064. return this._dPadRight;
  22065. },
  22066. set: function (value) {
  22067. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Xbox360Pad.prototype.update = function () {
  22073. _super.prototype.update.call(this);
  22074. this.buttonA = this.browserGamepad.buttons[0].value;
  22075. this.buttonB = this.browserGamepad.buttons[1].value;
  22076. this.buttonX = this.browserGamepad.buttons[2].value;
  22077. this.buttonY = this.browserGamepad.buttons[3].value;
  22078. this.buttonLB = this.browserGamepad.buttons[4].value;
  22079. this.buttonRB = this.browserGamepad.buttons[5].value;
  22080. this.leftTrigger = this.browserGamepad.buttons[6].value;
  22081. this.rightTrigger = this.browserGamepad.buttons[7].value;
  22082. this.buttonBack = this.browserGamepad.buttons[8].value;
  22083. this.buttonStart = this.browserGamepad.buttons[9].value;
  22084. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  22085. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  22086. this.dPadUp = this.browserGamepad.buttons[12].value;
  22087. this.dPadDown = this.browserGamepad.buttons[13].value;
  22088. this.dPadLeft = this.browserGamepad.buttons[14].value;
  22089. this.dPadRight = this.browserGamepad.buttons[15].value;
  22090. };
  22091. return Xbox360Pad;
  22092. })(Gamepad);
  22093. BABYLON.Xbox360Pad = Xbox360Pad;
  22094. })(BABYLON || (BABYLON = {}));
  22095. var __extends = this.__extends || function (d, b) {
  22096. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22097. function __() { this.constructor = d; }
  22098. __.prototype = b.prototype;
  22099. d.prototype = new __();
  22100. };
  22101. var BABYLON;
  22102. (function (BABYLON) {
  22103. var GamepadCamera = (function (_super) {
  22104. __extends(GamepadCamera, _super);
  22105. function GamepadCamera(name, position, scene) {
  22106. var _this = this;
  22107. _super.call(this, name, position, scene);
  22108. this.angularSensibility = 200;
  22109. this.moveSensibility = 75;
  22110. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  22111. _this._onNewGameConnected(gamepad);
  22112. });
  22113. }
  22114. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  22115. if (gamepad.index === 0) {
  22116. this._gamepad = gamepad;
  22117. }
  22118. };
  22119. GamepadCamera.prototype._checkInputs = function () {
  22120. if (!this._gamepad) {
  22121. return;
  22122. }
  22123. var LSValues = this._gamepad.leftStick;
  22124. var normalizedLX = LSValues.x / this.moveSensibility;
  22125. var normalizedLY = LSValues.y / this.moveSensibility;
  22126. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  22127. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  22128. var RSValues = this._gamepad.rightStick;
  22129. var normalizedRX = RSValues.x / this.angularSensibility;
  22130. var normalizedRY = RSValues.y / this.angularSensibility;
  22131. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  22132. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  22133. ;
  22134. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22135. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  22136. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22137. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  22138. };
  22139. GamepadCamera.prototype.dispose = function () {
  22140. this._gamepads.dispose();
  22141. _super.prototype.dispose.call(this);
  22142. };
  22143. return GamepadCamera;
  22144. })(BABYLON.FreeCamera);
  22145. BABYLON.GamepadCamera = GamepadCamera;
  22146. })(BABYLON || (BABYLON = {}));
  22147. var __extends = this.__extends || function (d, b) {
  22148. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22149. function __() { this.constructor = d; }
  22150. __.prototype = b.prototype;
  22151. d.prototype = new __();
  22152. };
  22153. var BABYLON;
  22154. (function (BABYLON) {
  22155. var LinesMesh = (function (_super) {
  22156. __extends(LinesMesh, _super);
  22157. function LinesMesh(name, scene, updatable) {
  22158. if (typeof updatable === "undefined") { updatable = false; }
  22159. _super.call(this, name, scene);
  22160. this.color = new BABYLON.Color3(1, 1, 1);
  22161. this.alpha = 1;
  22162. this._indices = new Array();
  22163. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22164. attributes: ["position"],
  22165. uniforms: ["worldViewProjection", "color"],
  22166. needAlphaBlending: true
  22167. });
  22168. }
  22169. Object.defineProperty(LinesMesh.prototype, "material", {
  22170. get: function () {
  22171. return this._colorShader;
  22172. },
  22173. enumerable: true,
  22174. configurable: true
  22175. });
  22176. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  22177. get: function () {
  22178. return false;
  22179. },
  22180. enumerable: true,
  22181. configurable: true
  22182. });
  22183. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  22184. get: function () {
  22185. return false;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  22191. var engine = this.getScene().getEngine();
  22192. var indexToBind = this._geometry.getIndexBuffer();
  22193. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  22194. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  22195. };
  22196. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  22197. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22198. return;
  22199. }
  22200. var engine = this.getScene().getEngine();
  22201. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  22202. };
  22203. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  22204. return null;
  22205. };
  22206. LinesMesh.prototype.dispose = function (doNotRecurse) {
  22207. this._colorShader.dispose();
  22208. _super.prototype.dispose.call(this, doNotRecurse);
  22209. };
  22210. return LinesMesh;
  22211. })(BABYLON.Mesh);
  22212. BABYLON.LinesMesh = LinesMesh;
  22213. })(BABYLON || (BABYLON = {}));
  22214. var BABYLON;
  22215. (function (BABYLON) {
  22216. var OutlineRenderer = (function () {
  22217. function OutlineRenderer(scene) {
  22218. this._scene = scene;
  22219. }
  22220. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  22221. if (typeof useOverlay === "undefined") { useOverlay = false; }
  22222. var scene = this._scene;
  22223. var engine = this._scene.getEngine();
  22224. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22225. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  22226. return;
  22227. }
  22228. var mesh = subMesh.getRenderingMesh();
  22229. var material = subMesh.getMaterial();
  22230. engine.enableEffect(this._effect);
  22231. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  22232. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  22233. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  22234. var useBones = mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  22235. if (useBones) {
  22236. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22237. }
  22238. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  22239. if (material && material.needAlphaTesting()) {
  22240. var alphaTexture = material.getAlphaTestTexture();
  22241. this._effect.setTexture("diffuseSampler", alphaTexture);
  22242. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  22243. }
  22244. if (hardwareInstancedRendering) {
  22245. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  22246. } else {
  22247. if (batch.renderSelf[subMesh._id]) {
  22248. this._effect.setMatrix("world", mesh.getWorldMatrix());
  22249. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22250. }
  22251. if (batch.visibleInstances[subMesh._id]) {
  22252. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22253. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22254. this._effect.setMatrix("world", instance.getWorldMatrix());
  22255. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  22256. }
  22257. }
  22258. }
  22259. };
  22260. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  22261. var defines = [];
  22262. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  22263. var mesh = subMesh.getMesh();
  22264. var material = subMesh.getMaterial();
  22265. if (material && material.needAlphaTesting()) {
  22266. defines.push("#define ALPHATEST");
  22267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22268. attribs.push(BABYLON.VertexBuffer.UVKind);
  22269. defines.push("#define UV1");
  22270. }
  22271. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22272. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22273. defines.push("#define UV2");
  22274. }
  22275. }
  22276. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22279. defines.push("#define BONES");
  22280. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22281. }
  22282. if (useInstances) {
  22283. defines.push("#define INSTANCES");
  22284. attribs.push("world0");
  22285. attribs.push("world1");
  22286. attribs.push("world2");
  22287. attribs.push("world3");
  22288. }
  22289. var join = defines.join("\n");
  22290. if (this._cachedDefines != join) {
  22291. this._cachedDefines = join;
  22292. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  22293. }
  22294. return this._effect.isReady();
  22295. };
  22296. return OutlineRenderer;
  22297. })();
  22298. BABYLON.OutlineRenderer = OutlineRenderer;
  22299. })(BABYLON || (BABYLON = {}));
  22300. var BABYLON;
  22301. (function (BABYLON) {
  22302. var MeshAssetTask = (function () {
  22303. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  22304. this.name = name;
  22305. this.meshesNames = meshesNames;
  22306. this.rootUrl = rootUrl;
  22307. this.sceneFilename = sceneFilename;
  22308. this.isCompleted = false;
  22309. }
  22310. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22311. var _this = this;
  22312. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  22313. _this.loadedMeshes = meshes;
  22314. _this.loadedParticleSystems = particleSystems;
  22315. _this.loadedSkeletons = skeletons;
  22316. _this.isCompleted = true;
  22317. if (_this.onSuccess) {
  22318. _this.onSuccess(_this);
  22319. }
  22320. onSuccess();
  22321. }, null, function () {
  22322. if (_this.onError) {
  22323. _this.onError(_this);
  22324. }
  22325. onError();
  22326. });
  22327. };
  22328. return MeshAssetTask;
  22329. })();
  22330. BABYLON.MeshAssetTask = MeshAssetTask;
  22331. var TextFileAssetTask = (function () {
  22332. function TextFileAssetTask(name, url) {
  22333. this.name = name;
  22334. this.url = url;
  22335. this.isCompleted = false;
  22336. }
  22337. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22338. var _this = this;
  22339. BABYLON.Tools.LoadFile(this.url, function (data) {
  22340. _this.text = data;
  22341. _this.isCompleted = true;
  22342. if (_this.onSuccess) {
  22343. _this.onSuccess(_this);
  22344. }
  22345. onSuccess();
  22346. }, null, scene.database, false, function () {
  22347. if (_this.onError) {
  22348. _this.onError(_this);
  22349. }
  22350. onError();
  22351. });
  22352. };
  22353. return TextFileAssetTask;
  22354. })();
  22355. BABYLON.TextFileAssetTask = TextFileAssetTask;
  22356. var BinaryFileAssetTask = (function () {
  22357. function BinaryFileAssetTask(name, url) {
  22358. this.name = name;
  22359. this.url = url;
  22360. this.isCompleted = false;
  22361. }
  22362. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22363. var _this = this;
  22364. BABYLON.Tools.LoadFile(this.url, function (data) {
  22365. _this.data = data;
  22366. _this.isCompleted = true;
  22367. if (_this.onSuccess) {
  22368. _this.onSuccess(_this);
  22369. }
  22370. onSuccess();
  22371. }, null, scene.database, true, function () {
  22372. if (_this.onError) {
  22373. _this.onError(_this);
  22374. }
  22375. onError();
  22376. });
  22377. };
  22378. return BinaryFileAssetTask;
  22379. })();
  22380. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  22381. var ImageAssetTask = (function () {
  22382. function ImageAssetTask(name, url) {
  22383. this.name = name;
  22384. this.url = url;
  22385. this.isCompleted = false;
  22386. }
  22387. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22388. var _this = this;
  22389. var img = new Image();
  22390. img.onload = function () {
  22391. _this.image = img;
  22392. _this.isCompleted = true;
  22393. if (_this.onSuccess) {
  22394. _this.onSuccess(_this);
  22395. }
  22396. onSuccess();
  22397. };
  22398. img.onerror = function () {
  22399. if (_this.onError) {
  22400. _this.onError(_this);
  22401. }
  22402. onError();
  22403. };
  22404. img.src = this.url;
  22405. };
  22406. return ImageAssetTask;
  22407. })();
  22408. BABYLON.ImageAssetTask = ImageAssetTask;
  22409. var TextureAssetTask = (function () {
  22410. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  22411. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22412. this.name = name;
  22413. this.url = url;
  22414. this.noMipmap = noMipmap;
  22415. this.invertY = invertY;
  22416. this.samplingMode = samplingMode;
  22417. this.isCompleted = false;
  22418. }
  22419. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  22420. var _this = this;
  22421. var onload = function () {
  22422. _this.isCompleted = true;
  22423. if (_this.onSuccess) {
  22424. _this.onSuccess(_this);
  22425. }
  22426. onSuccess();
  22427. };
  22428. var onerror = function () {
  22429. if (_this.onError) {
  22430. _this.onError(_this);
  22431. }
  22432. onError();
  22433. };
  22434. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  22435. };
  22436. return TextureAssetTask;
  22437. })();
  22438. BABYLON.TextureAssetTask = TextureAssetTask;
  22439. var AssetsManager = (function () {
  22440. function AssetsManager(scene) {
  22441. this._tasks = new Array();
  22442. this._waitingTasksCount = 0;
  22443. this.useDefaultLoadingScreen = true;
  22444. this._scene = scene;
  22445. }
  22446. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  22447. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  22448. this._tasks.push(task);
  22449. return task;
  22450. };
  22451. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  22452. var task = new TextFileAssetTask(taskName, url);
  22453. this._tasks.push(task);
  22454. return task;
  22455. };
  22456. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  22457. var task = new BinaryFileAssetTask(taskName, url);
  22458. this._tasks.push(task);
  22459. return task;
  22460. };
  22461. AssetsManager.prototype.addImageTask = function (taskName, url) {
  22462. var task = new ImageAssetTask(taskName, url);
  22463. this._tasks.push(task);
  22464. return task;
  22465. };
  22466. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  22467. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22468. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  22469. this._tasks.push(task);
  22470. return task;
  22471. };
  22472. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  22473. this._waitingTasksCount--;
  22474. if (this._waitingTasksCount === 0) {
  22475. if (this.onFinish) {
  22476. this.onFinish(this._tasks);
  22477. }
  22478. this._scene.getEngine().hideLoadingUI();
  22479. }
  22480. };
  22481. AssetsManager.prototype._runTask = function (task) {
  22482. var _this = this;
  22483. task.run(this._scene, function () {
  22484. if (_this.onTaskSuccess) {
  22485. _this.onTaskSuccess(task);
  22486. }
  22487. _this._decreaseWaitingTasksCount();
  22488. }, function () {
  22489. if (_this.onTaskError) {
  22490. _this.onTaskError(task);
  22491. }
  22492. _this._decreaseWaitingTasksCount();
  22493. });
  22494. };
  22495. AssetsManager.prototype.reset = function () {
  22496. this._tasks = new Array();
  22497. return this;
  22498. };
  22499. AssetsManager.prototype.load = function () {
  22500. this._waitingTasksCount = this._tasks.length;
  22501. if (this._waitingTasksCount === 0) {
  22502. if (this.onFinish) {
  22503. this.onFinish(this._tasks);
  22504. }
  22505. return this;
  22506. }
  22507. if (this.useDefaultLoadingScreen) {
  22508. this._scene.getEngine().displayLoadingUI();
  22509. }
  22510. for (var index = 0; index < this._tasks.length; index++) {
  22511. var task = this._tasks[index];
  22512. this._runTask(task);
  22513. }
  22514. return this;
  22515. };
  22516. return AssetsManager;
  22517. })();
  22518. BABYLON.AssetsManager = AssetsManager;
  22519. })(BABYLON || (BABYLON = {}));
  22520. var __extends = this.__extends || function (d, b) {
  22521. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22522. function __() { this.constructor = d; }
  22523. __.prototype = b.prototype;
  22524. d.prototype = new __();
  22525. };
  22526. var BABYLON;
  22527. (function (BABYLON) {
  22528. var VRDeviceOrientationCamera = (function (_super) {
  22529. __extends(VRDeviceOrientationCamera, _super);
  22530. function VRDeviceOrientationCamera(name, position, scene) {
  22531. _super.call(this, name, position, scene);
  22532. this._alpha = 0;
  22533. this._beta = 0;
  22534. this._gamma = 0;
  22535. }
  22536. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  22537. this._alpha = +evt.alpha | 0;
  22538. this._beta = +evt.beta | 0;
  22539. this._gamma = +evt.gamma | 0;
  22540. if (this._gamma < 0) {
  22541. this._gamma = 90 + this._gamma;
  22542. } else {
  22543. this._gamma = 270 - this._gamma;
  22544. }
  22545. this.rotation.x = this._gamma / 180.0 * Math.PI;
  22546. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  22547. this.rotation.z = this._beta / 180.0 * Math.PI;
  22548. };
  22549. return VRDeviceOrientationCamera;
  22550. })(BABYLON.OculusCamera);
  22551. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  22552. })(BABYLON || (BABYLON = {}));
  22553. var __extends = this.__extends || function (d, b) {
  22554. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22555. function __() { this.constructor = d; }
  22556. __.prototype = b.prototype;
  22557. d.prototype = new __();
  22558. };
  22559. var BABYLON;
  22560. (function (BABYLON) {
  22561. var WebVRCamera = (function (_super) {
  22562. __extends(WebVRCamera, _super);
  22563. function WebVRCamera(name, position, scene) {
  22564. _super.call(this, name, position, scene);
  22565. this._hmdDevice = null;
  22566. this._sensorDevice = null;
  22567. this._cacheState = null;
  22568. this._cacheQuaternion = new BABYLON.Quaternion();
  22569. this._cacheRotation = BABYLON.Vector3.Zero();
  22570. this._vrEnabled = false;
  22571. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  22572. }
  22573. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  22574. var size = devices.length;
  22575. var i = 0;
  22576. this._sensorDevice = null;
  22577. this._hmdDevice = null;
  22578. while (i < size && this._hmdDevice === null) {
  22579. if (devices[i] instanceof HMDVRDevice) {
  22580. this._hmdDevice = devices[i];
  22581. }
  22582. i++;
  22583. }
  22584. i = 0;
  22585. while (i < size && this._sensorDevice === null) {
  22586. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  22587. this._sensorDevice = devices[i];
  22588. }
  22589. i++;
  22590. }
  22591. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  22592. };
  22593. WebVRCamera.prototype._update = function () {
  22594. if (this._vrEnabled) {
  22595. this._cacheState = this._sensorDevice.getState();
  22596. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  22597. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  22598. this.rotation.x = -this._cacheRotation.z;
  22599. this.rotation.y = -this._cacheRotation.y;
  22600. this.rotation.z = this._cacheRotation.x;
  22601. }
  22602. _super.prototype._update.call(this);
  22603. };
  22604. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  22605. _super.prototype.attachControl.call(this, element, noPreventDefault);
  22606. if (navigator.getVRDevices) {
  22607. navigator.getVRDevices().then(this._getWebVRDevices);
  22608. } else if (navigator.mozGetVRDevices) {
  22609. navigator.mozGetVRDevices(this._getWebVRDevices);
  22610. }
  22611. };
  22612. WebVRCamera.prototype.detachControl = function (element) {
  22613. _super.prototype.detachControl.call(this, element);
  22614. this._vrEnabled = false;
  22615. };
  22616. return WebVRCamera;
  22617. })(BABYLON.OculusCamera);
  22618. BABYLON.WebVRCamera = WebVRCamera;
  22619. })(BABYLON || (BABYLON = {}));
  22620. var __extends = this.__extends || function (d, b) {
  22621. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22622. function __() { this.constructor = d; }
  22623. __.prototype = b.prototype;
  22624. d.prototype = new __();
  22625. };
  22626. var BABYLON;
  22627. (function (BABYLON) {
  22628. var SceneOptimization = (function () {
  22629. function SceneOptimization(priority) {
  22630. if (typeof priority === "undefined") { priority = 0; }
  22631. this.priority = priority;
  22632. this.apply = function (scene) {
  22633. return true;
  22634. };
  22635. }
  22636. return SceneOptimization;
  22637. })();
  22638. BABYLON.SceneOptimization = SceneOptimization;
  22639. var TextureOptimization = (function (_super) {
  22640. __extends(TextureOptimization, _super);
  22641. function TextureOptimization(priority, maximumSize) {
  22642. if (typeof priority === "undefined") { priority = 0; }
  22643. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  22644. var _this = this;
  22645. _super.call(this, priority);
  22646. this.priority = priority;
  22647. this.maximumSize = maximumSize;
  22648. this.apply = function (scene) {
  22649. var allDone = true;
  22650. for (var index = 0; index < scene.textures.length; index++) {
  22651. var texture = scene.textures[index];
  22652. if (!texture.canRescale) {
  22653. continue;
  22654. }
  22655. var currentSize = texture.getSize();
  22656. var maxDimension = Math.max(currentSize.width, currentSize.height);
  22657. if (maxDimension > _this.maximumSize) {
  22658. texture.scale(0.5);
  22659. allDone = false;
  22660. }
  22661. }
  22662. return allDone;
  22663. };
  22664. }
  22665. return TextureOptimization;
  22666. })(SceneOptimization);
  22667. BABYLON.TextureOptimization = TextureOptimization;
  22668. var HardwareScalingOptimization = (function (_super) {
  22669. __extends(HardwareScalingOptimization, _super);
  22670. function HardwareScalingOptimization(priority, maximumScale) {
  22671. if (typeof priority === "undefined") { priority = 0; }
  22672. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  22673. var _this = this;
  22674. _super.call(this, priority);
  22675. this.priority = priority;
  22676. this.maximumScale = maximumScale;
  22677. this._currentScale = 1;
  22678. this.apply = function (scene) {
  22679. _this._currentScale++;
  22680. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  22681. return _this._currentScale >= _this.maximumScale;
  22682. };
  22683. }
  22684. return HardwareScalingOptimization;
  22685. })(SceneOptimization);
  22686. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  22687. var ShadowsOptimization = (function (_super) {
  22688. __extends(ShadowsOptimization, _super);
  22689. function ShadowsOptimization() {
  22690. _super.apply(this, arguments);
  22691. this.apply = function (scene) {
  22692. scene.shadowsEnabled = false;
  22693. return true;
  22694. };
  22695. }
  22696. return ShadowsOptimization;
  22697. })(SceneOptimization);
  22698. BABYLON.ShadowsOptimization = ShadowsOptimization;
  22699. var PostProcessesOptimization = (function (_super) {
  22700. __extends(PostProcessesOptimization, _super);
  22701. function PostProcessesOptimization() {
  22702. _super.apply(this, arguments);
  22703. this.apply = function (scene) {
  22704. scene.postProcessesEnabled = false;
  22705. return true;
  22706. };
  22707. }
  22708. return PostProcessesOptimization;
  22709. })(SceneOptimization);
  22710. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  22711. var LensFlaresOptimization = (function (_super) {
  22712. __extends(LensFlaresOptimization, _super);
  22713. function LensFlaresOptimization() {
  22714. _super.apply(this, arguments);
  22715. this.apply = function (scene) {
  22716. scene.lensFlaresEnabled = false;
  22717. return true;
  22718. };
  22719. }
  22720. return LensFlaresOptimization;
  22721. })(SceneOptimization);
  22722. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  22723. var ParticlesOptimization = (function (_super) {
  22724. __extends(ParticlesOptimization, _super);
  22725. function ParticlesOptimization() {
  22726. _super.apply(this, arguments);
  22727. this.apply = function (scene) {
  22728. scene.particlesEnabled = false;
  22729. return true;
  22730. };
  22731. }
  22732. return ParticlesOptimization;
  22733. })(SceneOptimization);
  22734. BABYLON.ParticlesOptimization = ParticlesOptimization;
  22735. var RenderTargetsOptimization = (function (_super) {
  22736. __extends(RenderTargetsOptimization, _super);
  22737. function RenderTargetsOptimization() {
  22738. _super.apply(this, arguments);
  22739. this.apply = function (scene) {
  22740. scene.renderTargetsEnabled = false;
  22741. return true;
  22742. };
  22743. }
  22744. return RenderTargetsOptimization;
  22745. })(SceneOptimization);
  22746. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  22747. var SceneOptimizerOptions = (function () {
  22748. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  22749. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  22750. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  22751. this.targetFrameRate = targetFrameRate;
  22752. this.trackerDuration = trackerDuration;
  22753. this.optimizations = new Array();
  22754. }
  22755. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  22756. var result = new SceneOptimizerOptions(targetFrameRate);
  22757. var priority = 0;
  22758. result.optimizations.push(new ShadowsOptimization(priority));
  22759. result.optimizations.push(new LensFlaresOptimization(priority));
  22760. priority++;
  22761. result.optimizations.push(new PostProcessesOptimization(priority));
  22762. result.optimizations.push(new ParticlesOptimization(priority));
  22763. priority++;
  22764. result.optimizations.push(new TextureOptimization(priority, 1024));
  22765. return result;
  22766. };
  22767. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  22768. var result = new SceneOptimizerOptions(targetFrameRate);
  22769. var priority = 0;
  22770. result.optimizations.push(new ShadowsOptimization(priority));
  22771. result.optimizations.push(new LensFlaresOptimization(priority));
  22772. priority++;
  22773. result.optimizations.push(new PostProcessesOptimization(priority));
  22774. result.optimizations.push(new ParticlesOptimization(priority));
  22775. priority++;
  22776. result.optimizations.push(new TextureOptimization(priority, 512));
  22777. priority++;
  22778. result.optimizations.push(new RenderTargetsOptimization(priority));
  22779. priority++;
  22780. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  22781. return result;
  22782. };
  22783. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  22784. var result = new SceneOptimizerOptions(targetFrameRate);
  22785. var priority = 0;
  22786. result.optimizations.push(new ShadowsOptimization(priority));
  22787. result.optimizations.push(new LensFlaresOptimization(priority));
  22788. priority++;
  22789. result.optimizations.push(new PostProcessesOptimization(priority));
  22790. result.optimizations.push(new ParticlesOptimization(priority));
  22791. priority++;
  22792. result.optimizations.push(new TextureOptimization(priority, 256));
  22793. priority++;
  22794. result.optimizations.push(new RenderTargetsOptimization(priority));
  22795. priority++;
  22796. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  22797. return result;
  22798. };
  22799. return SceneOptimizerOptions;
  22800. })();
  22801. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  22802. var SceneOptimizer = (function () {
  22803. function SceneOptimizer() {
  22804. }
  22805. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  22806. if (BABYLON.Tools.GetFps() >= options.targetFrameRate) {
  22807. if (onSuccess) {
  22808. onSuccess();
  22809. }
  22810. return;
  22811. }
  22812. var allDone = true;
  22813. var noOptimizationApplied = true;
  22814. for (var index = 0; index < options.optimizations.length; index++) {
  22815. var optimization = options.optimizations[index];
  22816. if (optimization.priority === currentPriorityLevel) {
  22817. noOptimizationApplied = false;
  22818. allDone = allDone && optimization.apply(scene);
  22819. }
  22820. }
  22821. if (noOptimizationApplied) {
  22822. if (onFailure) {
  22823. onFailure();
  22824. }
  22825. return;
  22826. }
  22827. if (allDone) {
  22828. currentPriorityLevel++;
  22829. }
  22830. scene.executeWhenReady(function () {
  22831. setTimeout(function () {
  22832. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  22833. }, options.trackerDuration);
  22834. });
  22835. };
  22836. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  22837. if (!options) {
  22838. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  22839. }
  22840. scene.executeWhenReady(function () {
  22841. setTimeout(function () {
  22842. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  22843. }, options.trackerDuration);
  22844. });
  22845. };
  22846. return SceneOptimizer;
  22847. })();
  22848. BABYLON.SceneOptimizer = SceneOptimizer;
  22849. })(BABYLON || (BABYLON = {}));
  22850. var BABYLON;
  22851. (function (BABYLON) {
  22852. (function (Internals) {
  22853. var MeshLODLevel = (function () {
  22854. function MeshLODLevel(distance, mesh) {
  22855. this.distance = distance;
  22856. this.mesh = mesh;
  22857. }
  22858. return MeshLODLevel;
  22859. })();
  22860. Internals.MeshLODLevel = MeshLODLevel;
  22861. })(BABYLON.Internals || (BABYLON.Internals = {}));
  22862. var Internals = BABYLON.Internals;
  22863. })(BABYLON || (BABYLON = {}));
  22864. var BABYLON;
  22865. (function (BABYLON) {
  22866. var AudioEngine = (function () {
  22867. function AudioEngine() {
  22868. this.audioContext = null;
  22869. this.canUseWebAudio = false;
  22870. try {
  22871. if (typeof AudioContext !== 'undefined') {
  22872. this.audioContext = new AudioContext();
  22873. this.canUseWebAudio = true;
  22874. } else if (typeof webkitAudioContext !== 'undefined') {
  22875. this.audioContext = new webkitAudioContext();
  22876. this.canUseWebAudio = true;
  22877. }
  22878. } catch (e) {
  22879. this.canUseWebAudio = false;
  22880. }
  22881. if (this.canUseWebAudio) {
  22882. this.masterGain = this.audioContext.createGain();
  22883. this.masterGain.gain.value = 1;
  22884. this.masterGain.connect(this.audioContext.destination);
  22885. }
  22886. }
  22887. AudioEngine.prototype.getGlobalVolume = function () {
  22888. if (this.canUseWebAudio) {
  22889. return this.masterGain.gain.value;
  22890. } else {
  22891. return -1;
  22892. }
  22893. };
  22894. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  22895. if (this.canUseWebAudio) {
  22896. this.masterGain.gain.value = newVolume;
  22897. }
  22898. };
  22899. return AudioEngine;
  22900. })();
  22901. BABYLON.AudioEngine = AudioEngine;
  22902. })(BABYLON || (BABYLON = {}));
  22903. var BABYLON;
  22904. (function (BABYLON) {
  22905. var Sound = (function () {
  22906. function Sound(url, engine, readyToPlayCallback, distanceMax, autoplay, loop) {
  22907. var _this = this;
  22908. this.maxDistance = 10;
  22909. this.autoplay = false;
  22910. this.loop = false;
  22911. this._position = BABYLON.Vector3.Zero();
  22912. this._direction = BABYLON.Vector3.Zero();
  22913. this._isLoaded = false;
  22914. this._isReadyToPlay = false;
  22915. this._isPlaying = false;
  22916. this._isDirectional = false;
  22917. this._coneInnerAngle = null;
  22918. this._coneOuterAngle = null;
  22919. this._coneOuterGain = null;
  22920. this._audioEngine = engine.getAudioEngine();
  22921. ;
  22922. this._readyToPlayCallback = readyToPlayCallback;
  22923. if (distanceMax) {
  22924. this.maxDistance = distanceMax;
  22925. }
  22926. if (autoplay) {
  22927. this.autoplay = autoplay;
  22928. }
  22929. if (loop) {
  22930. this.loop = loop;
  22931. }
  22932. if (this._audioEngine.canUseWebAudio) {
  22933. BABYLON.Tools.LoadFile(url, function (data) {
  22934. _this._soundLoaded(data);
  22935. }, null, null, true);
  22936. }
  22937. }
  22938. /**
  22939. * Transform this sound into a directional source
  22940. * @param coneInnerAngle Size of the inner cone in degree
  22941. * @param coneOuterAngle Size of the outer cone in degree
  22942. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  22943. */
  22944. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  22945. if (coneOuterAngle < coneInnerAngle) {
  22946. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  22947. return;
  22948. }
  22949. this._coneInnerAngle = coneInnerAngle;
  22950. this._coneOuterAngle = coneOuterAngle;
  22951. this._coneOuterGain = coneOuterGain;
  22952. this._isDirectional = true;
  22953. if (this._isPlaying && this.loop) {
  22954. this.stop();
  22955. this.play();
  22956. }
  22957. };
  22958. Sound.prototype.setPosition = function (newPosition) {
  22959. this._position = newPosition;
  22960. if (this._isReadyToPlay) {
  22961. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  22962. }
  22963. };
  22964. Sound.prototype.setDirection = function (newDirection) {
  22965. this._direction = newDirection;
  22966. if (this._isReadyToPlay) {
  22967. console.log(this._direction.x + " " + this._direction.y + " " + this._direction.z);
  22968. this._soundPanner.setOrientation(this._direction.x, this._direction.y, this._direction.z);
  22969. }
  22970. };
  22971. Sound.prototype.play = function () {
  22972. if (this._isReadyToPlay) {
  22973. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  22974. this._soundSource.buffer = this._audioBuffer;
  22975. this._soundPanner = this._audioEngine.audioContext.createPanner();
  22976. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  22977. if (this._isDirectional) {
  22978. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  22979. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  22980. this._soundPanner.coneOuterGain = this._coneOuterGain;
  22981. }
  22982. this._soundPanner.connect(this._audioEngine.masterGain);
  22983. this._soundSource.connect(this._soundPanner);
  22984. this._soundSource.loop = this.loop;
  22985. this._soundSource.start(0);
  22986. this._isPlaying = true;
  22987. }
  22988. };
  22989. Sound.prototype.stop = function () {
  22990. this._soundSource.stop(0);
  22991. this._isPlaying = false;
  22992. };
  22993. Sound.prototype.pause = function () {
  22994. };
  22995. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  22996. var _this = this;
  22997. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  22998. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  22999. });
  23000. };
  23001. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  23002. this.setPosition(connectedMesh.position);
  23003. var mat = connectedMesh.getWorldMatrix();
  23004. var direction = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(0, 0, -1), mat);
  23005. direction.normalize();
  23006. this.setDirection(direction);
  23007. };
  23008. Sound.prototype._soundLoaded = function (audioData) {
  23009. var _this = this;
  23010. this._isLoaded = true;
  23011. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  23012. _this._audioBuffer = buffer;
  23013. _this._isReadyToPlay = true;
  23014. if (_this.autoplay) {
  23015. _this.play();
  23016. }
  23017. if (_this._readyToPlayCallback) {
  23018. _this._readyToPlayCallback();
  23019. }
  23020. }, function (error) {
  23021. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  23022. });
  23023. };
  23024. return Sound;
  23025. })();
  23026. BABYLON.Sound = Sound;
  23027. })(BABYLON || (BABYLON = {}));
  23028. var BABYLON;
  23029. (function (BABYLON) {
  23030. var DebugLayer = (function () {
  23031. function DebugLayer(scene) {
  23032. var _this = this;
  23033. this._enabled = false;
  23034. this._labelsEnabled = false;
  23035. this._displayStatistics = true;
  23036. this._displayLogs = false;
  23037. this._identityMatrix = BABYLON.Matrix.Identity();
  23038. this._scene = scene;
  23039. this._syncPositions = function () {
  23040. var engine = _this._scene.getEngine();
  23041. var canvasRect = engine.getRenderingCanvasClientRect();
  23042. _this._statsDiv.style.right = "0";
  23043. _this._statsDiv.style.bottom = "10px";
  23044. _this._statsDiv.style.width = "300px";
  23045. _this._statsDiv.style.height = "auto";
  23046. _this._statsDiv.style.maxHeight = (canvasRect.height - 40) + "px";
  23047. _this._optionsDiv.style.left = "0px";
  23048. _this._optionsDiv.style.top = "10px";
  23049. _this._optionsDiv.style.width = "200px";
  23050. _this._optionsDiv.style.height = "auto";
  23051. _this._optionsDiv.style.maxHeight = (canvasRect.height - 40) + "px";
  23052. _this._logDiv.style.left = "0px";
  23053. _this._logDiv.style.bottom = "10px";
  23054. _this._logDiv.style.width = "600px";
  23055. _this._logDiv.style.height = "auto";
  23056. _this._drawingCanvas.style.left = "0px";
  23057. _this._drawingCanvas.style.top = "0px";
  23058. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  23059. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  23060. var devicePixelRatio = window.devicePixelRatio || 1;
  23061. var context = _this._drawingContext;
  23062. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  23063. _this._ratio = devicePixelRatio / backingStoreRatio;
  23064. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  23065. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  23066. };
  23067. this._onCanvasClick = function (evt) {
  23068. _this._clickPosition = {
  23069. x: evt.clientX * _this._ratio,
  23070. y: evt.clientY * _this._ratio
  23071. };
  23072. };
  23073. this._syncData = function () {
  23074. if (_this._displayStatistics) {
  23075. _this._displayStats();
  23076. _this._statsDiv.style.display = "";
  23077. } else {
  23078. _this._statsDiv.style.display = "none";
  23079. }
  23080. if (_this._displayLogs) {
  23081. _this._logDiv.style.display = "";
  23082. } else {
  23083. _this._logDiv.style.display = "none";
  23084. }
  23085. if (_this._labelsEnabled) {
  23086. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  23087. _this._drawingContext.font = "normal 12px Segoe UI";
  23088. _this._drawingContext.strokeStyle = '#FFFFFF';
  23089. _this._drawingContext.lineWidth = 1;
  23090. var engine = _this._scene.getEngine();
  23091. var viewport = _this._scene.activeCamera.viewport;
  23092. var globalViewport = viewport.toGlobal(engine);
  23093. var meshes = _this._scene.getActiveMeshes();
  23094. for (var index = 0; index < meshes.length; index++) {
  23095. var mesh = meshes.data[index];
  23096. var position = mesh.getBoundingInfo().boundingSphere.center;
  23097. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  23098. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  23099. mesh.renderOverlay = !mesh.renderOverlay;
  23100. }, function () {
  23101. return mesh.renderOverlay ? 'red' : 'black';
  23102. });
  23103. }
  23104. for (index = 0; index < _this._scene.cameras.length; index++) {
  23105. var camera = _this._scene.cameras[index];
  23106. if (camera === _this._scene.activeCamera) {
  23107. continue;
  23108. }
  23109. projectedPosition = BABYLON.Vector3.Project(camera.position, _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  23110. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  23111. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  23112. _this._scene.activeCamera = camera;
  23113. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  23114. }, function () {
  23115. return "purple";
  23116. });
  23117. }
  23118. for (index = 0; index < _this._scene.lights.length; index++) {
  23119. var light = _this._scene.lights[index];
  23120. if (light.position) {
  23121. projectedPosition = BABYLON.Vector3.Project(light.position, _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  23122. _this._renderLabel(light.name, projectedPosition, -20, function () {
  23123. light.setEnabled(!light.isEnabled());
  23124. }, function () {
  23125. return light.isEnabled() ? "orange" : "gray";
  23126. });
  23127. }
  23128. }
  23129. }
  23130. _this._clickPosition = undefined;
  23131. };
  23132. }
  23133. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  23134. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  23135. var textMetrics = this._drawingContext.measureText(text);
  23136. var centerX = projectedPosition.x - textMetrics.width / 2;
  23137. var centerY = projectedPosition.y;
  23138. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  23139. onClick();
  23140. }
  23141. this._drawingContext.beginPath();
  23142. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  23143. this._drawingContext.fillStyle = getFillStyle();
  23144. this._drawingContext.globalAlpha = 0.5;
  23145. this._drawingContext.fill();
  23146. this._drawingContext.globalAlpha = 1.0;
  23147. this._drawingContext.stroke();
  23148. this._drawingContext.fillStyle = "#FFFFFF";
  23149. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  23150. this._drawingContext.beginPath();
  23151. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  23152. this._drawingContext.fill();
  23153. }
  23154. };
  23155. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  23156. if (!this._clickPosition) {
  23157. return false;
  23158. }
  23159. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  23160. return false;
  23161. }
  23162. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  23163. return false;
  23164. }
  23165. return true;
  23166. };
  23167. Object.defineProperty(DebugLayer.prototype, "enabled", {
  23168. get: function () {
  23169. return this._enabled;
  23170. },
  23171. set: function (value) {
  23172. if (this._enabled === value) {
  23173. return;
  23174. }
  23175. this._enabled = value;
  23176. var engine = this._scene.getEngine();
  23177. var parentElement = engine.getRenderingCanvas().parentElement;
  23178. if (this._enabled) {
  23179. this._scene.registerAfterRender(this._syncData);
  23180. this._globalDiv = document.createElement("div");
  23181. parentElement.appendChild(this._globalDiv);
  23182. this._generateDOMelements();
  23183. window.addEventListener("resize", this._syncPositions);
  23184. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  23185. this._syncPositions();
  23186. } else {
  23187. this._scene.unregisterAfterRender(this._syncData);
  23188. parentElement.removeChild(this._globalDiv);
  23189. window.removeEventListener("resize", this._syncPositions);
  23190. this._scene.forceShowBoundingBoxes = false;
  23191. this._scene.forceWireframe = false;
  23192. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  23193. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  23194. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  23195. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  23196. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  23197. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  23198. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  23199. this._scene.shadowsEnabled = true;
  23200. this._scene.particlesEnabled = true;
  23201. this._scene.postProcessesEnabled = true;
  23202. this._scene.collisionsEnabled = true;
  23203. this._scene.lightsEnabled = true;
  23204. this._scene.texturesEnabled = true;
  23205. this._scene.lensFlaresEnabled = true;
  23206. this._scene.proceduralTexturesEnabled = true;
  23207. this._scene.renderTargetsEnabled = true;
  23208. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  23209. }
  23210. },
  23211. enumerable: true,
  23212. configurable: true
  23213. });
  23214. DebugLayer.prototype._clearLabels = function () {
  23215. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  23216. for (var index = 0; index < this._scene.meshes.length; index++) {
  23217. var mesh = this._scene.meshes[index];
  23218. mesh.renderOverlay = false;
  23219. }
  23220. };
  23221. DebugLayer.prototype._generateTexBox = function (root, title) {
  23222. var label = document.createElement("label");
  23223. label.innerHTML = title;
  23224. root.appendChild(label);
  23225. root.appendChild(document.createElement("br"));
  23226. };
  23227. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task) {
  23228. var label = document.createElement("label");
  23229. var boundingBoxesCheckbox = document.createElement("input");
  23230. boundingBoxesCheckbox.type = "checkbox";
  23231. boundingBoxesCheckbox.checked = initialState;
  23232. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  23233. task(evt.target);
  23234. });
  23235. label.appendChild(boundingBoxesCheckbox);
  23236. label.appendChild(document.createTextNode(title));
  23237. root.appendChild(label);
  23238. root.appendChild(document.createElement("br"));
  23239. };
  23240. DebugLayer.prototype._generateDOMelements = function () {
  23241. var _this = this;
  23242. var background = "rgba(128, 128, 128, 0.4)";
  23243. this._statsDiv = document.createElement("div");
  23244. this._statsDiv.id = "Debug Layer - Stats";
  23245. this._statsDiv.style.position = "absolute";
  23246. this._statsDiv.style.background = background;
  23247. this._statsDiv.style.padding = "10px";
  23248. this._statsDiv.style.pointerEvents = "none";
  23249. this._statsDiv.style.overflowY = "auto";
  23250. this._logDiv = document.createElement("div");
  23251. this._logDiv.id = "Debug Layer - Logs";
  23252. this._logDiv.style.position = "absolute";
  23253. this._logDiv.style.background = background;
  23254. this._logDiv.style.padding = "10px";
  23255. this._logDiv.style.pointerEvents = "none";
  23256. this._logDiv.style.fontSize = "12px";
  23257. this._logDiv.style.fontFamily = "consolas";
  23258. this._logDiv.style.maxHeight = "300px";
  23259. this._logDiv.style.overflowY = "auto";
  23260. this._logDiv.style.display = "none";
  23261. this._logDiv.innerHTML = BABYLON.Tools.LogCache;
  23262. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  23263. _this._logDiv.innerHTML = entry + _this._logDiv.innerHTML;
  23264. };
  23265. this._drawingCanvas = document.createElement("canvas");
  23266. this._drawingCanvas.id = "Debug Layer - Drawing canvas";
  23267. this._drawingCanvas.style.position = "absolute";
  23268. this._drawingCanvas.style.pointerEvents = "none";
  23269. this._drawingContext = this._drawingCanvas.getContext("2d");
  23270. this._optionsDiv = document.createElement("div");
  23271. this._optionsDiv.id = "Debug Layer - Options";
  23272. this._optionsDiv.style.position = "absolute";
  23273. this._optionsDiv.style.background = background;
  23274. this._optionsDiv.style.padding = "10px";
  23275. this._optionsDiv.style.overflowY = "auto";
  23276. this._generateTexBox(this._optionsDiv, "<b>General:</b>");
  23277. this._generateCheckBox(this._optionsDiv, "Statistics", this._displayStatistics, function (element) {
  23278. _this._displayStatistics = element.checked;
  23279. });
  23280. this._generateCheckBox(this._optionsDiv, "Logs", this._displayLogs, function (element) {
  23281. _this._displayLogs = element.checked;
  23282. });
  23283. this._generateCheckBox(this._optionsDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  23284. _this._scene.forceShowBoundingBoxes = element.checked;
  23285. });
  23286. this._generateCheckBox(this._optionsDiv, "Wireframe", this._scene.forceWireframe, function (element) {
  23287. _this._scene.forceWireframe = element.checked;
  23288. });
  23289. this._generateCheckBox(this._optionsDiv, "Labels", this._labelsEnabled, function (element) {
  23290. _this._labelsEnabled = element.checked;
  23291. if (!_this._labelsEnabled) {
  23292. _this._clearLabels();
  23293. }
  23294. });
  23295. this._optionsDiv.appendChild(document.createElement("br"));
  23296. this._generateTexBox(this._optionsDiv, "<b>Texture Channels:</b>");
  23297. this._generateCheckBox(this._optionsDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  23298. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  23299. });
  23300. this._generateCheckBox(this._optionsDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  23301. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  23302. });
  23303. this._generateCheckBox(this._optionsDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  23304. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  23305. });
  23306. this._generateCheckBox(this._optionsDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  23307. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  23308. });
  23309. this._generateCheckBox(this._optionsDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  23310. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  23311. });
  23312. this._generateCheckBox(this._optionsDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  23313. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  23314. });
  23315. this._generateCheckBox(this._optionsDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  23316. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  23317. });
  23318. this._optionsDiv.appendChild(document.createElement("br"));
  23319. this._generateTexBox(this._optionsDiv, "<b>Options:</b>");
  23320. this._generateCheckBox(this._optionsDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  23321. _this._scene.shadowsEnabled = element.checked;
  23322. });
  23323. this._generateCheckBox(this._optionsDiv, "Particles", this._scene.particlesEnabled, function (element) {
  23324. _this._scene.particlesEnabled = element.checked;
  23325. });
  23326. this._generateCheckBox(this._optionsDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  23327. _this._scene.postProcessesEnabled = element.checked;
  23328. });
  23329. this._generateCheckBox(this._optionsDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  23330. _this._scene.collisionsEnabled = element.checked;
  23331. });
  23332. this._generateCheckBox(this._optionsDiv, "Lights", this._scene.lightsEnabled, function (element) {
  23333. _this._scene.lightsEnabled = element.checked;
  23334. });
  23335. this._generateCheckBox(this._optionsDiv, "Textures", this._scene.texturesEnabled, function (element) {
  23336. _this._scene.texturesEnabled = element.checked;
  23337. });
  23338. this._generateCheckBox(this._optionsDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  23339. _this._scene.lensFlaresEnabled = element.checked;
  23340. });
  23341. this._generateCheckBox(this._optionsDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  23342. _this._scene.renderTargetsEnabled = element.checked;
  23343. });
  23344. this._generateCheckBox(this._optionsDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  23345. _this._scene.proceduralTexturesEnabled = element.checked;
  23346. });
  23347. this._globalDiv.appendChild(this._drawingCanvas);
  23348. this._globalDiv.appendChild(this._statsDiv);
  23349. this._globalDiv.appendChild(this._logDiv);
  23350. this._globalDiv.appendChild(this._optionsDiv);
  23351. this._globalDiv.id = "Debug Layer";
  23352. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  23353. this._globalDiv.style.fontSize = "14px";
  23354. this._globalDiv.style.color = "white";
  23355. };
  23356. DebugLayer.prototype._displayStats = function () {
  23357. var scene = this._scene;
  23358. var engine = scene.getEngine();
  23359. this._statsDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(BABYLON.Tools.GetFps(), 0) + " fps</b><br><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br><br>" + "Frame duration: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<i>Evaluate Active Meshes duration:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "<i>Render Targets duration:</i> " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "<i>Particles duration:</i> " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "<i>Sprites duration:</i> " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br>" + "<i>Render duration:</i> <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b>";
  23360. };
  23361. return DebugLayer;
  23362. })();
  23363. BABYLON.DebugLayer = DebugLayer;
  23364. })(BABYLON || (BABYLON = {}));
  23365. var BABYLON;
  23366. (function (BABYLON) {
  23367. var Boxels = (function () {
  23368. function Boxels() {
  23369. }
  23370. Boxels.CreateBox = function (name, size, scene, updatable) {
  23371. var box = new BABYLON.Mesh(name, scene);
  23372. var vertexData = BABYLON.Boxels.CreateBoxVertexData(size);
  23373. vertexData.applyToMesh(box, updatable);
  23374. return box;
  23375. };
  23376. Boxels.CreateBoxVertexData = function (size) {
  23377. var normalsSource = [
  23378. new BABYLON.Vector3(0, 0, 1),
  23379. new BABYLON.Vector3(0, 0, -1),
  23380. new BABYLON.Vector3(1, 0, 0),
  23381. new BABYLON.Vector3(-1, 0, 0),
  23382. new BABYLON.Vector3(0, 1, 0),
  23383. new BABYLON.Vector3(0, -1, 0)
  23384. ];
  23385. var indices = [];
  23386. var positions = [];
  23387. var normals = [];
  23388. var uvs = [];
  23389. size = size || 1;
  23390. for (var index = 0; index < normalsSource.length; index++) {
  23391. var normal = normalsSource[index];
  23392. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23393. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23394. var verticesLength = positions.length / 3;
  23395. indices.push(verticesLength);
  23396. indices.push(verticesLength + 1);
  23397. indices.push(verticesLength + 2);
  23398. indices.push(verticesLength);
  23399. indices.push(verticesLength + 2);
  23400. indices.push(verticesLength + 3);
  23401. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  23402. positions.push(vertex.x, vertex.y, vertex.z);
  23403. normals.push(normal.x, normal.y, normal.z);
  23404. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  23405. positions.push(vertex.x, vertex.y, vertex.z);
  23406. normals.push(normal.x, normal.y, normal.z);
  23407. vertex = normal.add(side1).add(side2).scale(size / 2);
  23408. positions.push(vertex.x, vertex.y, vertex.z);
  23409. normals.push(normal.x, normal.y, normal.z);
  23410. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  23411. positions.push(vertex.x, vertex.y, vertex.z);
  23412. normals.push(normal.x, normal.y, normal.z);
  23413. if (normal.x == 1) {
  23414. uvs.push(1.0, 0.0);
  23415. uvs.push(1.0, 1.0);
  23416. uvs.push(0.0, 1.0);
  23417. uvs.push(0.0, 0.0);
  23418. } else if (normal.z == 1) {
  23419. uvs.push(1.0, 1.0);
  23420. uvs.push(0.0, 1.0);
  23421. uvs.push(0.0, 0.0);
  23422. uvs.push(1.0, 0.0);
  23423. } else if (normal.x == -1) {
  23424. uvs.push(1.0, 0.0);
  23425. uvs.push(1.0, 1.0);
  23426. uvs.push(0.0, 1.0);
  23427. uvs.push(0.0, 0.0);
  23428. } else if (normal.z == -1) {
  23429. uvs.push(0.0, 0.0);
  23430. uvs.push(1.0, 0.0);
  23431. uvs.push(1.0, 1.0);
  23432. uvs.push(0.0, 1.0);
  23433. } else {
  23434. uvs.push(1.0, 1.0);
  23435. uvs.push(0.0, 1.0);
  23436. uvs.push(0.0, 0.0);
  23437. uvs.push(1.0, 0.0);
  23438. }
  23439. }
  23440. var vertexData = new BABYLON.VertexData();
  23441. vertexData.indices = indices;
  23442. vertexData.positions = positions;
  23443. vertexData.normals = normals;
  23444. vertexData.uvs = uvs;
  23445. return vertexData;
  23446. };
  23447. return Boxels;
  23448. })();
  23449. BABYLON.Boxels = Boxels;
  23450. })(BABYLON || (BABYLON = {}));