babylon.2.0-alpha.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array) {
  91. return new Color3(array[0], array[1], array[2]);
  92. };
  93. Color3.FromInts = function (r, g, b) {
  94. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  95. };
  96. Color3.Lerp = function (start, end, amount) {
  97. var r = start.r + ((end.r - start.r) * amount);
  98. var g = start.g + ((end.g - start.g) * amount);
  99. var b = start.b + ((end.b - start.b) * amount);
  100. return new Color3(r, g, b);
  101. };
  102. Color3.Red = function () {
  103. return new Color3(1, 0, 0);
  104. };
  105. Color3.Green = function () {
  106. return new Color3(0, 1, 0);
  107. };
  108. Color3.Blue = function () {
  109. return new Color3(0, 0, 1);
  110. };
  111. Color3.Black = function () {
  112. return new Color3(0, 0, 0);
  113. };
  114. Color3.White = function () {
  115. return new Color3(1, 1, 1);
  116. };
  117. Color3.Purple = function () {
  118. return new Color3(0.5, 0, 0.5);
  119. };
  120. Color3.Magenta = function () {
  121. return new Color3(1, 0, 1);
  122. };
  123. Color3.Yellow = function () {
  124. return new Color3(1, 1, 0);
  125. };
  126. Color3.Gray = function () {
  127. return new Color3(0.5, 0.5, 0.5);
  128. };
  129. return Color3;
  130. })();
  131. BABYLON.Color3 = Color3;
  132. var Color4 = (function () {
  133. function Color4(r, g, b, a) {
  134. this.r = r;
  135. this.g = g;
  136. this.b = b;
  137. this.a = a;
  138. }
  139. // Operators
  140. Color4.prototype.addInPlace = function (right) {
  141. this.r += right.r;
  142. this.g += right.g;
  143. this.b += right.b;
  144. this.a += right.a;
  145. };
  146. Color4.prototype.asArray = function () {
  147. var result = [];
  148. this.toArray(result, 0);
  149. return result;
  150. };
  151. Color4.prototype.toArray = function (array, index) {
  152. if (index === undefined) {
  153. index = 0;
  154. }
  155. array[index] = this.r;
  156. array[index + 1] = this.g;
  157. array[index + 2] = this.b;
  158. array[index + 3] = this.a;
  159. };
  160. Color4.prototype.add = function (right) {
  161. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  162. };
  163. Color4.prototype.subtract = function (right) {
  164. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  165. };
  166. Color4.prototype.subtractToRef = function (right, result) {
  167. result.r = this.r - right.r;
  168. result.g = this.g - right.g;
  169. result.b = this.b - right.b;
  170. result.a = this.a - right.a;
  171. };
  172. Color4.prototype.scale = function (scale) {
  173. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  174. };
  175. Color4.prototype.scaleToRef = function (scale, result) {
  176. result.r = this.r * scale;
  177. result.g = this.g * scale;
  178. result.b = this.b * scale;
  179. result.a = this.a * scale;
  180. };
  181. Color4.prototype.toString = function () {
  182. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  183. };
  184. Color4.prototype.clone = function () {
  185. return new Color4(this.r, this.g, this.b, this.a);
  186. };
  187. // Statics
  188. Color4.Lerp = function (left, right, amount) {
  189. var result = new Color4(0, 0, 0, 0);
  190. Color4.LerpToRef(left, right, amount, result);
  191. return result;
  192. };
  193. Color4.LerpToRef = function (left, right, amount, result) {
  194. result.r = left.r + (right.r - left.r) * amount;
  195. result.g = left.g + (right.g - left.g) * amount;
  196. result.b = left.b + (right.b - left.b) * amount;
  197. result.a = left.a + (right.a - left.a) * amount;
  198. };
  199. Color4.FromArray = function (array, offset) {
  200. if (typeof offset === "undefined") { offset = 0; }
  201. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  202. };
  203. Color4.FromInts = function (r, g, b, a) {
  204. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  205. };
  206. return Color4;
  207. })();
  208. BABYLON.Color4 = Color4;
  209. var Vector2 = (function () {
  210. function Vector2(x, y) {
  211. this.x = x;
  212. this.y = y;
  213. }
  214. Vector2.prototype.toString = function () {
  215. return "{X: " + this.x + " Y:" + this.y + "}";
  216. };
  217. // Operators
  218. Vector2.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. };
  225. Vector2.prototype.asArray = function () {
  226. var result = [];
  227. this.toArray(result, 0);
  228. return result;
  229. };
  230. Vector2.prototype.copyFrom = function (source) {
  231. this.x = source.x;
  232. this.y = source.y;
  233. };
  234. Vector2.prototype.copyFromFloats = function (x, y) {
  235. this.x = x;
  236. this.y = y;
  237. };
  238. Vector2.prototype.add = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.addVector3 = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.subtract = function (otherVector) {
  245. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  246. };
  247. Vector2.prototype.subtractInPlace = function (otherVector) {
  248. this.x -= otherVector.x;
  249. this.y -= otherVector.y;
  250. };
  251. Vector2.prototype.multiplyInPlace = function (otherVector) {
  252. this.x *= otherVector.x;
  253. this.y *= otherVector.y;
  254. };
  255. Vector2.prototype.multiply = function (otherVector) {
  256. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  257. };
  258. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  259. result.x = this.x * otherVector.x;
  260. result.y = this.y * otherVector.y;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. };
  272. Vector2.prototype.negate = function () {
  273. return new Vector2(-this.x, -this.y);
  274. };
  275. Vector2.prototype.scaleInPlace = function (scale) {
  276. this.x *= scale;
  277. this.y *= scale;
  278. return this;
  279. };
  280. Vector2.prototype.scale = function (scale) {
  281. return new Vector2(this.x * scale, this.y * scale);
  282. };
  283. Vector2.prototype.equals = function (otherVector) {
  284. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  285. };
  286. // Properties
  287. Vector2.prototype.length = function () {
  288. return Math.sqrt(this.x * this.x + this.y * this.y);
  289. };
  290. Vector2.prototype.lengthSquared = function () {
  291. return (this.x * this.x + this.y * this.y);
  292. };
  293. // Methods
  294. Vector2.prototype.normalize = function () {
  295. var len = this.length();
  296. if (len === 0)
  297. return this;
  298. var num = 1.0 / len;
  299. this.x *= num;
  300. this.y *= num;
  301. return this;
  302. };
  303. Vector2.prototype.clone = function () {
  304. return new Vector2(this.x, this.y);
  305. };
  306. // Statics
  307. Vector2.Zero = function () {
  308. return new Vector2(0, 0);
  309. };
  310. Vector2.FromArray = function (array, offset) {
  311. if (!offset) {
  312. offset = 0;
  313. }
  314. return new Vector2(array[offset], array[offset + 1]);
  315. };
  316. Vector2.FromArrayToRef = function (array, offset, result) {
  317. result.x = array[offset];
  318. result.y = array[offset + 1];
  319. };
  320. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  321. var squared = amount * amount;
  322. var cubed = amount * squared;
  323. 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));
  324. 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));
  325. return new Vector2(x, y);
  326. };
  327. Vector2.Clamp = function (value, min, max) {
  328. var x = value.x;
  329. x = (x > max.x) ? max.x : x;
  330. x = (x < min.x) ? min.x : x;
  331. var y = value.y;
  332. y = (y > max.y) ? max.y : y;
  333. y = (y < min.y) ? min.y : y;
  334. return new Vector2(x, y);
  335. };
  336. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  337. var squared = amount * amount;
  338. var cubed = amount * squared;
  339. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  340. var part2 = (-2.0 * cubed) + (3.0 * squared);
  341. var part3 = (cubed - (2.0 * squared)) + amount;
  342. var part4 = cubed - squared;
  343. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  344. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Lerp = function (start, end, amount) {
  348. var x = start.x + ((end.x - start.x) * amount);
  349. var y = start.y + ((end.y - start.y) * amount);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Dot = function (left, right) {
  353. return left.x * right.x + left.y * right.y;
  354. };
  355. Vector2.Normalize = function (vector) {
  356. var newVector = vector.clone();
  357. newVector.normalize();
  358. return newVector;
  359. };
  360. Vector2.Minimize = function (left, right) {
  361. var x = (left.x < right.x) ? left.x : right.x;
  362. var y = (left.y < right.y) ? left.y : right.y;
  363. return new Vector2(x, y);
  364. };
  365. Vector2.Maximize = function (left, right) {
  366. var x = (left.x > right.x) ? left.x : right.x;
  367. var y = (left.y > right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Transform = function (vector, transformation) {
  371. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  372. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Distance = function (value1, value2) {
  376. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  377. };
  378. Vector2.DistanceSquared = function (value1, value2) {
  379. var x = value1.x - value2.x;
  380. var y = value1.y - value2.y;
  381. return (x * x) + (y * y);
  382. };
  383. return Vector2;
  384. })();
  385. BABYLON.Vector2 = Vector2;
  386. var Vector3 = (function () {
  387. function Vector3(x, y, z) {
  388. this.x = x;
  389. this.y = y;
  390. this.z = z;
  391. }
  392. Vector3.prototype.toString = function () {
  393. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  394. };
  395. // Operators
  396. Vector3.prototype.asArray = function () {
  397. var result = [];
  398. this.toArray(result, 0);
  399. return result;
  400. };
  401. Vector3.prototype.toArray = function (array, index) {
  402. if (index === undefined) {
  403. index = 0;
  404. }
  405. array[index] = this.x;
  406. array[index + 1] = this.y;
  407. array[index + 2] = this.z;
  408. };
  409. Vector3.prototype.addInPlace = function (otherVector) {
  410. this.x += otherVector.x;
  411. this.y += otherVector.y;
  412. this.z += otherVector.z;
  413. };
  414. Vector3.prototype.add = function (otherVector) {
  415. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  416. };
  417. Vector3.prototype.addToRef = function (otherVector, result) {
  418. result.x = this.x + otherVector.x;
  419. result.y = this.y + otherVector.y;
  420. result.z = this.z + otherVector.z;
  421. };
  422. Vector3.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. this.z -= otherVector.z;
  426. };
  427. Vector3.prototype.subtract = function (otherVector) {
  428. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  429. };
  430. Vector3.prototype.subtractToRef = function (otherVector, result) {
  431. result.x = this.x - otherVector.x;
  432. result.y = this.y - otherVector.y;
  433. result.z = this.z - otherVector.z;
  434. };
  435. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  436. return new Vector3(this.x - x, this.y - y, this.z - z);
  437. };
  438. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  439. result.x = this.x - x;
  440. result.y = this.y - y;
  441. result.z = this.z - z;
  442. };
  443. Vector3.prototype.negate = function () {
  444. return new Vector3(-this.x, -this.y, -this.z);
  445. };
  446. Vector3.prototype.scaleInPlace = function (scale) {
  447. this.x *= scale;
  448. this.y *= scale;
  449. this.z *= scale;
  450. return this;
  451. };
  452. Vector3.prototype.scale = function (scale) {
  453. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  454. };
  455. Vector3.prototype.scaleToRef = function (scale, result) {
  456. result.x = this.x * scale;
  457. result.y = this.y * scale;
  458. result.z = this.z * scale;
  459. };
  460. Vector3.prototype.equals = function (otherVector) {
  461. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  462. };
  463. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  464. 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;
  465. };
  466. Vector3.prototype.equalsToFloats = function (x, y, z) {
  467. return this.x === x && this.y === y && this.z === z;
  468. };
  469. Vector3.prototype.multiplyInPlace = function (otherVector) {
  470. this.x *= otherVector.x;
  471. this.y *= otherVector.y;
  472. this.z *= otherVector.z;
  473. };
  474. Vector3.prototype.multiply = function (otherVector) {
  475. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  476. };
  477. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  478. result.x = this.x * otherVector.x;
  479. result.y = this.y * otherVector.y;
  480. result.z = this.z * otherVector.z;
  481. };
  482. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  483. return new Vector3(this.x * x, this.y * y, this.z * z);
  484. };
  485. Vector3.prototype.divide = function (otherVector) {
  486. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  487. };
  488. Vector3.prototype.divideToRef = function (otherVector, result) {
  489. result.x = this.x / otherVector.x;
  490. result.y = this.y / otherVector.y;
  491. result.z = this.z / otherVector.z;
  492. };
  493. Vector3.prototype.MinimizeInPlace = function (other) {
  494. if (other.x < this.x)
  495. this.x = other.x;
  496. if (other.y < this.y)
  497. this.y = other.y;
  498. if (other.z < this.z)
  499. this.z = other.z;
  500. };
  501. Vector3.prototype.MaximizeInPlace = function (other) {
  502. if (other.x > this.x)
  503. this.x = other.x;
  504. if (other.y > this.y)
  505. this.y = other.y;
  506. if (other.z > this.z)
  507. this.z = other.z;
  508. };
  509. // Properties
  510. Vector3.prototype.length = function () {
  511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  512. };
  513. Vector3.prototype.lengthSquared = function () {
  514. return (this.x * this.x + this.y * this.y + this.z * this.z);
  515. };
  516. // Methods
  517. Vector3.prototype.normalize = function () {
  518. var len = this.length();
  519. if (len === 0)
  520. return this;
  521. var num = 1.0 / len;
  522. this.x *= num;
  523. this.y *= num;
  524. this.z *= num;
  525. return this;
  526. };
  527. Vector3.prototype.clone = function () {
  528. return new Vector3(this.x, this.y, this.z);
  529. };
  530. Vector3.prototype.copyFrom = function (source) {
  531. this.x = source.x;
  532. this.y = source.y;
  533. this.z = source.z;
  534. };
  535. Vector3.prototype.copyFromFloats = function (x, y, z) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. };
  540. // Statics
  541. Vector3.FromArray = function (array, offset) {
  542. if (!offset) {
  543. offset = 0;
  544. }
  545. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  546. };
  547. Vector3.FromArrayToRef = function (array, offset, result) {
  548. result.x = array[offset];
  549. result.y = array[offset + 1];
  550. result.z = array[offset + 2];
  551. };
  552. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatsToRef = function (x, y, z, result) {
  558. result.x = x;
  559. result.y = y;
  560. result.z = z;
  561. };
  562. Vector3.Zero = function () {
  563. return new Vector3(0, 0, 0);
  564. };
  565. Vector3.Up = function () {
  566. return new Vector3(0, 1.0, 0);
  567. };
  568. Vector3.TransformCoordinates = function (vector, transformation) {
  569. var result = Vector3.Zero();
  570. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  571. return result;
  572. };
  573. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  574. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  575. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  576. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  577. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  578. result.x = x / w;
  579. result.y = y / w;
  580. result.z = z / w;
  581. };
  582. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  583. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  584. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  585. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  586. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  587. result.x = rx / rw;
  588. result.y = ry / rw;
  589. result.z = rz / rw;
  590. };
  591. Vector3.TransformNormal = function (vector, transformation) {
  592. var result = Vector3.Zero();
  593. Vector3.TransformNormalToRef(vector, transformation, result);
  594. return result;
  595. };
  596. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  597. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  598. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  599. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  600. };
  601. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  602. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  603. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  604. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  605. };
  606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  607. var squared = amount * amount;
  608. var cubed = amount * squared;
  609. 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));
  610. 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));
  611. 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));
  612. return new Vector3(x, y, z);
  613. };
  614. Vector3.Clamp = function (value, min, max) {
  615. var x = value.x;
  616. x = (x > max.x) ? max.x : x;
  617. x = (x < min.x) ? min.x : x;
  618. var y = value.y;
  619. y = (y > max.y) ? max.y : y;
  620. y = (y < min.y) ? min.y : y;
  621. var z = value.z;
  622. z = (z > max.z) ? max.z : z;
  623. z = (z < min.z) ? min.z : z;
  624. return new Vector3(x, y, z);
  625. };
  626. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  627. var squared = amount * amount;
  628. var cubed = amount * squared;
  629. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  630. var part2 = (-2.0 * cubed) + (3.0 * squared);
  631. var part3 = (cubed - (2.0 * squared)) + amount;
  632. var part4 = cubed - squared;
  633. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  634. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  635. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  636. return new Vector3(x, y, z);
  637. };
  638. Vector3.Lerp = function (start, end, amount) {
  639. var x = start.x + ((end.x - start.x) * amount);
  640. var y = start.y + ((end.y - start.y) * amount);
  641. var z = start.z + ((end.z - start.z) * amount);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Dot = function (left, right) {
  645. return (left.x * right.x + left.y * right.y + left.z * right.z);
  646. };
  647. Vector3.Cross = function (left, right) {
  648. var result = Vector3.Zero();
  649. Vector3.CrossToRef(left, right, result);
  650. return result;
  651. };
  652. Vector3.CrossToRef = function (left, right, result) {
  653. result.x = left.y * right.z - left.z * right.y;
  654. result.y = left.z * right.x - left.x * right.z;
  655. result.z = left.x * right.y - left.y * right.x;
  656. };
  657. Vector3.Normalize = function (vector) {
  658. var result = Vector3.Zero();
  659. Vector3.NormalizeToRef(vector, result);
  660. return result;
  661. };
  662. Vector3.NormalizeToRef = function (vector, result) {
  663. result.copyFrom(vector);
  664. result.normalize();
  665. };
  666. Vector3.Project = function (vector, world, transform, viewport) {
  667. var cw = viewport.width;
  668. var ch = viewport.height;
  669. var cx = viewport.x;
  670. var cy = viewport.y;
  671. var viewportMatrix = 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);
  672. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  673. return Vector3.TransformCoordinates(vector, finalMatrix);
  674. };
  675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  676. var matrix = world.multiply(transform);
  677. matrix.invert();
  678. source.x = source.x / viewportWidth * 2 - 1;
  679. source.y = -(source.y / viewportHeight * 2 - 1);
  680. var vector = Vector3.TransformCoordinates(source, matrix);
  681. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  682. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  683. vector = vector.scale(1.0 / num);
  684. }
  685. return vector;
  686. };
  687. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  688. var matrix = world.multiply(view).multiply(projection);
  689. matrix.invert();
  690. source.x = source.x / viewportWidth * 2 - 1;
  691. source.y = -(source.y / viewportHeight * 2 - 1);
  692. var vector = Vector3.TransformCoordinates(source, matrix);
  693. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  694. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  695. vector = vector.scale(1.0 / num);
  696. }
  697. return vector;
  698. };
  699. Vector3.Minimize = function (left, right) {
  700. var min = left.clone();
  701. min.MinimizeInPlace(right);
  702. return min;
  703. };
  704. Vector3.Maximize = function (left, right) {
  705. var max = left.clone();
  706. max.MaximizeInPlace(right);
  707. return max;
  708. };
  709. Vector3.Distance = function (value1, value2) {
  710. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  711. };
  712. Vector3.DistanceSquared = function (value1, value2) {
  713. var x = value1.x - value2.x;
  714. var y = value1.y - value2.y;
  715. var z = value1.z - value2.z;
  716. return (x * x) + (y * y) + (z * z);
  717. };
  718. Vector3.Center = function (value1, value2) {
  719. var center = value1.add(value2);
  720. center.scaleInPlace(0.5);
  721. return center;
  722. };
  723. return Vector3;
  724. })();
  725. BABYLON.Vector3 = Vector3;
  726. //Vector4 class created for EulerAngle class conversion to Quaternion
  727. var Vector4 = (function () {
  728. function Vector4(x, y, z, w) {
  729. this.x = x;
  730. this.y = y;
  731. this.z = z;
  732. this.w = w;
  733. }
  734. Vector4.prototype.toString = function () {
  735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  736. };
  737. // Operators
  738. Vector4.prototype.asArray = function () {
  739. var result = [];
  740. this.toArray(result, 0);
  741. return result;
  742. };
  743. Vector4.prototype.toArray = function (array, index) {
  744. if (index === undefined) {
  745. index = 0;
  746. }
  747. array[index] = this.x;
  748. array[index + 1] = this.y;
  749. array[index + 2] = this.z;
  750. array[index + 3] = this.w;
  751. };
  752. Vector4.prototype.addInPlace = function (otherVector) {
  753. this.x += otherVector.x;
  754. this.y += otherVector.y;
  755. this.z += otherVector.z;
  756. this.w += otherVector.w;
  757. };
  758. Vector4.prototype.add = function (otherVector) {
  759. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  760. };
  761. Vector4.prototype.addToRef = function (otherVector, result) {
  762. result.x = this.x + otherVector.x;
  763. result.y = this.y + otherVector.y;
  764. result.z = this.z + otherVector.z;
  765. result.w = this.w + otherVector.w;
  766. };
  767. Vector4.prototype.subtractInPlace = function (otherVector) {
  768. this.x -= otherVector.x;
  769. this.y -= otherVector.y;
  770. this.z -= otherVector.z;
  771. this.w -= otherVector.w;
  772. };
  773. Vector4.prototype.subtract = function (otherVector) {
  774. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  775. };
  776. Vector4.prototype.subtractToRef = function (otherVector, result) {
  777. result.x = this.x - otherVector.x;
  778. result.y = this.y - otherVector.y;
  779. result.z = this.z - otherVector.z;
  780. result.w = this.w - otherVector.w;
  781. };
  782. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  783. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  784. };
  785. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  786. result.x = this.x - x;
  787. result.y = this.y - y;
  788. result.z = this.z - z;
  789. result.w = this.w - w;
  790. };
  791. Vector4.prototype.negate = function () {
  792. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  793. };
  794. Vector4.prototype.scaleInPlace = function (scale) {
  795. this.x *= scale;
  796. this.y *= scale;
  797. this.z *= scale;
  798. this.w *= scale;
  799. return this;
  800. };
  801. Vector4.prototype.scale = function (scale) {
  802. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  803. };
  804. Vector4.prototype.scaleToRef = function (scale, result) {
  805. result.x = this.x * scale;
  806. result.y = this.y * scale;
  807. result.z = this.z * scale;
  808. result.w = this.w * scale;
  809. };
  810. Vector4.prototype.equals = function (otherVector) {
  811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  812. };
  813. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  814. 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;
  815. };
  816. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  817. return this.x === x && this.y === y && this.z === z && this.w === w;
  818. };
  819. Vector4.prototype.multiplyInPlace = function (otherVector) {
  820. this.x *= otherVector.x;
  821. this.y *= otherVector.y;
  822. this.z *= otherVector.z;
  823. this.w *= otherVector.w;
  824. };
  825. Vector4.prototype.multiply = function (otherVector) {
  826. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  827. };
  828. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  829. result.x = this.x * otherVector.x;
  830. result.y = this.y * otherVector.y;
  831. result.z = this.z * otherVector.z;
  832. result.w = this.w * otherVector.w;
  833. };
  834. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  835. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  836. };
  837. Vector4.prototype.divide = function (otherVector) {
  838. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  839. };
  840. Vector4.prototype.divideToRef = function (otherVector, result) {
  841. result.x = this.x / otherVector.x;
  842. result.y = this.y / otherVector.y;
  843. result.z = this.z / otherVector.z;
  844. result.w = this.w / otherVector.w;
  845. };
  846. Vector4.prototype.MinimizeInPlace = function (other) {
  847. if (other.x < this.x)
  848. this.x = other.x;
  849. if (other.y < this.y)
  850. this.y = other.y;
  851. if (other.z < this.z)
  852. this.z = other.z;
  853. if (other.w < this.w)
  854. this.w = other.w;
  855. };
  856. Vector4.prototype.MaximizeInPlace = function (other) {
  857. if (other.x > this.x)
  858. this.x = other.x;
  859. if (other.y > this.y)
  860. this.y = other.y;
  861. if (other.z > this.z)
  862. this.z = other.z;
  863. if (other.w > this.w)
  864. this.w = other.w;
  865. };
  866. // Properties
  867. Vector4.prototype.length = function () {
  868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  869. };
  870. Vector4.prototype.lengthSquared = function () {
  871. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  872. };
  873. // Methods
  874. Vector4.prototype.normalize = function () {
  875. var len = this.length();
  876. if (len === 0)
  877. return this;
  878. var num = 1.0 / len;
  879. this.x *= num;
  880. this.y *= num;
  881. this.z *= num;
  882. this.w *= num;
  883. return this;
  884. };
  885. Vector4.prototype.clone = function () {
  886. return new Vector4(this.x, this.y, this.z, this.w);
  887. };
  888. Vector4.prototype.copyFrom = function (source) {
  889. this.x = source.x;
  890. this.y = source.y;
  891. this.z = source.z;
  892. this.w = source.w;
  893. };
  894. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. };
  900. // Statics
  901. Vector4.FromArray = function (array, offset) {
  902. if (!offset) {
  903. offset = 0;
  904. }
  905. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  906. };
  907. Vector4.FromArrayToRef = function (array, offset, result) {
  908. result.x = array[offset];
  909. result.y = array[offset + 1];
  910. result.z = array[offset + 2];
  911. result.w = array[offset + 3];
  912. };
  913. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  914. result.x = array[offset];
  915. result.y = array[offset + 1];
  916. result.z = array[offset + 2];
  917. result.w = array[offset + 3];
  918. };
  919. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  920. result.x = x;
  921. result.y = y;
  922. result.z = z;
  923. result.w = w;
  924. };
  925. Vector4.Zero = function () {
  926. return new Vector4(0, 0, 0, 0);
  927. };
  928. Vector4.Normalize = function (vector) {
  929. var result = Vector4.Zero();
  930. Vector4.NormalizeToRef(vector, result);
  931. return result;
  932. };
  933. Vector4.NormalizeToRef = function (vector, result) {
  934. result.copyFrom(vector);
  935. result.normalize();
  936. };
  937. Vector4.Minimize = function (left, right) {
  938. var min = left.clone();
  939. min.MinimizeInPlace(right);
  940. return min;
  941. };
  942. Vector4.Maximize = function (left, right) {
  943. var max = left.clone();
  944. max.MaximizeInPlace(right);
  945. return max;
  946. };
  947. Vector4.Distance = function (value1, value2) {
  948. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  949. };
  950. Vector4.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. var z = value1.z - value2.z;
  954. var w = value1.w - value2.w;
  955. return (x * x) + (y * y) + (z * z) + (w * w);
  956. };
  957. Vector4.Center = function (value1, value2) {
  958. var center = value1.add(value2);
  959. center.scaleInPlace(0.5);
  960. return center;
  961. };
  962. return Vector4;
  963. })();
  964. BABYLON.Vector4 = Vector4;
  965. var Quaternion = (function () {
  966. function Quaternion(x, y, z, w) {
  967. if (typeof x === "undefined") { x = 0; }
  968. if (typeof y === "undefined") { y = 0; }
  969. if (typeof z === "undefined") { z = 0; }
  970. if (typeof w === "undefined") { w = 1; }
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. this.w = w;
  975. }
  976. Quaternion.prototype.toString = function () {
  977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  978. };
  979. Quaternion.prototype.asArray = function () {
  980. return [this.x, this.y, this.z, this.w];
  981. };
  982. Quaternion.prototype.equals = function (otherQuaternion) {
  983. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  984. };
  985. Quaternion.prototype.clone = function () {
  986. return new Quaternion(this.x, this.y, this.z, this.w);
  987. };
  988. Quaternion.prototype.copyFrom = function (other) {
  989. this.x = other.x;
  990. this.y = other.y;
  991. this.z = other.z;
  992. this.w = other.w;
  993. };
  994. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. };
  1000. Quaternion.prototype.add = function (other) {
  1001. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1002. };
  1003. Quaternion.prototype.subtract = function (other) {
  1004. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1005. };
  1006. Quaternion.prototype.scale = function (value) {
  1007. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1008. };
  1009. Quaternion.prototype.multiply = function (q1) {
  1010. var result = new Quaternion(0, 0, 0, 1.0);
  1011. this.multiplyToRef(q1, result);
  1012. return result;
  1013. };
  1014. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1015. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1016. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1017. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1018. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1019. };
  1020. Quaternion.prototype.length = function () {
  1021. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1022. };
  1023. Quaternion.prototype.normalize = function () {
  1024. var length = 1.0 / this.length();
  1025. this.x *= length;
  1026. this.y *= length;
  1027. this.z *= length;
  1028. this.w *= length;
  1029. };
  1030. Quaternion.prototype.toEulerAngles = function () {
  1031. var result = Vector3.Zero();
  1032. this.toEulerAnglesToRef(result);
  1033. return result;
  1034. };
  1035. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1036. //result is an EulerAngles in the in the z-x-z convention
  1037. var qx = this.x;
  1038. var qy = this.y;
  1039. var qz = this.z;
  1040. var qw = this.w;
  1041. var qxy = qx * qy;
  1042. var qxz = qx * qz;
  1043. var qwy = qw * qy;
  1044. var qwz = qw * qz;
  1045. var qwx = qw * qx;
  1046. var qyz = qy * qz;
  1047. var sqx = qx * qx;
  1048. var sqy = qy * qy;
  1049. var determinant = sqx + sqy;
  1050. if (determinant !== 0.000 && determinant !== 1.000) {
  1051. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1052. result.y = Math.acos(1 - 2 * determinant);
  1053. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1054. } else {
  1055. if (determinant === 0.0) {
  1056. result.x = 0.0;
  1057. result.y = 0.0;
  1058. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1059. } else {
  1060. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1061. result.y = Math.PI;
  1062. result.z = 0.0;
  1063. }
  1064. }
  1065. };
  1066. Quaternion.prototype.toRotationMatrix = function (result) {
  1067. var xx = this.x * this.x;
  1068. var yy = this.y * this.y;
  1069. var zz = this.z * this.z;
  1070. var xy = this.x * this.y;
  1071. var zw = this.z * this.w;
  1072. var zx = this.z * this.x;
  1073. var yw = this.y * this.w;
  1074. var yz = this.y * this.z;
  1075. var xw = this.x * this.w;
  1076. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1077. result.m[1] = 2.0 * (xy + zw);
  1078. result.m[2] = 2.0 * (zx - yw);
  1079. result.m[3] = 0;
  1080. result.m[4] = 2.0 * (xy - zw);
  1081. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1082. result.m[6] = 2.0 * (yz + xw);
  1083. result.m[7] = 0;
  1084. result.m[8] = 2.0 * (zx + yw);
  1085. result.m[9] = 2.0 * (yz - xw);
  1086. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1087. result.m[11] = 0;
  1088. result.m[12] = 0;
  1089. result.m[13] = 0;
  1090. result.m[14] = 0;
  1091. result.m[15] = 1.0;
  1092. };
  1093. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1094. var data = matrix.m;
  1095. var m11 = data[0], m12 = data[4], m13 = data[8];
  1096. var m21 = data[1], m22 = data[5], m23 = data[9];
  1097. var m31 = data[2], m32 = data[6], m33 = data[10];
  1098. var trace = m11 + m22 + m33;
  1099. var s;
  1100. if (trace > 0) {
  1101. s = 0.5 / Math.sqrt(trace + 1.0);
  1102. this.w = 0.25 / s;
  1103. this.x = (m32 - m23) * s;
  1104. this.y = (m13 - m31) * s;
  1105. this.z = (m21 - m12) * s;
  1106. return;
  1107. }
  1108. if (m11 > m22 && m11 > m33) {
  1109. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1110. this.w = (m32 - m23) / s;
  1111. this.x = 0.25 * s;
  1112. this.y = (m12 + m21) / s;
  1113. this.z = (m13 + m31) / s;
  1114. return;
  1115. }
  1116. if (m22 > m33) {
  1117. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1118. this.w = (m13 - m31) / s;
  1119. this.x = (m12 + m21) / s;
  1120. this.y = 0.25 * s;
  1121. this.z = (m23 + m32) / s;
  1122. return;
  1123. }
  1124. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1125. this.w = (m21 - m12) / s;
  1126. this.x = (m13 + m31) / s;
  1127. this.y = (m23 + m32) / s;
  1128. this.z = 0.25 * s;
  1129. };
  1130. // Statics
  1131. Quaternion.Inverse = function (q) {
  1132. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1133. };
  1134. Quaternion.RotationAxis = function (axis, angle) {
  1135. var result = new Quaternion();
  1136. var sin = Math.sin(angle / 2);
  1137. result.w = Math.cos(angle / 2);
  1138. result.x = axis.x * sin;
  1139. result.y = axis.y * sin;
  1140. result.z = axis.z * sin;
  1141. return result;
  1142. };
  1143. Quaternion.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1150. var result = new Quaternion();
  1151. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1152. return result;
  1153. };
  1154. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1155. var halfRoll = roll * 0.5;
  1156. var halfPitch = pitch * 0.5;
  1157. var halfYaw = yaw * 0.5;
  1158. var sinRoll = Math.sin(halfRoll);
  1159. var cosRoll = Math.cos(halfRoll);
  1160. var sinPitch = Math.sin(halfPitch);
  1161. var cosPitch = Math.cos(halfPitch);
  1162. var sinYaw = Math.sin(halfYaw);
  1163. var cosYaw = Math.cos(halfYaw);
  1164. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1165. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1166. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1167. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1168. };
  1169. Quaternion.Slerp = function (left, right, amount) {
  1170. var num2;
  1171. var num3;
  1172. var num = amount;
  1173. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1174. var flag = false;
  1175. if (num4 < 0) {
  1176. flag = true;
  1177. num4 = -num4;
  1178. }
  1179. if (num4 > 0.999999) {
  1180. num3 = 1 - num;
  1181. num2 = flag ? -num : num;
  1182. } else {
  1183. var num5 = Math.acos(num4);
  1184. var num6 = (1.0 / Math.sin(num5));
  1185. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1186. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1187. }
  1188. 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));
  1189. };
  1190. return Quaternion;
  1191. })();
  1192. BABYLON.Quaternion = Quaternion;
  1193. var Matrix = (function () {
  1194. function Matrix() {
  1195. this.m = new Float32Array(16);
  1196. }
  1197. // Properties
  1198. Matrix.prototype.isIdentity = function () {
  1199. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1200. return false;
  1201. 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)
  1202. return false;
  1203. return true;
  1204. };
  1205. Matrix.prototype.determinant = function () {
  1206. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1207. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1208. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1209. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1210. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1211. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1212. 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))));
  1213. };
  1214. // Methods
  1215. Matrix.prototype.toArray = function () {
  1216. return this.m;
  1217. };
  1218. Matrix.prototype.asArray = function () {
  1219. return this.toArray();
  1220. };
  1221. Matrix.prototype.invert = function () {
  1222. this.invertToRef(this);
  1223. };
  1224. Matrix.prototype.invertToRef = function (other) {
  1225. var l1 = this.m[0];
  1226. var l2 = this.m[1];
  1227. var l3 = this.m[2];
  1228. var l4 = this.m[3];
  1229. var l5 = this.m[4];
  1230. var l6 = this.m[5];
  1231. var l7 = this.m[6];
  1232. var l8 = this.m[7];
  1233. var l9 = this.m[8];
  1234. var l10 = this.m[9];
  1235. var l11 = this.m[10];
  1236. var l12 = this.m[11];
  1237. var l13 = this.m[12];
  1238. var l14 = this.m[13];
  1239. var l15 = this.m[14];
  1240. var l16 = this.m[15];
  1241. var l17 = (l11 * l16) - (l12 * l15);
  1242. var l18 = (l10 * l16) - (l12 * l14);
  1243. var l19 = (l10 * l15) - (l11 * l14);
  1244. var l20 = (l9 * l16) - (l12 * l13);
  1245. var l21 = (l9 * l15) - (l11 * l13);
  1246. var l22 = (l9 * l14) - (l10 * l13);
  1247. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1248. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1249. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1250. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1251. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1252. var l28 = (l7 * l16) - (l8 * l15);
  1253. var l29 = (l6 * l16) - (l8 * l14);
  1254. var l30 = (l6 * l15) - (l7 * l14);
  1255. var l31 = (l5 * l16) - (l8 * l13);
  1256. var l32 = (l5 * l15) - (l7 * l13);
  1257. var l33 = (l5 * l14) - (l6 * l13);
  1258. var l34 = (l7 * l12) - (l8 * l11);
  1259. var l35 = (l6 * l12) - (l8 * l10);
  1260. var l36 = (l6 * l11) - (l7 * l10);
  1261. var l37 = (l5 * l12) - (l8 * l9);
  1262. var l38 = (l5 * l11) - (l7 * l9);
  1263. var l39 = (l5 * l10) - (l6 * l9);
  1264. other.m[0] = l23 * l27;
  1265. other.m[4] = l24 * l27;
  1266. other.m[8] = l25 * l27;
  1267. other.m[12] = l26 * l27;
  1268. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1269. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1270. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1271. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1272. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1273. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1274. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1275. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1276. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1277. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1278. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1279. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1280. };
  1281. Matrix.prototype.setTranslation = function (vector3) {
  1282. this.m[12] = vector3.x;
  1283. this.m[13] = vector3.y;
  1284. this.m[14] = vector3.z;
  1285. };
  1286. Matrix.prototype.multiply = function (other) {
  1287. var result = new Matrix();
  1288. this.multiplyToRef(other, result);
  1289. return result;
  1290. };
  1291. Matrix.prototype.copyFrom = function (other) {
  1292. for (var index = 0; index < 16; index++) {
  1293. this.m[index] = other.m[index];
  1294. }
  1295. };
  1296. Matrix.prototype.copyToArray = function (array, offset) {
  1297. if (typeof offset === "undefined") { offset = 0; }
  1298. for (var index = 0; index < 16; index++) {
  1299. array[offset + index] = this.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.multiplyToRef = function (other, result) {
  1303. this.multiplyToArray(other, result.m, 0);
  1304. };
  1305. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1306. var tm0 = this.m[0];
  1307. var tm1 = this.m[1];
  1308. var tm2 = this.m[2];
  1309. var tm3 = this.m[3];
  1310. var tm4 = this.m[4];
  1311. var tm5 = this.m[5];
  1312. var tm6 = this.m[6];
  1313. var tm7 = this.m[7];
  1314. var tm8 = this.m[8];
  1315. var tm9 = this.m[9];
  1316. var tm10 = this.m[10];
  1317. var tm11 = this.m[11];
  1318. var tm12 = this.m[12];
  1319. var tm13 = this.m[13];
  1320. var tm14 = this.m[14];
  1321. var tm15 = this.m[15];
  1322. var om0 = other.m[0];
  1323. var om1 = other.m[1];
  1324. var om2 = other.m[2];
  1325. var om3 = other.m[3];
  1326. var om4 = other.m[4];
  1327. var om5 = other.m[5];
  1328. var om6 = other.m[6];
  1329. var om7 = other.m[7];
  1330. var om8 = other.m[8];
  1331. var om9 = other.m[9];
  1332. var om10 = other.m[10];
  1333. var om11 = other.m[11];
  1334. var om12 = other.m[12];
  1335. var om13 = other.m[13];
  1336. var om14 = other.m[14];
  1337. var om15 = other.m[15];
  1338. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1339. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1340. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1341. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1342. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1343. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1344. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1345. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1346. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1347. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1348. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1349. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1350. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1351. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1352. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1353. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1354. };
  1355. Matrix.prototype.equals = function (value) {
  1356. 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]);
  1357. };
  1358. Matrix.prototype.clone = function () {
  1359. 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]);
  1360. };
  1361. // Statics
  1362. Matrix.FromArray = function (array, offset) {
  1363. var result = new Matrix();
  1364. if (!offset) {
  1365. offset = 0;
  1366. }
  1367. Matrix.FromArrayToRef(array, offset, result);
  1368. return result;
  1369. };
  1370. Matrix.FromArrayToRef = function (array, offset, result) {
  1371. for (var index = 0; index < 16; index++) {
  1372. result.m[index] = array[index + offset];
  1373. }
  1374. };
  1375. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1376. result.m[0] = initialM11;
  1377. result.m[1] = initialM12;
  1378. result.m[2] = initialM13;
  1379. result.m[3] = initialM14;
  1380. result.m[4] = initialM21;
  1381. result.m[5] = initialM22;
  1382. result.m[6] = initialM23;
  1383. result.m[7] = initialM24;
  1384. result.m[8] = initialM31;
  1385. result.m[9] = initialM32;
  1386. result.m[10] = initialM33;
  1387. result.m[11] = initialM34;
  1388. result.m[12] = initialM41;
  1389. result.m[13] = initialM42;
  1390. result.m[14] = initialM43;
  1391. result.m[15] = initialM44;
  1392. };
  1393. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1394. var result = new Matrix();
  1395. result.m[0] = initialM11;
  1396. result.m[1] = initialM12;
  1397. result.m[2] = initialM13;
  1398. result.m[3] = initialM14;
  1399. result.m[4] = initialM21;
  1400. result.m[5] = initialM22;
  1401. result.m[6] = initialM23;
  1402. result.m[7] = initialM24;
  1403. result.m[8] = initialM31;
  1404. result.m[9] = initialM32;
  1405. result.m[10] = initialM33;
  1406. result.m[11] = initialM34;
  1407. result.m[12] = initialM41;
  1408. result.m[13] = initialM42;
  1409. result.m[14] = initialM43;
  1410. result.m[15] = initialM44;
  1411. return result;
  1412. };
  1413. Matrix.Identity = function () {
  1414. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1415. };
  1416. Matrix.IdentityToRef = function (result) {
  1417. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1418. };
  1419. Matrix.Zero = function () {
  1420. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1421. };
  1422. Matrix.RotationX = function (angle) {
  1423. var result = new Matrix();
  1424. Matrix.RotationXToRef(angle, result);
  1425. return result;
  1426. };
  1427. Matrix.Invert = function (source) {
  1428. var result = new Matrix();
  1429. source.invertToRef(result);
  1430. return result;
  1431. };
  1432. Matrix.RotationXToRef = function (angle, result) {
  1433. var s = Math.sin(angle);
  1434. var c = Math.cos(angle);
  1435. result.m[0] = 1.0;
  1436. result.m[15] = 1.0;
  1437. result.m[5] = c;
  1438. result.m[10] = c;
  1439. result.m[9] = -s;
  1440. result.m[6] = s;
  1441. result.m[1] = 0;
  1442. result.m[2] = 0;
  1443. result.m[3] = 0;
  1444. result.m[4] = 0;
  1445. result.m[7] = 0;
  1446. result.m[8] = 0;
  1447. result.m[11] = 0;
  1448. result.m[12] = 0;
  1449. result.m[13] = 0;
  1450. result.m[14] = 0;
  1451. };
  1452. Matrix.RotationY = function (angle) {
  1453. var result = new Matrix();
  1454. Matrix.RotationYToRef(angle, result);
  1455. return result;
  1456. };
  1457. Matrix.RotationYToRef = function (angle, result) {
  1458. var s = Math.sin(angle);
  1459. var c = Math.cos(angle);
  1460. result.m[5] = 1.0;
  1461. result.m[15] = 1.0;
  1462. result.m[0] = c;
  1463. result.m[2] = -s;
  1464. result.m[8] = s;
  1465. result.m[10] = c;
  1466. result.m[1] = 0;
  1467. result.m[3] = 0;
  1468. result.m[4] = 0;
  1469. result.m[6] = 0;
  1470. result.m[7] = 0;
  1471. result.m[9] = 0;
  1472. result.m[11] = 0;
  1473. result.m[12] = 0;
  1474. result.m[13] = 0;
  1475. result.m[14] = 0;
  1476. };
  1477. Matrix.RotationZ = function (angle) {
  1478. var result = new Matrix();
  1479. Matrix.RotationZToRef(angle, result);
  1480. return result;
  1481. };
  1482. Matrix.RotationZToRef = function (angle, result) {
  1483. var s = Math.sin(angle);
  1484. var c = Math.cos(angle);
  1485. result.m[10] = 1.0;
  1486. result.m[15] = 1.0;
  1487. result.m[0] = c;
  1488. result.m[1] = s;
  1489. result.m[4] = -s;
  1490. result.m[5] = c;
  1491. result.m[2] = 0;
  1492. result.m[3] = 0;
  1493. result.m[6] = 0;
  1494. result.m[7] = 0;
  1495. result.m[8] = 0;
  1496. result.m[9] = 0;
  1497. result.m[11] = 0;
  1498. result.m[12] = 0;
  1499. result.m[13] = 0;
  1500. result.m[14] = 0;
  1501. };
  1502. Matrix.RotationAxis = function (axis, angle) {
  1503. var s = Math.sin(-angle);
  1504. var c = Math.cos(-angle);
  1505. var c1 = 1 - c;
  1506. axis.normalize();
  1507. var result = Matrix.Zero();
  1508. result.m[0] = (axis.x * axis.x) * c1 + c;
  1509. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1510. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1511. result.m[3] = 0.0;
  1512. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1513. result.m[5] = (axis.y * axis.y) * c1 + c;
  1514. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1515. result.m[7] = 0.0;
  1516. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1517. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1518. result.m[10] = (axis.z * axis.z) * c1 + c;
  1519. result.m[11] = 0.0;
  1520. result.m[15] = 1.0;
  1521. return result;
  1522. };
  1523. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1524. var result = new Matrix();
  1525. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1526. return result;
  1527. };
  1528. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1529. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1530. this._tempQuaternion.toRotationMatrix(result);
  1531. };
  1532. Matrix.Scaling = function (x, y, z) {
  1533. var result = Matrix.Zero();
  1534. Matrix.ScalingToRef(x, y, z, result);
  1535. return result;
  1536. };
  1537. Matrix.ScalingToRef = function (x, y, z, result) {
  1538. result.m[0] = x;
  1539. result.m[1] = 0;
  1540. result.m[2] = 0;
  1541. result.m[3] = 0;
  1542. result.m[4] = 0;
  1543. result.m[5] = y;
  1544. result.m[6] = 0;
  1545. result.m[7] = 0;
  1546. result.m[8] = 0;
  1547. result.m[9] = 0;
  1548. result.m[10] = z;
  1549. result.m[11] = 0;
  1550. result.m[12] = 0;
  1551. result.m[13] = 0;
  1552. result.m[14] = 0;
  1553. result.m[15] = 1.0;
  1554. };
  1555. Matrix.Translation = function (x, y, z) {
  1556. var result = Matrix.Identity();
  1557. Matrix.TranslationToRef(x, y, z, result);
  1558. return result;
  1559. };
  1560. Matrix.TranslationToRef = function (x, y, z, result) {
  1561. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1562. };
  1563. Matrix.LookAtLH = function (eye, target, up) {
  1564. var result = Matrix.Zero();
  1565. Matrix.LookAtLHToRef(eye, target, up, result);
  1566. return result;
  1567. };
  1568. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1569. // Z axis
  1570. target.subtractToRef(eye, this._zAxis);
  1571. this._zAxis.normalize();
  1572. // X axis
  1573. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1574. this._xAxis.normalize();
  1575. // Y axis
  1576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1577. this._yAxis.normalize();
  1578. // Eye angles
  1579. var ex = -Vector3.Dot(this._xAxis, eye);
  1580. var ey = -Vector3.Dot(this._yAxis, eye);
  1581. var ez = -Vector3.Dot(this._zAxis, eye);
  1582. 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);
  1583. };
  1584. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1585. var hw = 2.0 / width;
  1586. var hh = 2.0 / height;
  1587. var id = 1.0 / (zfar - znear);
  1588. var nid = znear / (znear - zfar);
  1589. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1590. };
  1591. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1592. var matrix = Matrix.Zero();
  1593. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1594. return matrix;
  1595. };
  1596. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1597. result.m[0] = 2.0 / (right - left);
  1598. result.m[1] = result.m[2] = result.m[3] = 0;
  1599. result.m[5] = 2.0 / (top - bottom);
  1600. result.m[4] = result.m[6] = result.m[7] = 0;
  1601. result.m[10] = -1.0 / (znear - zfar);
  1602. result.m[8] = result.m[9] = result.m[11] = 0;
  1603. result.m[12] = (left + right) / (left - right);
  1604. result.m[13] = (top + bottom) / (bottom - top);
  1605. result.m[14] = znear / (znear - zfar);
  1606. result.m[15] = 1.0;
  1607. };
  1608. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1609. var matrix = Matrix.Zero();
  1610. matrix.m[0] = (2.0 * znear) / width;
  1611. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1612. matrix.m[5] = (2.0 * znear) / height;
  1613. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1614. matrix.m[10] = -zfar / (znear - zfar);
  1615. matrix.m[8] = matrix.m[9] = 0.0;
  1616. matrix.m[11] = 1.0;
  1617. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1618. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1619. return matrix;
  1620. };
  1621. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1622. var matrix = Matrix.Zero();
  1623. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1624. return matrix;
  1625. };
  1626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1627. var tan = 1.0 / (Math.tan(fov * 0.5));
  1628. result.m[0] = tan / aspect;
  1629. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1630. result.m[5] = tan;
  1631. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1632. result.m[8] = result.m[9] = 0.0;
  1633. result.m[10] = -zfar / (znear - zfar);
  1634. result.m[11] = 1.0;
  1635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1636. result.m[14] = (znear * zfar) / (znear - zfar);
  1637. };
  1638. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1639. var cw = viewport.width;
  1640. var ch = viewport.height;
  1641. var cx = viewport.x;
  1642. var cy = viewport.y;
  1643. 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);
  1644. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1645. };
  1646. Matrix.Transpose = function (matrix) {
  1647. var result = new Matrix();
  1648. result.m[0] = matrix.m[0];
  1649. result.m[1] = matrix.m[4];
  1650. result.m[2] = matrix.m[8];
  1651. result.m[3] = matrix.m[12];
  1652. result.m[4] = matrix.m[1];
  1653. result.m[5] = matrix.m[5];
  1654. result.m[6] = matrix.m[9];
  1655. result.m[7] = matrix.m[13];
  1656. result.m[8] = matrix.m[2];
  1657. result.m[9] = matrix.m[6];
  1658. result.m[10] = matrix.m[10];
  1659. result.m[11] = matrix.m[14];
  1660. result.m[12] = matrix.m[3];
  1661. result.m[13] = matrix.m[7];
  1662. result.m[14] = matrix.m[11];
  1663. result.m[15] = matrix.m[15];
  1664. return result;
  1665. };
  1666. Matrix.Reflection = function (plane) {
  1667. var matrix = new Matrix();
  1668. Matrix.ReflectionToRef(plane, matrix);
  1669. return matrix;
  1670. };
  1671. Matrix.ReflectionToRef = function (plane, result) {
  1672. plane.normalize();
  1673. var x = plane.normal.x;
  1674. var y = plane.normal.y;
  1675. var z = plane.normal.z;
  1676. var temp = -2 * x;
  1677. var temp2 = -2 * y;
  1678. var temp3 = -2 * z;
  1679. result.m[0] = (temp * x) + 1;
  1680. result.m[1] = temp2 * x;
  1681. result.m[2] = temp3 * x;
  1682. result.m[3] = 0.0;
  1683. result.m[4] = temp * y;
  1684. result.m[5] = (temp2 * y) + 1;
  1685. result.m[6] = temp3 * y;
  1686. result.m[7] = 0.0;
  1687. result.m[8] = temp * z;
  1688. result.m[9] = temp2 * z;
  1689. result.m[10] = (temp3 * z) + 1;
  1690. result.m[11] = 0.0;
  1691. result.m[12] = temp * plane.d;
  1692. result.m[13] = temp2 * plane.d;
  1693. result.m[14] = temp3 * plane.d;
  1694. result.m[15] = 1.0;
  1695. };
  1696. Matrix._tempQuaternion = new Quaternion();
  1697. Matrix._xAxis = Vector3.Zero();
  1698. Matrix._yAxis = Vector3.Zero();
  1699. Matrix._zAxis = Vector3.Zero();
  1700. return Matrix;
  1701. })();
  1702. BABYLON.Matrix = Matrix;
  1703. var Plane = (function () {
  1704. function Plane(a, b, c, d) {
  1705. this.normal = new Vector3(a, b, c);
  1706. this.d = d;
  1707. }
  1708. Plane.prototype.asArray = function () {
  1709. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1710. };
  1711. // Methods
  1712. Plane.prototype.clone = function () {
  1713. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1714. };
  1715. Plane.prototype.normalize = function () {
  1716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1717. var magnitude = 0;
  1718. if (norm !== 0) {
  1719. magnitude = 1.0 / norm;
  1720. }
  1721. this.normal.x *= magnitude;
  1722. this.normal.y *= magnitude;
  1723. this.normal.z *= magnitude;
  1724. this.d *= magnitude;
  1725. };
  1726. Plane.prototype.transform = function (transformation) {
  1727. var transposedMatrix = Matrix.Transpose(transformation);
  1728. var x = this.normal.x;
  1729. var y = this.normal.y;
  1730. var z = this.normal.z;
  1731. var d = this.d;
  1732. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1733. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1734. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1735. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1736. return new Plane(normalX, normalY, normalZ, finalD);
  1737. };
  1738. Plane.prototype.dotCoordinate = function (point) {
  1739. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1740. };
  1741. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1742. var x1 = point2.x - point1.x;
  1743. var y1 = point2.y - point1.y;
  1744. var z1 = point2.z - point1.z;
  1745. var x2 = point3.x - point1.x;
  1746. var y2 = point3.y - point1.y;
  1747. var z2 = point3.z - point1.z;
  1748. var yz = (y1 * z2) - (z1 * y2);
  1749. var xz = (z1 * x2) - (x1 * z2);
  1750. var xy = (x1 * y2) - (y1 * x2);
  1751. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1752. var invPyth;
  1753. if (pyth !== 0) {
  1754. invPyth = 1.0 / pyth;
  1755. } else {
  1756. invPyth = 0;
  1757. }
  1758. this.normal.x = yz * invPyth;
  1759. this.normal.y = xz * invPyth;
  1760. this.normal.z = xy * invPyth;
  1761. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1762. };
  1763. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1764. var dot = Vector3.Dot(this.normal, direction);
  1765. return (dot <= epsilon);
  1766. };
  1767. Plane.prototype.signedDistanceTo = function (point) {
  1768. return Vector3.Dot(point, this.normal) + this.d;
  1769. };
  1770. // Statics
  1771. Plane.FromArray = function (array) {
  1772. return new Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new Plane(0, 0, 0, 0);
  1776. result.copyFromPoints(point1, point2, point3);
  1777. return result;
  1778. };
  1779. Plane.FromPositionAndNormal = function (origin, normal) {
  1780. var result = new Plane(0, 0, 0, 0);
  1781. normal.normalize();
  1782. result.normal = normal;
  1783. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1784. return result;
  1785. };
  1786. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1787. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1788. return Vector3.Dot(point, normal) + d;
  1789. };
  1790. return Plane;
  1791. })();
  1792. BABYLON.Plane = Plane;
  1793. var Viewport = (function () {
  1794. function Viewport(x, y, width, height) {
  1795. this.x = x;
  1796. this.y = y;
  1797. this.width = width;
  1798. this.height = height;
  1799. }
  1800. Viewport.prototype.toGlobal = function (engine) {
  1801. var width = engine.getRenderWidth();
  1802. var height = engine.getRenderHeight();
  1803. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1804. };
  1805. return Viewport;
  1806. })();
  1807. BABYLON.Viewport = Viewport;
  1808. var Frustum = (function () {
  1809. function Frustum() {
  1810. }
  1811. Frustum.GetPlanes = function (transform) {
  1812. var frustumPlanes = [];
  1813. for (var index = 0; index < 6; index++) {
  1814. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1815. }
  1816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1817. return frustumPlanes;
  1818. };
  1819. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1820. // Near
  1821. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1822. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1823. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1824. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1825. frustumPlanes[0].normalize();
  1826. // Far
  1827. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1828. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1829. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1830. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1831. frustumPlanes[1].normalize();
  1832. // Left
  1833. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1834. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1835. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1836. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1837. frustumPlanes[2].normalize();
  1838. // Right
  1839. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1840. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1841. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1842. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1843. frustumPlanes[3].normalize();
  1844. // Top
  1845. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1846. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1847. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1848. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1849. frustumPlanes[4].normalize();
  1850. // Bottom
  1851. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1852. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1853. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1854. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1855. frustumPlanes[5].normalize();
  1856. };
  1857. return Frustum;
  1858. })();
  1859. BABYLON.Frustum = Frustum;
  1860. var Ray = (function () {
  1861. function Ray(origin, direction, length) {
  1862. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1863. this.origin = origin;
  1864. this.direction = direction;
  1865. this.length = length;
  1866. }
  1867. // Methods
  1868. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1869. var d = 0.0;
  1870. var maxValue = Number.MAX_VALUE;
  1871. if (Math.abs(this.direction.x) < 0.0000001) {
  1872. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1873. return false;
  1874. }
  1875. } else {
  1876. var inv = 1.0 / this.direction.x;
  1877. var min = (minimum.x - this.origin.x) * inv;
  1878. var max = (maximum.x - this.origin.x) * inv;
  1879. if (max === -Infinity) {
  1880. max = Infinity;
  1881. }
  1882. if (min > max) {
  1883. var temp = min;
  1884. min = max;
  1885. max = temp;
  1886. }
  1887. d = Math.max(min, d);
  1888. maxValue = Math.min(max, maxValue);
  1889. if (d > maxValue) {
  1890. return false;
  1891. }
  1892. }
  1893. if (Math.abs(this.direction.y) < 0.0000001) {
  1894. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1895. return false;
  1896. }
  1897. } else {
  1898. inv = 1.0 / this.direction.y;
  1899. min = (minimum.y - this.origin.y) * inv;
  1900. max = (maximum.y - this.origin.y) * inv;
  1901. if (max === -Infinity) {
  1902. max = Infinity;
  1903. }
  1904. if (min > max) {
  1905. temp = min;
  1906. min = max;
  1907. max = temp;
  1908. }
  1909. d = Math.max(min, d);
  1910. maxValue = Math.min(max, maxValue);
  1911. if (d > maxValue) {
  1912. return false;
  1913. }
  1914. }
  1915. if (Math.abs(this.direction.z) < 0.0000001) {
  1916. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1917. return false;
  1918. }
  1919. } else {
  1920. inv = 1.0 / this.direction.z;
  1921. min = (minimum.z - this.origin.z) * inv;
  1922. max = (maximum.z - this.origin.z) * inv;
  1923. if (max === -Infinity) {
  1924. max = Infinity;
  1925. }
  1926. if (min > max) {
  1927. temp = min;
  1928. min = max;
  1929. max = temp;
  1930. }
  1931. d = Math.max(min, d);
  1932. maxValue = Math.min(max, maxValue);
  1933. if (d > maxValue) {
  1934. return false;
  1935. }
  1936. }
  1937. return true;
  1938. };
  1939. Ray.prototype.intersectsBox = function (box) {
  1940. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1941. };
  1942. Ray.prototype.intersectsSphere = function (sphere) {
  1943. var x = sphere.center.x - this.origin.x;
  1944. var y = sphere.center.y - this.origin.y;
  1945. var z = sphere.center.z - this.origin.z;
  1946. var pyth = (x * x) + (y * y) + (z * z);
  1947. var rr = sphere.radius * sphere.radius;
  1948. if (pyth <= rr) {
  1949. return true;
  1950. }
  1951. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1952. if (dot < 0.0) {
  1953. return false;
  1954. }
  1955. var temp = pyth - (dot * dot);
  1956. return temp <= rr;
  1957. };
  1958. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1959. if (!this._edge1) {
  1960. this._edge1 = Vector3.Zero();
  1961. this._edge2 = Vector3.Zero();
  1962. this._pvec = Vector3.Zero();
  1963. this._tvec = Vector3.Zero();
  1964. this._qvec = Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1969. var det = Vector3.Dot(this._edge1, this._pvec);
  1970. if (det === 0) {
  1971. return null;
  1972. }
  1973. var invdet = 1 / det;
  1974. this.origin.subtractToRef(vertex0, this._tvec);
  1975. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1976. if (bu < 0 || bu > 1.0) {
  1977. return null;
  1978. }
  1979. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1980. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1981. if (bv < 0 || bu + bv > 1.0) {
  1982. return null;
  1983. }
  1984. //check if the distance is longer than the predefined length.
  1985. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1986. if (distance > this.length) {
  1987. return null;
  1988. }
  1989. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1990. };
  1991. // Statics
  1992. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1993. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1995. var direction = end.subtract(start);
  1996. direction.normalize();
  1997. return new Ray(start, direction);
  1998. };
  1999. /**
  2000. * 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
  2001. * transformed to the given world matrix.
  2002. * @param origin The origin point
  2003. * @param end The end point
  2004. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2005. */
  2006. Ray.CreateNewFromTo = function (origin, end, world) {
  2007. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2008. var direction = end.subtract(origin);
  2009. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2010. direction.normalize();
  2011. return Ray.Transform(new Ray(origin, direction, length), world);
  2012. };
  2013. Ray.Transform = function (ray, matrix) {
  2014. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2016. return new Ray(newOrigin, newDirection, ray.length);
  2017. };
  2018. return Ray;
  2019. })();
  2020. BABYLON.Ray = Ray;
  2021. (function (Space) {
  2022. Space[Space["LOCAL"] = 0] = "LOCAL";
  2023. Space[Space["WORLD"] = 1] = "WORLD";
  2024. })(BABYLON.Space || (BABYLON.Space = {}));
  2025. var Space = BABYLON.Space;
  2026. var Axis = (function () {
  2027. function Axis() {
  2028. }
  2029. Axis.X = new Vector3(1, 0, 0);
  2030. Axis.Y = new Vector3(0, 1, 0);
  2031. Axis.Z = new Vector3(0, 0, 1);
  2032. return Axis;
  2033. })();
  2034. BABYLON.Axis = Axis;
  2035. ;
  2036. var BezierCurve = (function () {
  2037. function BezierCurve() {
  2038. }
  2039. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2040. // Extract X (which is equal to time here)
  2041. var f0 = 1 - 3 * x2 + 3 * x1;
  2042. var f1 = 3 * x2 - 6 * x1;
  2043. var f2 = 3 * x1;
  2044. var refinedT = t;
  2045. for (var i = 0; i < 5; i++) {
  2046. var refinedT2 = refinedT * refinedT;
  2047. var refinedT3 = refinedT2 * refinedT;
  2048. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2049. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2050. refinedT -= (x - t) * slope;
  2051. refinedT = Math.min(1, Math.max(0, refinedT));
  2052. }
  2053. // Resolve cubic bezier for the given x
  2054. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2055. };
  2056. return BezierCurve;
  2057. })();
  2058. BABYLON.BezierCurve = BezierCurve;
  2059. (function (Orientation) {
  2060. Orientation[Orientation["CW"] = 0] = "CW";
  2061. Orientation[Orientation["CCW"] = 1] = "CCW";
  2062. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2063. var Orientation = BABYLON.Orientation;
  2064. var Angle = (function () {
  2065. function Angle(radians) {
  2066. var _this = this;
  2067. this.degrees = function () {
  2068. return _this._radians * 180 / Math.PI;
  2069. };
  2070. this.radians = function () {
  2071. return _this._radians;
  2072. };
  2073. this._radians = radians;
  2074. if (this._radians < 0)
  2075. this._radians += (2 * Math.PI);
  2076. }
  2077. Angle.BetweenTwoPoints = function (a, b) {
  2078. var delta = b.subtract(a);
  2079. var theta = Math.atan2(delta.y, delta.x);
  2080. return new Angle(theta);
  2081. };
  2082. Angle.FromRadians = function (radians) {
  2083. return new Angle(radians);
  2084. };
  2085. Angle.FromDegrees = function (degrees) {
  2086. return new Angle(degrees * Math.PI / 180);
  2087. };
  2088. return Angle;
  2089. })();
  2090. BABYLON.Angle = Angle;
  2091. var Arc2 = (function () {
  2092. function Arc2(startPoint, midPoint, endPoint) {
  2093. this.startPoint = startPoint;
  2094. this.midPoint = midPoint;
  2095. this.endPoint = endPoint;
  2096. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2097. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2098. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2099. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2100. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2101. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2102. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2103. var a1 = this.startAngle.degrees();
  2104. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2105. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2106. // angles correction
  2107. if (a2 - a1 > +180.0)
  2108. a2 -= 360.0;
  2109. if (a2 - a1 < -180.0)
  2110. a2 += 360.0;
  2111. if (a3 - a2 > +180.0)
  2112. a3 -= 360.0;
  2113. if (a3 - a2 < -180.0)
  2114. a3 += 360.0;
  2115. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2116. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2117. }
  2118. return Arc2;
  2119. })();
  2120. BABYLON.Arc2 = Arc2;
  2121. var PathCursor = (function () {
  2122. function PathCursor(path) {
  2123. this.path = path;
  2124. this._onchange = new Array();
  2125. this.value = 0;
  2126. this.animations = new Array();
  2127. }
  2128. PathCursor.prototype.getPoint = function () {
  2129. var point = this.path.getPointAtLengthPosition(this.value);
  2130. return new Vector3(point.x, 0, point.y);
  2131. };
  2132. PathCursor.prototype.moveAhead = function (step) {
  2133. if (typeof step === "undefined") { step = 0.002; }
  2134. this.move(step);
  2135. };
  2136. PathCursor.prototype.moveBack = function (step) {
  2137. if (typeof step === "undefined") { step = 0.002; }
  2138. this.move(-step);
  2139. };
  2140. PathCursor.prototype.move = function (step) {
  2141. if (Math.abs(step) > 1) {
  2142. throw "step size should be less than 1.";
  2143. }
  2144. this.value += step;
  2145. this.ensureLimits();
  2146. this.raiseOnChange();
  2147. };
  2148. PathCursor.prototype.ensureLimits = function () {
  2149. while (this.value > 1) {
  2150. this.value -= 1;
  2151. }
  2152. while (this.value < 0) {
  2153. this.value += 1;
  2154. }
  2155. };
  2156. // used by animation engine
  2157. PathCursor.prototype.markAsDirty = function (propertyName) {
  2158. this.ensureLimits();
  2159. this.raiseOnChange();
  2160. };
  2161. PathCursor.prototype.raiseOnChange = function () {
  2162. var _this = this;
  2163. this._onchange.forEach(function (f) {
  2164. return f(_this);
  2165. });
  2166. };
  2167. PathCursor.prototype.onchange = function (f) {
  2168. this._onchange.push(f);
  2169. };
  2170. return PathCursor;
  2171. })();
  2172. BABYLON.PathCursor = PathCursor;
  2173. var Path2 = (function () {
  2174. function Path2(x, y) {
  2175. this._points = [];
  2176. this._length = 0;
  2177. this.closed = false;
  2178. this._points.push(new Vector2(x, y));
  2179. }
  2180. Path2.prototype.addLineTo = function (x, y) {
  2181. if (closed) {
  2182. BABYLON.Tools.Error("cannot add lines to closed paths");
  2183. return this;
  2184. }
  2185. var newPoint = new Vector2(x, y);
  2186. var previousPoint = this._points[this._points.length - 1];
  2187. this._points.push(newPoint);
  2188. this._length += newPoint.subtract(previousPoint).length();
  2189. return this;
  2190. };
  2191. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2192. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2193. if (closed) {
  2194. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2195. return this;
  2196. }
  2197. var startPoint = this._points[this._points.length - 1];
  2198. var midPoint = new Vector2(midX, midY);
  2199. var endPoint = new Vector2(endX, endY);
  2200. var arc = new Arc2(startPoint, midPoint, endPoint);
  2201. var increment = arc.angle.radians() / numberOfSegments;
  2202. if (arc.orientation === 0 /* CW */)
  2203. increment *= -1;
  2204. var currentAngle = arc.startAngle.radians() + increment;
  2205. for (var i = 0; i < numberOfSegments; i++) {
  2206. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2207. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2208. this.addLineTo(x, y);
  2209. currentAngle += increment;
  2210. }
  2211. return this;
  2212. };
  2213. Path2.prototype.close = function () {
  2214. this.closed = true;
  2215. return this;
  2216. };
  2217. Path2.prototype.length = function () {
  2218. var result = this._length;
  2219. if (!this.closed) {
  2220. var lastPoint = this._points[this._points.length - 1];
  2221. var firstPoint = this._points[0];
  2222. result += (firstPoint.subtract(lastPoint).length());
  2223. }
  2224. return result;
  2225. };
  2226. Path2.prototype.getPoints = function () {
  2227. return this._points;
  2228. };
  2229. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2230. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2231. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2232. return;
  2233. }
  2234. var lengthPosition = normalizedLengthPosition * this.length();
  2235. var previousOffset = 0;
  2236. for (var i = 0; i < this._points.length; i++) {
  2237. var j = (i + 1) % this._points.length;
  2238. var a = this._points[i];
  2239. var b = this._points[j];
  2240. var bToA = b.subtract(a);
  2241. var nextOffset = (bToA.length() + previousOffset);
  2242. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2243. var dir = bToA.normalize();
  2244. var localOffset = lengthPosition - previousOffset;
  2245. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2246. }
  2247. previousOffset = nextOffset;
  2248. }
  2249. BABYLON.Tools.Error("internal error");
  2250. };
  2251. Path2.StartingAt = function (x, y) {
  2252. return new Path2(x, y);
  2253. };
  2254. return Path2;
  2255. })();
  2256. BABYLON.Path2 = Path2;
  2257. })(BABYLON || (BABYLON = {}));
  2258. //# sourceMappingURL=babylon.math.js.map
  2259. var BABYLON;
  2260. (function (BABYLON) {
  2261. // Screenshots
  2262. var screenshotCanvas;
  2263. var cloneValue = function (source, destinationObject) {
  2264. if (!source)
  2265. return null;
  2266. if (source instanceof BABYLON.Mesh) {
  2267. return null;
  2268. }
  2269. if (source instanceof BABYLON.SubMesh) {
  2270. return source.clone(destinationObject);
  2271. } else if (source.clone) {
  2272. return source.clone();
  2273. }
  2274. return null;
  2275. };
  2276. var Tools = (function () {
  2277. function Tools() {
  2278. }
  2279. Tools.GetFilename = function (path) {
  2280. var index = path.lastIndexOf("/");
  2281. if (index < 0)
  2282. return path;
  2283. return path.substring(index + 1);
  2284. };
  2285. Tools.GetDOMTextContent = function (element) {
  2286. var result = "";
  2287. var child = element.firstChild;
  2288. while (child) {
  2289. if (child.nodeType == 3) {
  2290. result += child.textContent;
  2291. }
  2292. child = child.nextSibling;
  2293. }
  2294. return result;
  2295. };
  2296. Tools.ToDegrees = function (angle) {
  2297. return angle * 180 / Math.PI;
  2298. };
  2299. Tools.ToRadians = function (angle) {
  2300. return angle * Math.PI / 180;
  2301. };
  2302. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2303. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2304. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2305. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2306. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2307. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2308. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2309. }
  2310. return {
  2311. minimum: minimum,
  2312. maximum: maximum
  2313. };
  2314. };
  2315. Tools.ExtractMinAndMax = function (positions, start, count) {
  2316. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2317. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2318. for (var index = start; index < start + count; index++) {
  2319. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2320. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2321. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2322. }
  2323. return {
  2324. minimum: minimum,
  2325. maximum: maximum
  2326. };
  2327. };
  2328. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2329. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2330. return undefined;
  2331. return Array.isArray(obj) ? obj : [obj];
  2332. };
  2333. // Misc.
  2334. Tools.GetPointerPrefix = function () {
  2335. var eventPrefix = "pointer";
  2336. // Check if hand.js is referenced or if the browser natively supports pointer events
  2337. if (!navigator.pointerEnabled) {
  2338. eventPrefix = "mouse";
  2339. }
  2340. return eventPrefix;
  2341. };
  2342. Tools.QueueNewFrame = function (func) {
  2343. if (window.requestAnimationFrame)
  2344. window.requestAnimationFrame(func);
  2345. else if (window.msRequestAnimationFrame)
  2346. window.msRequestAnimationFrame(func);
  2347. else if (window.webkitRequestAnimationFrame)
  2348. window.webkitRequestAnimationFrame(func);
  2349. else if (window.mozRequestAnimationFrame)
  2350. window.mozRequestAnimationFrame(func);
  2351. else if (window.oRequestAnimationFrame)
  2352. window.oRequestAnimationFrame(func);
  2353. else {
  2354. window.setTimeout(func, 16);
  2355. }
  2356. };
  2357. Tools.RequestFullscreen = function (element) {
  2358. if (element.requestFullscreen)
  2359. element.requestFullscreen();
  2360. else if (element.msRequestFullscreen)
  2361. element.msRequestFullscreen();
  2362. else if (element.webkitRequestFullscreen)
  2363. element.webkitRequestFullscreen();
  2364. else if (element.mozRequestFullScreen)
  2365. element.mozRequestFullScreen();
  2366. };
  2367. Tools.ExitFullscreen = function () {
  2368. if (document.exitFullscreen) {
  2369. document.exitFullscreen();
  2370. } else if (document.mozCancelFullScreen) {
  2371. document.mozCancelFullScreen();
  2372. } else if (document.webkitCancelFullScreen) {
  2373. document.webkitCancelFullScreen();
  2374. } else if (document.msCancelFullScreen) {
  2375. document.msCancelFullScreen();
  2376. }
  2377. };
  2378. // External files
  2379. Tools.CleanUrl = function (url) {
  2380. url = url.replace(/#/mg, "%23");
  2381. return url;
  2382. };
  2383. Tools.LoadImage = function (url, onload, onerror, database) {
  2384. url = Tools.CleanUrl(url);
  2385. var img = new Image();
  2386. if (url.substr(0, 5) != "data:")
  2387. img.crossOrigin = 'anonymous';
  2388. img.onload = function () {
  2389. onload(img);
  2390. };
  2391. img.onerror = function (err) {
  2392. onerror(img, err);
  2393. };
  2394. var noIndexedDB = function () {
  2395. img.src = url;
  2396. };
  2397. var loadFromIndexedDB = function () {
  2398. database.loadImageFromDB(url, img);
  2399. };
  2400. //ANY database to do!
  2401. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2402. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2403. } else {
  2404. if (url.indexOf("file:") === -1) {
  2405. noIndexedDB();
  2406. } else {
  2407. try {
  2408. var textureName = url.substring(5);
  2409. var blobURL;
  2410. try {
  2411. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2412. } catch (ex) {
  2413. // Chrome doesn't support oneTimeOnly parameter
  2414. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2415. }
  2416. img.src = blobURL;
  2417. } catch (e) {
  2418. Tools.Log("Error while trying to load texture: " + textureName);
  2419. img.src = null;
  2420. }
  2421. }
  2422. }
  2423. return img;
  2424. };
  2425. //ANY
  2426. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2427. url = Tools.CleanUrl(url);
  2428. var noIndexedDB = function () {
  2429. var request = new XMLHttpRequest();
  2430. var loadUrl = Tools.BaseUrl + url;
  2431. request.open('GET', loadUrl, true);
  2432. if (useArrayBuffer) {
  2433. request.responseType = "arraybuffer";
  2434. }
  2435. request.onprogress = progressCallBack;
  2436. request.onreadystatechange = function () {
  2437. if (request.readyState == 4) {
  2438. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2439. callback(!useArrayBuffer ? request.responseText : request.response);
  2440. } else {
  2441. if (onError) {
  2442. onError();
  2443. } else {
  2444. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2445. }
  2446. }
  2447. }
  2448. };
  2449. request.send(null);
  2450. };
  2451. var loadFromIndexedDB = function () {
  2452. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2453. };
  2454. if (url.indexOf("file:") !== -1) {
  2455. var fileName = url.substring(5);
  2456. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2457. } else {
  2458. // Caching all files
  2459. if (database && database.enableSceneOffline) {
  2460. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2461. } else {
  2462. noIndexedDB();
  2463. }
  2464. }
  2465. };
  2466. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2467. var reader = new FileReader();
  2468. reader.onload = function (e) {
  2469. callback(e.target.result);
  2470. };
  2471. reader.onprogress = progressCallback;
  2472. reader.readAsDataURL(fileToLoad);
  2473. };
  2474. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2475. var reader = new FileReader();
  2476. reader.onload = function (e) {
  2477. callback(e.target.result);
  2478. };
  2479. reader.onprogress = progressCallBack;
  2480. if (!useArrayBuffer) {
  2481. // Asynchronous read
  2482. reader.readAsText(fileToLoad);
  2483. } else {
  2484. reader.readAsArrayBuffer(fileToLoad);
  2485. }
  2486. };
  2487. // Misc.
  2488. Tools.Clamp = function (value, min, max) {
  2489. if (typeof min === "undefined") { min = 0; }
  2490. if (typeof max === "undefined") { max = 1; }
  2491. return Math.min(max, Math.max(min, value));
  2492. };
  2493. Tools.Format = function (value, decimals) {
  2494. if (typeof decimals === "undefined") { decimals = 2; }
  2495. return value.toFixed(decimals);
  2496. };
  2497. Tools.CheckExtends = function (v, min, max) {
  2498. if (v.x < min.x)
  2499. min.x = v.x;
  2500. if (v.y < min.y)
  2501. min.y = v.y;
  2502. if (v.z < min.z)
  2503. min.z = v.z;
  2504. if (v.x > max.x)
  2505. max.x = v.x;
  2506. if (v.y > max.y)
  2507. max.y = v.y;
  2508. if (v.z > max.z)
  2509. max.z = v.z;
  2510. };
  2511. Tools.WithinEpsilon = function (a, b, epsilon) {
  2512. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2513. var num = a - b;
  2514. return -epsilon <= num && num <= epsilon;
  2515. };
  2516. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2517. for (var prop in source) {
  2518. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2519. continue;
  2520. }
  2521. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2522. continue;
  2523. }
  2524. var sourceValue = source[prop];
  2525. var typeOfSourceValue = typeof sourceValue;
  2526. if (typeOfSourceValue == "function") {
  2527. continue;
  2528. }
  2529. if (typeOfSourceValue == "object") {
  2530. if (sourceValue instanceof Array) {
  2531. destination[prop] = [];
  2532. if (sourceValue.length > 0) {
  2533. if (typeof sourceValue[0] == "object") {
  2534. for (var index = 0; index < sourceValue.length; index++) {
  2535. var clonedValue = cloneValue(sourceValue[index], destination);
  2536. if (destination[prop].indexOf(clonedValue) === -1) {
  2537. destination[prop].push(clonedValue);
  2538. }
  2539. }
  2540. } else {
  2541. destination[prop] = sourceValue.slice(0);
  2542. }
  2543. }
  2544. } else {
  2545. destination[prop] = cloneValue(sourceValue, destination);
  2546. }
  2547. } else {
  2548. destination[prop] = sourceValue;
  2549. }
  2550. }
  2551. };
  2552. Tools.IsEmpty = function (obj) {
  2553. for (var i in obj) {
  2554. return false;
  2555. }
  2556. return true;
  2557. };
  2558. Tools.RegisterTopRootEvents = function (events) {
  2559. for (var index = 0; index < events.length; index++) {
  2560. var event = events[index];
  2561. window.addEventListener(event.name, event.handler, false);
  2562. try {
  2563. if (window.parent) {
  2564. window.parent.addEventListener(event.name, event.handler, false);
  2565. }
  2566. } catch (e) {
  2567. // Silently fails...
  2568. }
  2569. }
  2570. };
  2571. Tools.UnregisterTopRootEvents = function (events) {
  2572. for (var index = 0; index < events.length; index++) {
  2573. var event = events[index];
  2574. window.removeEventListener(event.name, event.handler);
  2575. try {
  2576. if (window.parent) {
  2577. window.parent.removeEventListener(event.name, event.handler);
  2578. }
  2579. } catch (e) {
  2580. // Silently fails...
  2581. }
  2582. }
  2583. };
  2584. Tools.CreateScreenshot = function (engine, camera, size) {
  2585. var width;
  2586. var height;
  2587. var scene = camera.getScene();
  2588. var previousCamera = null;
  2589. if (scene.activeCamera !== camera) {
  2590. previousCamera = scene.activeCamera;
  2591. scene.activeCamera = camera;
  2592. }
  2593. //If a precision value is specified
  2594. if (size.precision) {
  2595. width = Math.round(engine.getRenderWidth() * size.precision);
  2596. height = Math.round(width / engine.getAspectRatio(camera));
  2597. size = { width: width, height: height };
  2598. } else if (size.width && size.height) {
  2599. width = size.width;
  2600. height = size.height;
  2601. } else if (size.width && !size.height) {
  2602. width = size.width;
  2603. height = Math.round(width / engine.getAspectRatio(camera));
  2604. size = { width: width, height: height };
  2605. } else if (size.height && !size.width) {
  2606. height = size.height;
  2607. width = Math.round(height * engine.getAspectRatio(camera));
  2608. size = { width: width, height: height };
  2609. } else if (!isNaN(size)) {
  2610. height = size;
  2611. width = size;
  2612. } else {
  2613. Tools.Error("Invalid 'size' parameter !");
  2614. return;
  2615. }
  2616. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2617. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2618. texture.renderList = engine.scenes[0].meshes;
  2619. texture.onAfterRender = function () {
  2620. // Read the contents of the framebuffer
  2621. var numberOfChannelsByLine = width * 4;
  2622. var halfHeight = height / 2;
  2623. //Reading datas from WebGL
  2624. var data = engine.readPixels(0, 0, width, height);
  2625. for (var i = 0; i < halfHeight; i++) {
  2626. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2627. var currentCell = j + i * numberOfChannelsByLine;
  2628. var targetLine = height - i - 1;
  2629. var targetCell = j + targetLine * numberOfChannelsByLine;
  2630. var temp = data[currentCell];
  2631. data[currentCell] = data[targetCell];
  2632. data[targetCell] = temp;
  2633. }
  2634. }
  2635. // Create a 2D canvas to store the result
  2636. if (!screenshotCanvas) {
  2637. screenshotCanvas = document.createElement('canvas');
  2638. }
  2639. screenshotCanvas.width = width;
  2640. screenshotCanvas.height = height;
  2641. var context = screenshotCanvas.getContext('2d');
  2642. // Copy the pixels to a 2D canvas
  2643. var imageData = context.createImageData(width, height);
  2644. imageData.data.set(data);
  2645. context.putImageData(imageData, 0, 0);
  2646. var base64Image = screenshotCanvas.toDataURL();
  2647. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2648. if (("download" in document.createElement("a"))) {
  2649. var a = window.document.createElement("a");
  2650. a.href = base64Image;
  2651. var date = new Date();
  2652. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2653. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2654. window.document.body.appendChild(a);
  2655. a.addEventListener("click", function () {
  2656. a.parentElement.removeChild(a);
  2657. });
  2658. a.click();
  2659. //Or opening a new tab with the image if it is not possible to automatically start download.
  2660. } else {
  2661. var newWindow = window.open("");
  2662. var img = newWindow.document.createElement("img");
  2663. img.src = base64Image;
  2664. newWindow.document.body.appendChild(img);
  2665. }
  2666. };
  2667. texture.render(true);
  2668. texture.dispose();
  2669. if (previousCamera) {
  2670. scene.activeCamera = previousCamera;
  2671. }
  2672. };
  2673. // XHR response validator for local file scenario
  2674. Tools.ValidateXHRData = function (xhr, dataType) {
  2675. if (typeof dataType === "undefined") { dataType = 7; }
  2676. try {
  2677. if (dataType & 1) {
  2678. if (xhr.responseText && xhr.responseText.length > 0) {
  2679. return true;
  2680. } else if (dataType === 1) {
  2681. return false;
  2682. }
  2683. }
  2684. if (dataType & 2) {
  2685. // Check header width and height since there is no "TGA" magic number
  2686. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2687. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2688. return true;
  2689. } else if (dataType === 2) {
  2690. return false;
  2691. }
  2692. }
  2693. if (dataType & 4) {
  2694. // Check for the "DDS" magic number
  2695. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2696. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2697. return true;
  2698. } else {
  2699. return false;
  2700. }
  2701. }
  2702. } catch (e) {
  2703. // Global protection
  2704. }
  2705. return false;
  2706. };
  2707. Object.defineProperty(Tools, "NoneLogLevel", {
  2708. get: function () {
  2709. return Tools._NoneLogLevel;
  2710. },
  2711. enumerable: true,
  2712. configurable: true
  2713. });
  2714. Object.defineProperty(Tools, "MessageLogLevel", {
  2715. get: function () {
  2716. return Tools._MessageLogLevel;
  2717. },
  2718. enumerable: true,
  2719. configurable: true
  2720. });
  2721. Object.defineProperty(Tools, "WarningLogLevel", {
  2722. get: function () {
  2723. return Tools._WarningLogLevel;
  2724. },
  2725. enumerable: true,
  2726. configurable: true
  2727. });
  2728. Object.defineProperty(Tools, "ErrorLogLevel", {
  2729. get: function () {
  2730. return Tools._ErrorLogLevel;
  2731. },
  2732. enumerable: true,
  2733. configurable: true
  2734. });
  2735. Object.defineProperty(Tools, "AllLogLevel", {
  2736. get: function () {
  2737. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2738. },
  2739. enumerable: true,
  2740. configurable: true
  2741. });
  2742. Tools._AddLogEntry = function (entry) {
  2743. Tools._LogCache = entry + Tools._LogCache;
  2744. if (Tools.OnNewCacheEntry) {
  2745. Tools.OnNewCacheEntry(entry);
  2746. }
  2747. };
  2748. Tools._FormatMessage = function (message) {
  2749. var padStr = function (i) {
  2750. return (i < 10) ? "0" + i : "" + i;
  2751. };
  2752. var date = new Date();
  2753. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2754. };
  2755. Tools._LogDisabled = function (message) {
  2756. // nothing to do
  2757. };
  2758. Tools._LogEnabled = function (message) {
  2759. var formattedMessage = Tools._FormatMessage(message);
  2760. console.log("BJS - " + formattedMessage);
  2761. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2762. Tools._AddLogEntry(entry);
  2763. };
  2764. Tools._WarnDisabled = function (message) {
  2765. // nothing to do
  2766. };
  2767. Tools._WarnEnabled = function (message) {
  2768. var formattedMessage = Tools._FormatMessage(message);
  2769. console.warn("BJS - " + formattedMessage);
  2770. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2771. Tools._AddLogEntry(entry);
  2772. };
  2773. Tools._ErrorDisabled = function (message) {
  2774. // nothing to do
  2775. };
  2776. Tools._ErrorEnabled = function (message) {
  2777. var formattedMessage = Tools._FormatMessage(message);
  2778. console.error("BJS - " + formattedMessage);
  2779. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2780. Tools._AddLogEntry(entry);
  2781. };
  2782. Object.defineProperty(Tools, "LogCache", {
  2783. get: function () {
  2784. return Tools._LogCache;
  2785. },
  2786. enumerable: true,
  2787. configurable: true
  2788. });
  2789. Object.defineProperty(Tools, "LogLevels", {
  2790. set: function (level) {
  2791. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2792. Tools.Log = Tools._LogEnabled;
  2793. } else {
  2794. Tools.Log = Tools._LogDisabled;
  2795. }
  2796. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2797. Tools.Warn = Tools._WarnEnabled;
  2798. } else {
  2799. Tools.Warn = Tools._WarnDisabled;
  2800. }
  2801. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2802. Tools.Error = Tools._ErrorEnabled;
  2803. } else {
  2804. Tools.Error = Tools._ErrorDisabled;
  2805. }
  2806. },
  2807. enumerable: true,
  2808. configurable: true
  2809. });
  2810. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2811. get: function () {
  2812. return Tools._PerformanceNoneLogLevel;
  2813. },
  2814. enumerable: true,
  2815. configurable: true
  2816. });
  2817. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2818. get: function () {
  2819. return Tools._PerformanceUserMarkLogLevel;
  2820. },
  2821. enumerable: true,
  2822. configurable: true
  2823. });
  2824. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2825. get: function () {
  2826. return Tools._PerformanceConsoleLogLevel;
  2827. },
  2828. enumerable: true,
  2829. configurable: true
  2830. });
  2831. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2832. set: function (level) {
  2833. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2834. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2835. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2836. return;
  2837. }
  2838. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2839. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2840. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2841. return;
  2842. }
  2843. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2844. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2845. },
  2846. enumerable: true,
  2847. configurable: true
  2848. });
  2849. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2850. };
  2851. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2852. };
  2853. Tools._StartUserMark = function (counterName, condition) {
  2854. if (typeof condition === "undefined") { condition = true; }
  2855. if (!condition || !Tools._performance.mark) {
  2856. return;
  2857. }
  2858. Tools._performance.mark(counterName + "-Begin");
  2859. };
  2860. Tools._EndUserMark = function (counterName, condition) {
  2861. if (typeof condition === "undefined") { condition = true; }
  2862. if (!condition || !Tools._performance.mark) {
  2863. return;
  2864. }
  2865. Tools._performance.mark(counterName + "-End");
  2866. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2867. };
  2868. Tools._StartPerformanceConsole = function (counterName, condition) {
  2869. if (typeof condition === "undefined") { condition = true; }
  2870. if (!condition) {
  2871. return;
  2872. }
  2873. Tools._StartUserMark(counterName, condition);
  2874. if (console.time) {
  2875. console.time(counterName);
  2876. }
  2877. };
  2878. Tools._EndPerformanceConsole = function (counterName, condition) {
  2879. if (typeof condition === "undefined") { condition = true; }
  2880. if (!condition) {
  2881. return;
  2882. }
  2883. Tools._EndUserMark(counterName, condition);
  2884. if (console.time) {
  2885. console.timeEnd(counterName);
  2886. }
  2887. };
  2888. Object.defineProperty(Tools, "Now", {
  2889. get: function () {
  2890. if (window.performance && window.performance.now) {
  2891. return window.performance.now();
  2892. }
  2893. return new Date().getTime();
  2894. },
  2895. enumerable: true,
  2896. configurable: true
  2897. });
  2898. // Deprecated
  2899. Tools.GetFps = function () {
  2900. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2901. return 0;
  2902. };
  2903. Tools.BaseUrl = "";
  2904. Tools.GetExponantOfTwo = function (value, max) {
  2905. var count = 1;
  2906. do {
  2907. count *= 2;
  2908. } while(count < value);
  2909. if (count > max)
  2910. count = max;
  2911. return count;
  2912. };
  2913. Tools._NoneLogLevel = 0;
  2914. Tools._MessageLogLevel = 1;
  2915. Tools._WarningLogLevel = 2;
  2916. Tools._ErrorLogLevel = 4;
  2917. Tools._LogCache = "";
  2918. Tools.Log = Tools._LogEnabled;
  2919. Tools.Warn = Tools._WarnEnabled;
  2920. Tools.Error = Tools._ErrorEnabled;
  2921. Tools._PerformanceNoneLogLevel = 0;
  2922. Tools._PerformanceUserMarkLogLevel = 1;
  2923. Tools._PerformanceConsoleLogLevel = 2;
  2924. Tools._performance = window.performance;
  2925. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2926. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2927. return Tools;
  2928. })();
  2929. BABYLON.Tools = Tools;
  2930. })(BABYLON || (BABYLON = {}));
  2931. //# sourceMappingURL=babylon.tools.js.map
  2932. var BABYLON;
  2933. (function (BABYLON) {
  2934. var _DepthCullingState = (function () {
  2935. function _DepthCullingState() {
  2936. this._isDepthTestDirty = false;
  2937. this._isDepthMaskDirty = false;
  2938. this._isDepthFuncDirty = false;
  2939. this._isCullFaceDirty = false;
  2940. this._isCullDirty = false;
  2941. }
  2942. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2943. get: function () {
  2944. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2945. },
  2946. enumerable: true,
  2947. configurable: true
  2948. });
  2949. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2950. get: function () {
  2951. return this._cullFace;
  2952. },
  2953. set: function (value) {
  2954. if (this._cullFace === value) {
  2955. return;
  2956. }
  2957. this._cullFace = value;
  2958. this._isCullFaceDirty = true;
  2959. },
  2960. enumerable: true,
  2961. configurable: true
  2962. });
  2963. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2964. get: function () {
  2965. return this._cull;
  2966. },
  2967. set: function (value) {
  2968. if (this._cull === value) {
  2969. return;
  2970. }
  2971. this._cull = value;
  2972. this._isCullDirty = true;
  2973. },
  2974. enumerable: true,
  2975. configurable: true
  2976. });
  2977. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2978. get: function () {
  2979. return this._depthFunc;
  2980. },
  2981. set: function (value) {
  2982. if (this._depthFunc === value) {
  2983. return;
  2984. }
  2985. this._depthFunc = value;
  2986. this._isDepthFuncDirty = true;
  2987. },
  2988. enumerable: true,
  2989. configurable: true
  2990. });
  2991. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2992. get: function () {
  2993. return this._depthMask;
  2994. },
  2995. set: function (value) {
  2996. if (this._depthMask === value) {
  2997. return;
  2998. }
  2999. this._depthMask = value;
  3000. this._isDepthMaskDirty = true;
  3001. },
  3002. enumerable: true,
  3003. configurable: true
  3004. });
  3005. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3006. get: function () {
  3007. return this._depthTest;
  3008. },
  3009. set: function (value) {
  3010. if (this._depthTest === value) {
  3011. return;
  3012. }
  3013. this._depthTest = value;
  3014. this._isDepthTestDirty = true;
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. _DepthCullingState.prototype.reset = function () {
  3020. this._depthMask = true;
  3021. this._depthTest = true;
  3022. this._depthFunc = null;
  3023. this._cull = null;
  3024. this._cullFace = null;
  3025. this._isDepthTestDirty = true;
  3026. this._isDepthMaskDirty = true;
  3027. this._isDepthFuncDirty = false;
  3028. this._isCullFaceDirty = false;
  3029. this._isCullDirty = false;
  3030. };
  3031. _DepthCullingState.prototype.apply = function (gl) {
  3032. if (!this.isDirty) {
  3033. return;
  3034. }
  3035. // Cull
  3036. if (this._isCullDirty) {
  3037. if (this.cull === true) {
  3038. gl.enable(gl.CULL_FACE);
  3039. } else if (this.cull === false) {
  3040. gl.disable(gl.CULL_FACE);
  3041. }
  3042. this._isCullDirty = false;
  3043. }
  3044. // Cull face
  3045. if (this._isCullFaceDirty) {
  3046. gl.cullFace(this.cullFace);
  3047. this._isCullFaceDirty = false;
  3048. }
  3049. // Depth mask
  3050. if (this._isDepthMaskDirty) {
  3051. gl.depthMask(this.depthMask);
  3052. this._isDepthMaskDirty = false;
  3053. }
  3054. // Depth test
  3055. if (this._isDepthTestDirty) {
  3056. if (this.depthTest === true) {
  3057. gl.enable(gl.DEPTH_TEST);
  3058. } else if (this.depthTest === false) {
  3059. gl.disable(gl.DEPTH_TEST);
  3060. }
  3061. this._isDepthTestDirty = false;
  3062. }
  3063. // Depth func
  3064. if (this._isDepthFuncDirty) {
  3065. gl.depthFunc(this.depthFunc);
  3066. this._isDepthFuncDirty = false;
  3067. }
  3068. };
  3069. return _DepthCullingState;
  3070. })();
  3071. BABYLON._DepthCullingState = _DepthCullingState;
  3072. var _AlphaState = (function () {
  3073. function _AlphaState() {
  3074. this._isAlphaBlendDirty = false;
  3075. this._isBlendFunctionParametersDirty = false;
  3076. this._alphaBlend = false;
  3077. this._blendFunctionParameters = new Array(4);
  3078. }
  3079. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3080. get: function () {
  3081. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3082. },
  3083. enumerable: true,
  3084. configurable: true
  3085. });
  3086. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3087. get: function () {
  3088. return this._alphaBlend;
  3089. },
  3090. set: function (value) {
  3091. if (this._alphaBlend === value) {
  3092. return;
  3093. }
  3094. this._alphaBlend = value;
  3095. this._isAlphaBlendDirty = true;
  3096. },
  3097. enumerable: true,
  3098. configurable: true
  3099. });
  3100. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3101. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3102. return;
  3103. }
  3104. this._blendFunctionParameters[0] = value0;
  3105. this._blendFunctionParameters[1] = value1;
  3106. this._blendFunctionParameters[2] = value2;
  3107. this._blendFunctionParameters[3] = value3;
  3108. this._isBlendFunctionParametersDirty = true;
  3109. };
  3110. _AlphaState.prototype.reset = function () {
  3111. this._alphaBlend = false;
  3112. this._blendFunctionParameters[0] = null;
  3113. this._blendFunctionParameters[1] = null;
  3114. this._blendFunctionParameters[2] = null;
  3115. this._blendFunctionParameters[3] = null;
  3116. this._isAlphaBlendDirty = true;
  3117. this._isBlendFunctionParametersDirty = false;
  3118. };
  3119. _AlphaState.prototype.apply = function (gl) {
  3120. if (!this.isDirty) {
  3121. return;
  3122. }
  3123. // Alpha blend
  3124. if (this._isAlphaBlendDirty) {
  3125. if (this._alphaBlend === true) {
  3126. gl.enable(gl.BLEND);
  3127. } else if (this._alphaBlend === false) {
  3128. gl.disable(gl.BLEND);
  3129. }
  3130. this._isAlphaBlendDirty = false;
  3131. }
  3132. // Alpha function
  3133. if (this._isBlendFunctionParametersDirty) {
  3134. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3135. this._isBlendFunctionParametersDirty = false;
  3136. }
  3137. };
  3138. return _AlphaState;
  3139. })();
  3140. BABYLON._AlphaState = _AlphaState;
  3141. var compileShader = function (gl, source, type, defines) {
  3142. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3143. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3144. gl.compileShader(shader);
  3145. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3146. throw new Error(gl.getShaderInfoLog(shader));
  3147. }
  3148. return shader;
  3149. };
  3150. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3151. var magFilter = gl.NEAREST;
  3152. var minFilter = gl.NEAREST;
  3153. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3154. magFilter = gl.LINEAR;
  3155. if (generateMipMaps) {
  3156. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3157. } else {
  3158. minFilter = gl.LINEAR;
  3159. }
  3160. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3161. magFilter = gl.LINEAR;
  3162. if (generateMipMaps) {
  3163. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3164. } else {
  3165. minFilter = gl.LINEAR;
  3166. }
  3167. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3168. magFilter = gl.NEAREST;
  3169. if (generateMipMaps) {
  3170. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3171. } else {
  3172. minFilter = gl.NEAREST;
  3173. }
  3174. }
  3175. return {
  3176. min: minFilter,
  3177. mag: magFilter
  3178. };
  3179. };
  3180. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3181. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3182. var engine = scene.getEngine();
  3183. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3184. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3185. gl.bindTexture(gl.TEXTURE_2D, texture);
  3186. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3187. processFunction(potWidth, potHeight);
  3188. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3191. if (!noMipmap && !isCompressed) {
  3192. gl.generateMipmap(gl.TEXTURE_2D);
  3193. }
  3194. gl.bindTexture(gl.TEXTURE_2D, null);
  3195. engine._activeTexturesCache = [];
  3196. texture._baseWidth = width;
  3197. texture._baseHeight = height;
  3198. texture._width = potWidth;
  3199. texture._height = potHeight;
  3200. texture.isReady = true;
  3201. texture.samplingMode = samplingMode;
  3202. scene._removePendingData(texture);
  3203. };
  3204. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3205. var img;
  3206. var onload = function () {
  3207. loadedImages[index] = img;
  3208. loadedImages._internalCount++;
  3209. scene._removePendingData(img);
  3210. if (loadedImages._internalCount == 6) {
  3211. onfinish(loadedImages);
  3212. }
  3213. };
  3214. var onerror = function () {
  3215. scene._removePendingData(img);
  3216. };
  3217. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3218. scene._addPendingData(img);
  3219. };
  3220. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3221. var loadedImages = [];
  3222. loadedImages._internalCount = 0;
  3223. for (var index = 0; index < 6; index++) {
  3224. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3225. }
  3226. };
  3227. var EngineCapabilities = (function () {
  3228. function EngineCapabilities() {
  3229. }
  3230. return EngineCapabilities;
  3231. })();
  3232. BABYLON.EngineCapabilities = EngineCapabilities;
  3233. var Engine = (function () {
  3234. function Engine(canvas, antialias, options) {
  3235. var _this = this;
  3236. // Public members
  3237. this.isFullscreen = false;
  3238. this.isPointerLock = false;
  3239. this.cullBackFaces = true;
  3240. this.renderEvenInBackground = true;
  3241. this.scenes = new Array();
  3242. this._windowIsBackground = false;
  3243. this._loadingDivBackgroundColor = "black";
  3244. this._drawCalls = 0;
  3245. this._renderingQueueLaunched = false;
  3246. this._activeRenderLoops = [];
  3247. // FPS
  3248. this.fpsRange = 60;
  3249. this.previousFramesDuration = [];
  3250. this.fps = 60;
  3251. this.deltaTime = 0;
  3252. // States
  3253. this._depthCullingState = new _DepthCullingState();
  3254. this._alphaState = new _AlphaState();
  3255. this._alphaMode = Engine.ALPHA_DISABLE;
  3256. // Cache
  3257. this._loadedTexturesCache = new Array();
  3258. this._activeTexturesCache = new Array();
  3259. this._compiledEffects = {};
  3260. this._uintIndicesCurrentlySet = false;
  3261. this._renderingCanvas = canvas;
  3262. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3263. options = options || {};
  3264. options.antialias = antialias;
  3265. try {
  3266. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3267. } catch (e) {
  3268. throw new Error("WebGL not supported");
  3269. }
  3270. if (!this._gl) {
  3271. throw new Error("WebGL not supported");
  3272. }
  3273. this._onBlur = function () {
  3274. _this._windowIsBackground = true;
  3275. };
  3276. this._onFocus = function () {
  3277. _this._windowIsBackground = false;
  3278. };
  3279. window.addEventListener("blur", this._onBlur);
  3280. window.addEventListener("focus", this._onFocus);
  3281. // Textures
  3282. this._workingCanvas = document.createElement("canvas");
  3283. this._workingContext = this._workingCanvas.getContext("2d");
  3284. // Viewport
  3285. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3286. this.resize();
  3287. // Caps
  3288. this._caps = new EngineCapabilities();
  3289. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3290. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3291. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3292. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3293. // Extensions
  3294. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3295. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3296. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3297. 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');
  3298. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3299. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3300. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3301. // Depth buffer
  3302. this.setDepthBuffer(true);
  3303. this.setDepthFunctionToLessOrEqual();
  3304. this.setDepthWrite(true);
  3305. // Fullscreen
  3306. this._onFullscreenChange = function () {
  3307. if (document.fullscreen !== undefined) {
  3308. _this.isFullscreen = document.fullscreen;
  3309. } else if (document.mozFullScreen !== undefined) {
  3310. _this.isFullscreen = document.mozFullScreen;
  3311. } else if (document.webkitIsFullScreen !== undefined) {
  3312. _this.isFullscreen = document.webkitIsFullScreen;
  3313. } else if (document.msIsFullScreen !== undefined) {
  3314. _this.isFullscreen = document.msIsFullScreen;
  3315. }
  3316. // Pointer lock
  3317. if (_this.isFullscreen && _this._pointerLockRequested) {
  3318. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3319. if (canvas.requestPointerLock) {
  3320. canvas.requestPointerLock();
  3321. }
  3322. }
  3323. };
  3324. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3325. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3326. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3327. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3328. // Pointer lock
  3329. this._onPointerLockChange = function () {
  3330. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3331. };
  3332. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3333. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3334. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3335. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3336. this._audioEngine = new BABYLON.AudioEngine();
  3337. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3338. }
  3339. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3340. get: function () {
  3341. return Engine._ALPHA_DISABLE;
  3342. },
  3343. enumerable: true,
  3344. configurable: true
  3345. });
  3346. Object.defineProperty(Engine, "ALPHA_ADD", {
  3347. get: function () {
  3348. return Engine._ALPHA_ADD;
  3349. },
  3350. enumerable: true,
  3351. configurable: true
  3352. });
  3353. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3354. get: function () {
  3355. return Engine._ALPHA_COMBINE;
  3356. },
  3357. enumerable: true,
  3358. configurable: true
  3359. });
  3360. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3361. get: function () {
  3362. return Engine._DELAYLOADSTATE_NONE;
  3363. },
  3364. enumerable: true,
  3365. configurable: true
  3366. });
  3367. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3368. get: function () {
  3369. return Engine._DELAYLOADSTATE_LOADED;
  3370. },
  3371. enumerable: true,
  3372. configurable: true
  3373. });
  3374. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3375. get: function () {
  3376. return Engine._DELAYLOADSTATE_LOADING;
  3377. },
  3378. enumerable: true,
  3379. configurable: true
  3380. });
  3381. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3382. get: function () {
  3383. return Engine._DELAYLOADSTATE_NOTLOADED;
  3384. },
  3385. enumerable: true,
  3386. configurable: true
  3387. });
  3388. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3389. get: function () {
  3390. return Engine._TEXTUREFORMAT_ALPHA;
  3391. },
  3392. enumerable: true,
  3393. configurable: true
  3394. });
  3395. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3396. get: function () {
  3397. return Engine._TEXTUREFORMAT_LUMINANCE;
  3398. },
  3399. enumerable: true,
  3400. configurable: true
  3401. });
  3402. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3403. get: function () {
  3404. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3405. },
  3406. enumerable: true,
  3407. configurable: true
  3408. });
  3409. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3410. get: function () {
  3411. return Engine._TEXTUREFORMAT_RGB;
  3412. },
  3413. enumerable: true,
  3414. configurable: true
  3415. });
  3416. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3417. get: function () {
  3418. return Engine._TEXTUREFORMAT_RGBA;
  3419. },
  3420. enumerable: true,
  3421. configurable: true
  3422. });
  3423. Object.defineProperty(Engine, "Version", {
  3424. get: function () {
  3425. return "2.0.0";
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. Engine.prototype.getAudioEngine = function () {
  3431. return this._audioEngine;
  3432. };
  3433. Engine.prototype.getAspectRatio = function (camera) {
  3434. var viewport = camera.viewport;
  3435. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3436. };
  3437. Engine.prototype.getRenderWidth = function () {
  3438. if (this._currentRenderTarget) {
  3439. return this._currentRenderTarget._width;
  3440. }
  3441. return this._renderingCanvas.width;
  3442. };
  3443. Engine.prototype.getRenderHeight = function () {
  3444. if (this._currentRenderTarget) {
  3445. return this._currentRenderTarget._height;
  3446. }
  3447. return this._renderingCanvas.height;
  3448. };
  3449. Engine.prototype.getRenderingCanvas = function () {
  3450. return this._renderingCanvas;
  3451. };
  3452. Engine.prototype.getRenderingCanvasClientRect = function () {
  3453. return this._renderingCanvas.getBoundingClientRect();
  3454. };
  3455. Engine.prototype.setHardwareScalingLevel = function (level) {
  3456. this._hardwareScalingLevel = level;
  3457. this.resize();
  3458. };
  3459. Engine.prototype.getHardwareScalingLevel = function () {
  3460. return this._hardwareScalingLevel;
  3461. };
  3462. Engine.prototype.getLoadedTexturesCache = function () {
  3463. return this._loadedTexturesCache;
  3464. };
  3465. Engine.prototype.getCaps = function () {
  3466. return this._caps;
  3467. };
  3468. Object.defineProperty(Engine.prototype, "drawCalls", {
  3469. get: function () {
  3470. return this._drawCalls;
  3471. },
  3472. enumerable: true,
  3473. configurable: true
  3474. });
  3475. // Methods
  3476. Engine.prototype.resetDrawCalls = function () {
  3477. this._drawCalls = 0;
  3478. };
  3479. Engine.prototype.setDepthFunctionToGreater = function () {
  3480. this._depthCullingState.depthFunc = this._gl.GREATER;
  3481. };
  3482. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3483. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3484. };
  3485. Engine.prototype.setDepthFunctionToLess = function () {
  3486. this._depthCullingState.depthFunc = this._gl.LESS;
  3487. };
  3488. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3489. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3490. };
  3491. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3492. if (!renderFunction) {
  3493. this._activeRenderLoops = [];
  3494. return;
  3495. }
  3496. var index = this._activeRenderLoops.indexOf(renderFunction);
  3497. if (index >= 0) {
  3498. this._activeRenderLoops.splice(index, 1);
  3499. }
  3500. };
  3501. Engine.prototype._renderLoop = function () {
  3502. var _this = this;
  3503. var shouldRender = true;
  3504. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3505. shouldRender = false;
  3506. }
  3507. if (shouldRender) {
  3508. // Start new frame
  3509. this.beginFrame();
  3510. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3511. var renderFunction = this._activeRenderLoops[index];
  3512. renderFunction();
  3513. }
  3514. // Present
  3515. this.endFrame();
  3516. }
  3517. if (this._activeRenderLoops.length > 0) {
  3518. // Register new frame
  3519. BABYLON.Tools.QueueNewFrame(function () {
  3520. _this._renderLoop();
  3521. });
  3522. } else {
  3523. this._renderingQueueLaunched = false;
  3524. }
  3525. };
  3526. Engine.prototype.runRenderLoop = function (renderFunction) {
  3527. var _this = this;
  3528. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3529. return;
  3530. }
  3531. this._activeRenderLoops.push(renderFunction);
  3532. if (!this._renderingQueueLaunched) {
  3533. this._renderingQueueLaunched = true;
  3534. BABYLON.Tools.QueueNewFrame(function () {
  3535. _this._renderLoop();
  3536. });
  3537. }
  3538. };
  3539. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3540. if (this.isFullscreen) {
  3541. BABYLON.Tools.ExitFullscreen();
  3542. } else {
  3543. this._pointerLockRequested = requestPointerLock;
  3544. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3545. }
  3546. };
  3547. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3548. this.applyStates();
  3549. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3550. if (this._depthCullingState.depthMask) {
  3551. this._gl.clearDepth(1.0);
  3552. }
  3553. var mode = 0;
  3554. if (backBuffer)
  3555. mode |= this._gl.COLOR_BUFFER_BIT;
  3556. if (depthStencil && this._depthCullingState.depthMask)
  3557. mode |= this._gl.DEPTH_BUFFER_BIT;
  3558. this._gl.clear(mode);
  3559. };
  3560. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3561. var width = requiredWidth || this._renderingCanvas.width;
  3562. var height = requiredHeight || this._renderingCanvas.height;
  3563. var x = viewport.x || 0;
  3564. var y = viewport.y || 0;
  3565. this._cachedViewport = viewport;
  3566. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3567. };
  3568. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3569. this._cachedViewport = null;
  3570. this._gl.viewport(x, y, width, height);
  3571. };
  3572. Engine.prototype.beginFrame = function () {
  3573. this._measureFps();
  3574. };
  3575. Engine.prototype.endFrame = function () {
  3576. this.flushFramebuffer();
  3577. };
  3578. Engine.prototype.resize = function () {
  3579. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3580. };
  3581. Engine.prototype.setSize = function (width, height) {
  3582. this._renderingCanvas.width = width;
  3583. this._renderingCanvas.height = height;
  3584. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3585. };
  3586. Engine.prototype.bindFramebuffer = function (texture) {
  3587. this._currentRenderTarget = texture;
  3588. var gl = this._gl;
  3589. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3590. this._gl.viewport(0, 0, texture._width, texture._height);
  3591. this.wipeCaches();
  3592. };
  3593. Engine.prototype.unBindFramebuffer = function (texture) {
  3594. this._currentRenderTarget = null;
  3595. if (texture.generateMipMaps) {
  3596. var gl = this._gl;
  3597. gl.bindTexture(gl.TEXTURE_2D, texture);
  3598. gl.generateMipmap(gl.TEXTURE_2D);
  3599. gl.bindTexture(gl.TEXTURE_2D, null);
  3600. }
  3601. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3602. };
  3603. Engine.prototype.flushFramebuffer = function () {
  3604. // this._gl.flush();
  3605. };
  3606. Engine.prototype.restoreDefaultFramebuffer = function () {
  3607. this._currentRenderTarget = null;
  3608. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3609. this.setViewport(this._cachedViewport);
  3610. this.wipeCaches();
  3611. };
  3612. // VBOs
  3613. Engine.prototype._resetVertexBufferBinding = function () {
  3614. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3615. this._cachedVertexBuffers = null;
  3616. };
  3617. Engine.prototype.createVertexBuffer = function (vertices) {
  3618. var vbo = this._gl.createBuffer();
  3619. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3620. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3621. this._resetVertexBufferBinding();
  3622. vbo.references = 1;
  3623. return vbo;
  3624. };
  3625. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3626. var vbo = this._gl.createBuffer();
  3627. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3628. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3629. this._resetVertexBufferBinding();
  3630. vbo.references = 1;
  3631. return vbo;
  3632. };
  3633. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3634. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3635. if (offset === undefined) {
  3636. offset = 0;
  3637. }
  3638. if (vertices instanceof Float32Array) {
  3639. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3640. } else {
  3641. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3642. }
  3643. this._resetVertexBufferBinding();
  3644. };
  3645. Engine.prototype._resetIndexBufferBinding = function () {
  3646. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3647. this._cachedIndexBuffer = null;
  3648. };
  3649. Engine.prototype.createIndexBuffer = function (indices) {
  3650. var vbo = this._gl.createBuffer();
  3651. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3652. // Check for 32 bits indices
  3653. var arrayBuffer;
  3654. var need32Bits = false;
  3655. if (this._caps.uintIndices) {
  3656. for (var index = 0; index < indices.length; index++) {
  3657. if (indices[index] > 65535) {
  3658. need32Bits = true;
  3659. break;
  3660. }
  3661. }
  3662. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3663. } else {
  3664. arrayBuffer = new Uint16Array(indices);
  3665. }
  3666. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3667. this._resetIndexBufferBinding();
  3668. vbo.references = 1;
  3669. vbo.is32Bits = need32Bits;
  3670. return vbo;
  3671. };
  3672. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3673. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3674. this._cachedVertexBuffers = vertexBuffer;
  3675. this._cachedEffectForVertexBuffers = effect;
  3676. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3677. var offset = 0;
  3678. for (var index = 0; index < vertexDeclaration.length; index++) {
  3679. var order = effect.getAttributeLocation(index);
  3680. if (order >= 0) {
  3681. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3682. }
  3683. offset += vertexDeclaration[index] * 4;
  3684. }
  3685. }
  3686. if (this._cachedIndexBuffer !== indexBuffer) {
  3687. this._cachedIndexBuffer = indexBuffer;
  3688. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3689. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3690. }
  3691. };
  3692. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3693. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3694. this._cachedVertexBuffers = vertexBuffers;
  3695. this._cachedEffectForVertexBuffers = effect;
  3696. var attributes = effect.getAttributesNames();
  3697. for (var index = 0; index < attributes.length; index++) {
  3698. var order = effect.getAttributeLocation(index);
  3699. if (order >= 0) {
  3700. var vertexBuffer = vertexBuffers[attributes[index]];
  3701. if (!vertexBuffer) {
  3702. continue;
  3703. }
  3704. var stride = vertexBuffer.getStrideSize();
  3705. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3706. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3707. }
  3708. }
  3709. }
  3710. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3711. this._cachedIndexBuffer = indexBuffer;
  3712. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3713. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3714. }
  3715. };
  3716. Engine.prototype._releaseBuffer = function (buffer) {
  3717. buffer.references--;
  3718. if (buffer.references === 0) {
  3719. this._gl.deleteBuffer(buffer);
  3720. return true;
  3721. }
  3722. return false;
  3723. };
  3724. Engine.prototype.createInstancesBuffer = function (capacity) {
  3725. var buffer = this._gl.createBuffer();
  3726. buffer.capacity = capacity;
  3727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3728. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3729. return buffer;
  3730. };
  3731. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3732. this._gl.deleteBuffer(buffer);
  3733. };
  3734. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3735. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3736. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3737. for (var index = 0; index < 4; index++) {
  3738. var offsetLocation = offsetLocations[index];
  3739. this._gl.enableVertexAttribArray(offsetLocation);
  3740. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3741. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3742. }
  3743. };
  3744. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3745. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3746. for (var index = 0; index < 4; index++) {
  3747. var offsetLocation = offsetLocations[index];
  3748. this._gl.disableVertexAttribArray(offsetLocation);
  3749. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3750. }
  3751. };
  3752. Engine.prototype.applyStates = function () {
  3753. this._depthCullingState.apply(this._gl);
  3754. this._alphaState.apply(this._gl);
  3755. };
  3756. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3757. // Apply states
  3758. this.applyStates();
  3759. this._drawCalls++;
  3760. // Render
  3761. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3762. if (instancesCount) {
  3763. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3764. return;
  3765. }
  3766. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3767. };
  3768. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3769. // Apply states
  3770. this.applyStates();
  3771. this._drawCalls++;
  3772. if (instancesCount) {
  3773. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3774. return;
  3775. }
  3776. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3777. };
  3778. // Shaders
  3779. Engine.prototype._releaseEffect = function (effect) {
  3780. if (this._compiledEffects[effect._key]) {
  3781. delete this._compiledEffects[effect._key];
  3782. if (effect.getProgram()) {
  3783. this._gl.deleteProgram(effect.getProgram());
  3784. }
  3785. }
  3786. };
  3787. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3788. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3789. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3790. var name = vertex + "+" + fragment + "@" + defines;
  3791. if (this._compiledEffects[name]) {
  3792. return this._compiledEffects[name];
  3793. }
  3794. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3795. effect._key = name;
  3796. this._compiledEffects[name] = effect;
  3797. return effect;
  3798. };
  3799. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3800. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3801. if (typeof samplers === "undefined") { samplers = []; }
  3802. if (typeof defines === "undefined") { defines = ""; }
  3803. return this.createEffect({
  3804. vertex: "particles",
  3805. fragmentElement: fragmentName
  3806. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3807. };
  3808. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3809. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3810. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3811. var shaderProgram = this._gl.createProgram();
  3812. this._gl.attachShader(shaderProgram, vertexShader);
  3813. this._gl.attachShader(shaderProgram, fragmentShader);
  3814. this._gl.linkProgram(shaderProgram);
  3815. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3816. if (!linked) {
  3817. var error = this._gl.getProgramInfoLog(shaderProgram);
  3818. if (error) {
  3819. throw new Error(error);
  3820. }
  3821. }
  3822. this._gl.deleteShader(vertexShader);
  3823. this._gl.deleteShader(fragmentShader);
  3824. return shaderProgram;
  3825. };
  3826. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3827. var results = [];
  3828. for (var index = 0; index < uniformsNames.length; index++) {
  3829. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3830. }
  3831. return results;
  3832. };
  3833. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3834. var results = [];
  3835. for (var index = 0; index < attributesNames.length; index++) {
  3836. try {
  3837. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3838. } catch (e) {
  3839. results.push(-1);
  3840. }
  3841. }
  3842. return results;
  3843. };
  3844. Engine.prototype.enableEffect = function (effect) {
  3845. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3846. if (effect && effect.onBind) {
  3847. effect.onBind(effect);
  3848. }
  3849. return;
  3850. }
  3851. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3852. // Use program
  3853. this._gl.useProgram(effect.getProgram());
  3854. for (var i in this._vertexAttribArrays) {
  3855. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3856. continue;
  3857. }
  3858. this._vertexAttribArrays[i] = false;
  3859. this._gl.disableVertexAttribArray(i);
  3860. }
  3861. var attributesCount = effect.getAttributesCount();
  3862. for (var index = 0; index < attributesCount; index++) {
  3863. // Attributes
  3864. var order = effect.getAttributeLocation(index);
  3865. if (order >= 0) {
  3866. this._vertexAttribArrays[order] = true;
  3867. this._gl.enableVertexAttribArray(order);
  3868. }
  3869. }
  3870. this._currentEffect = effect;
  3871. if (effect.onBind) {
  3872. effect.onBind(effect);
  3873. }
  3874. };
  3875. Engine.prototype.setArray = function (uniform, array) {
  3876. if (!uniform)
  3877. return;
  3878. this._gl.uniform1fv(uniform, array);
  3879. };
  3880. Engine.prototype.setMatrices = function (uniform, matrices) {
  3881. if (!uniform)
  3882. return;
  3883. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3884. };
  3885. Engine.prototype.setMatrix = function (uniform, matrix) {
  3886. if (!uniform)
  3887. return;
  3888. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3889. };
  3890. Engine.prototype.setFloat = function (uniform, value) {
  3891. if (!uniform)
  3892. return;
  3893. this._gl.uniform1f(uniform, value);
  3894. };
  3895. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3896. if (!uniform)
  3897. return;
  3898. this._gl.uniform2f(uniform, x, y);
  3899. };
  3900. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3901. if (!uniform)
  3902. return;
  3903. this._gl.uniform3f(uniform, x, y, z);
  3904. };
  3905. Engine.prototype.setBool = function (uniform, bool) {
  3906. if (!uniform)
  3907. return;
  3908. this._gl.uniform1i(uniform, bool);
  3909. };
  3910. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3911. if (!uniform)
  3912. return;
  3913. this._gl.uniform4f(uniform, x, y, z, w);
  3914. };
  3915. Engine.prototype.setColor3 = function (uniform, color3) {
  3916. if (!uniform)
  3917. return;
  3918. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3919. };
  3920. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3921. if (!uniform)
  3922. return;
  3923. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3924. };
  3925. // States
  3926. Engine.prototype.setState = function (culling, force) {
  3927. // Culling
  3928. if (this._depthCullingState.cull !== culling || force) {
  3929. if (culling) {
  3930. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3931. this._depthCullingState.cull = true;
  3932. } else {
  3933. this._depthCullingState.cull = false;
  3934. }
  3935. }
  3936. };
  3937. Engine.prototype.setDepthBuffer = function (enable) {
  3938. this._depthCullingState.depthTest = enable;
  3939. };
  3940. Engine.prototype.getDepthWrite = function () {
  3941. return this._depthCullingState.depthMask;
  3942. };
  3943. Engine.prototype.setDepthWrite = function (enable) {
  3944. this._depthCullingState.depthMask = enable;
  3945. };
  3946. Engine.prototype.setColorWrite = function (enable) {
  3947. this._gl.colorMask(enable, enable, enable, enable);
  3948. };
  3949. Engine.prototype.setAlphaMode = function (mode) {
  3950. switch (mode) {
  3951. case BABYLON.Engine.ALPHA_DISABLE:
  3952. this.setDepthWrite(true);
  3953. this._alphaState.alphaBlend = false;
  3954. break;
  3955. case BABYLON.Engine.ALPHA_COMBINE:
  3956. this.setDepthWrite(false);
  3957. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3958. this._alphaState.alphaBlend = true;
  3959. break;
  3960. case BABYLON.Engine.ALPHA_ADD:
  3961. this.setDepthWrite(false);
  3962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3963. this._alphaState.alphaBlend = true;
  3964. break;
  3965. }
  3966. this._alphaMode = mode;
  3967. };
  3968. Engine.prototype.getAlphaMode = function () {
  3969. return this._alphaMode;
  3970. };
  3971. Engine.prototype.setAlphaTesting = function (enable) {
  3972. this._alphaTest = enable;
  3973. };
  3974. Engine.prototype.getAlphaTesting = function () {
  3975. return this._alphaTest;
  3976. };
  3977. // Textures
  3978. Engine.prototype.wipeCaches = function () {
  3979. this._activeTexturesCache = [];
  3980. this._currentEffect = null;
  3981. this._depthCullingState.reset();
  3982. this._alphaState.reset();
  3983. this._cachedVertexBuffers = null;
  3984. this._cachedIndexBuffer = null;
  3985. this._cachedEffectForVertexBuffers = null;
  3986. };
  3987. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3988. var gl = this._gl;
  3989. gl.bindTexture(gl.TEXTURE_2D, texture);
  3990. var magFilter = gl.NEAREST;
  3991. var minFilter = gl.NEAREST;
  3992. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3993. magFilter = gl.LINEAR;
  3994. minFilter = gl.LINEAR;
  3995. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3996. magFilter = gl.LINEAR;
  3997. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3998. }
  3999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4001. gl.bindTexture(gl.TEXTURE_2D, null);
  4002. texture.samplingMode = samplingMode;
  4003. };
  4004. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4005. var _this = this;
  4006. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4007. if (typeof onLoad === "undefined") { onLoad = null; }
  4008. if (typeof onError === "undefined") { onError = null; }
  4009. if (typeof buffer === "undefined") { buffer = null; }
  4010. var texture = this._gl.createTexture();
  4011. var extension;
  4012. var fromData = false;
  4013. if (url.substr(0, 5) === "data:") {
  4014. fromData = true;
  4015. }
  4016. if (!fromData)
  4017. extension = url.substr(url.length - 4, 4).toLowerCase();
  4018. else {
  4019. var oldUrl = url;
  4020. fromData = oldUrl.split(':');
  4021. url = oldUrl;
  4022. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4023. }
  4024. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4025. var isTGA = (extension === ".tga");
  4026. scene._addPendingData(texture);
  4027. texture.url = url;
  4028. texture.noMipmap = noMipmap;
  4029. texture.references = 1;
  4030. this._loadedTexturesCache.push(texture);
  4031. var onerror = function () {
  4032. scene._removePendingData(texture);
  4033. if (onError) {
  4034. onError();
  4035. }
  4036. };
  4037. if (isTGA) {
  4038. var callback = function (arrayBuffer) {
  4039. var data = new Uint8Array(arrayBuffer);
  4040. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4041. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4042. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4043. if (onLoad) {
  4044. onLoad();
  4045. }
  4046. }, samplingMode);
  4047. };
  4048. if (!(fromData instanceof Array))
  4049. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4050. callback(arrayBuffer);
  4051. }, onerror, scene.database, true);
  4052. else
  4053. callback(buffer);
  4054. } else if (isDDS) {
  4055. callback = function (data) {
  4056. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4057. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  4058. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4059. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4060. if (onLoad) {
  4061. onLoad();
  4062. }
  4063. }, samplingMode);
  4064. };
  4065. if (!(fromData instanceof Array))
  4066. BABYLON.Tools.LoadFile(url, function (data) {
  4067. callback(data);
  4068. }, onerror, scene.database, true);
  4069. else
  4070. callback(buffer);
  4071. } else {
  4072. var onload = function (img) {
  4073. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4074. var isPot = (img.width == potWidth && img.height == potHeight);
  4075. if (!isPot) {
  4076. _this._workingCanvas.width = potWidth;
  4077. _this._workingCanvas.height = potHeight;
  4078. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4079. }
  4080. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4081. if (onLoad) {
  4082. onLoad();
  4083. }
  4084. }, samplingMode);
  4085. };
  4086. if (!(fromData instanceof Array))
  4087. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4088. else
  4089. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4090. }
  4091. return texture;
  4092. };
  4093. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4094. var texture = this._gl.createTexture();
  4095. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4096. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4097. // Format
  4098. var internalFormat = this._gl.RGBA;
  4099. switch (format) {
  4100. case Engine.TEXTUREFORMAT_ALPHA:
  4101. internalFormat = this._gl.ALPHA;
  4102. break;
  4103. case Engine.TEXTUREFORMAT_LUMINANCE:
  4104. internalFormat = this._gl.LUMINANCE;
  4105. break;
  4106. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4107. internalFormat = this._gl.LUMINANCE_ALPHA;
  4108. break;
  4109. case Engine.TEXTUREFORMAT_RGB:
  4110. internalFormat = this._gl.RGB;
  4111. break;
  4112. case Engine.TEXTUREFORMAT_RGBA:
  4113. internalFormat = this._gl.RGBA;
  4114. break;
  4115. }
  4116. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4117. if (generateMipMaps) {
  4118. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4119. }
  4120. // Filters
  4121. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4122. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4124. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4125. this._activeTexturesCache = [];
  4126. texture._baseWidth = width;
  4127. texture._baseHeight = height;
  4128. texture._width = width;
  4129. texture._height = height;
  4130. texture.isReady = true;
  4131. texture.references = 1;
  4132. texture.samplingMode = samplingMode;
  4133. this._loadedTexturesCache.push(texture);
  4134. return texture;
  4135. };
  4136. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4137. var texture = this._gl.createTexture();
  4138. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4139. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4140. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4141. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4142. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4143. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4144. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4145. this._activeTexturesCache = [];
  4146. texture._baseWidth = width;
  4147. texture._baseHeight = height;
  4148. texture._width = width;
  4149. texture._height = height;
  4150. texture.isReady = false;
  4151. texture.generateMipMaps = generateMipMaps;
  4152. texture.references = 1;
  4153. texture.samplingMode = samplingMode;
  4154. this._loadedTexturesCache.push(texture);
  4155. return texture;
  4156. };
  4157. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4158. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4159. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4160. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4161. if (texture.generateMipMaps) {
  4162. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4163. }
  4164. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4165. this._activeTexturesCache = [];
  4166. texture.isReady = true;
  4167. };
  4168. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4169. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4171. // Scale the video if it is a NPOT using the current working canvas
  4172. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4173. if (!texture._workingCanvas) {
  4174. texture._workingCanvas = document.createElement("canvas");
  4175. texture._workingContext = texture._workingCanvas.getContext("2d");
  4176. texture._workingCanvas.width = texture._width;
  4177. texture._workingCanvas.height = texture._height;
  4178. }
  4179. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4180. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4181. } else {
  4182. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4183. }
  4184. if (texture.generateMipMaps) {
  4185. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4186. }
  4187. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4188. this._activeTexturesCache = [];
  4189. texture.isReady = true;
  4190. };
  4191. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4192. // old version had a "generateMipMaps" arg instead of options.
  4193. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4194. // in the same way, generateDepthBuffer is defaulted to true
  4195. var generateMipMaps = false;
  4196. var generateDepthBuffer = true;
  4197. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4198. if (options !== undefined) {
  4199. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4200. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4201. if (options.samplingMode !== undefined) {
  4202. samplingMode = options.samplingMode;
  4203. }
  4204. }
  4205. var gl = this._gl;
  4206. var texture = gl.createTexture();
  4207. gl.bindTexture(gl.TEXTURE_2D, texture);
  4208. var width = size.width || size;
  4209. var height = size.height || size;
  4210. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4215. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4216. var depthBuffer;
  4217. // Create the depth buffer
  4218. if (generateDepthBuffer) {
  4219. depthBuffer = gl.createRenderbuffer();
  4220. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4221. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4222. }
  4223. // Create the framebuffer
  4224. var framebuffer = gl.createFramebuffer();
  4225. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4227. if (generateDepthBuffer) {
  4228. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4229. }
  4230. // Unbind
  4231. gl.bindTexture(gl.TEXTURE_2D, null);
  4232. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4233. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4234. texture._framebuffer = framebuffer;
  4235. if (generateDepthBuffer) {
  4236. texture._depthBuffer = depthBuffer;
  4237. }
  4238. texture._width = width;
  4239. texture._height = height;
  4240. texture.isReady = true;
  4241. texture.generateMipMaps = generateMipMaps;
  4242. texture.references = 1;
  4243. texture.samplingMode = samplingMode;
  4244. this._activeTexturesCache = [];
  4245. this._loadedTexturesCache.push(texture);
  4246. return texture;
  4247. };
  4248. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4249. var _this = this;
  4250. var gl = this._gl;
  4251. var texture = gl.createTexture();
  4252. texture.isCube = true;
  4253. texture.url = rootUrl;
  4254. texture.references = 1;
  4255. this._loadedTexturesCache.push(texture);
  4256. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4257. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4258. if (isDDS) {
  4259. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4260. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4261. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4262. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4264. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4265. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4266. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4267. }
  4268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4272. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4273. _this._activeTexturesCache = [];
  4274. texture._width = info.width;
  4275. texture._height = info.height;
  4276. texture.isReady = true;
  4277. }, null, null, true);
  4278. } else {
  4279. cascadeLoad(rootUrl, scene, function (imgs) {
  4280. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4281. var height = width;
  4282. _this._workingCanvas.width = width;
  4283. _this._workingCanvas.height = height;
  4284. var faces = [
  4285. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4286. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4287. ];
  4288. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4290. for (var index = 0; index < faces.length; index++) {
  4291. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4292. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4293. }
  4294. if (!noMipmap) {
  4295. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4296. }
  4297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4301. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4302. _this._activeTexturesCache = [];
  4303. texture._width = width;
  4304. texture._height = height;
  4305. texture.isReady = true;
  4306. }, extensions);
  4307. }
  4308. return texture;
  4309. };
  4310. Engine.prototype._releaseTexture = function (texture) {
  4311. var gl = this._gl;
  4312. if (texture._framebuffer) {
  4313. gl.deleteFramebuffer(texture._framebuffer);
  4314. }
  4315. if (texture._depthBuffer) {
  4316. gl.deleteRenderbuffer(texture._depthBuffer);
  4317. }
  4318. gl.deleteTexture(texture);
  4319. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4320. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4322. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4323. this._activeTexturesCache[channel] = null;
  4324. }
  4325. var index = this._loadedTexturesCache.indexOf(texture);
  4326. if (index !== -1) {
  4327. this._loadedTexturesCache.splice(index, 1);
  4328. }
  4329. };
  4330. Engine.prototype.bindSamplers = function (effect) {
  4331. this._gl.useProgram(effect.getProgram());
  4332. var samplers = effect.getSamplers();
  4333. for (var index = 0; index < samplers.length; index++) {
  4334. var uniform = effect.getUniform(samplers[index]);
  4335. this._gl.uniform1i(uniform, index);
  4336. }
  4337. this._currentEffect = null;
  4338. };
  4339. Engine.prototype._bindTexture = function (channel, texture) {
  4340. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4341. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4342. this._activeTexturesCache[channel] = null;
  4343. };
  4344. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4345. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4346. };
  4347. Engine.prototype.setTexture = function (channel, texture) {
  4348. if (channel < 0) {
  4349. return;
  4350. }
  4351. // Not ready?
  4352. if (!texture || !texture.isReady()) {
  4353. if (this._activeTexturesCache[channel] != null) {
  4354. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4355. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4356. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4357. this._activeTexturesCache[channel] = null;
  4358. }
  4359. return;
  4360. }
  4361. // Video
  4362. if (texture instanceof BABYLON.VideoTexture) {
  4363. if (texture.update()) {
  4364. this._activeTexturesCache[channel] = null;
  4365. }
  4366. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4367. texture.delayLoad();
  4368. return;
  4369. }
  4370. if (this._activeTexturesCache[channel] == texture) {
  4371. return;
  4372. }
  4373. this._activeTexturesCache[channel] = texture;
  4374. var internalTexture = texture.getInternalTexture();
  4375. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4376. if (internalTexture.isCube) {
  4377. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4378. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4379. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4380. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4381. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4383. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4384. }
  4385. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4386. } else {
  4387. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4388. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4389. internalTexture._cachedWrapU = texture.wrapU;
  4390. switch (texture.wrapU) {
  4391. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4393. break;
  4394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4396. break;
  4397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4399. break;
  4400. }
  4401. }
  4402. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4403. internalTexture._cachedWrapV = texture.wrapV;
  4404. switch (texture.wrapV) {
  4405. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4407. break;
  4408. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4410. break;
  4411. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4413. break;
  4414. }
  4415. }
  4416. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4417. }
  4418. };
  4419. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4420. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4421. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4422. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4423. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4424. }
  4425. };
  4426. Engine.prototype.readPixels = function (x, y, width, height) {
  4427. var data = new Uint8Array(height * width * 4);
  4428. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4429. return data;
  4430. };
  4431. // Dispose
  4432. Engine.prototype.dispose = function () {
  4433. this.hideLoadingUI();
  4434. this.stopRenderLoop();
  4435. while (this.scenes.length) {
  4436. this.scenes[0].dispose();
  4437. }
  4438. for (var name in this._compiledEffects) {
  4439. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4440. }
  4441. for (var i in this._vertexAttribArrays) {
  4442. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4443. continue;
  4444. }
  4445. this._gl.disableVertexAttribArray(i);
  4446. }
  4447. // Events
  4448. window.removeEventListener("blur", this._onBlur);
  4449. window.removeEventListener("focus", this._onFocus);
  4450. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4451. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4452. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4453. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4454. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4455. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4456. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4457. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4458. };
  4459. // Loading screen
  4460. Engine.prototype.displayLoadingUI = function () {
  4461. var _this = this;
  4462. this._loadingDiv = document.createElement("div");
  4463. this._loadingDiv.style.opacity = "0";
  4464. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4465. // Loading text
  4466. this._loadingTextDiv = document.createElement("div");
  4467. this._loadingTextDiv.style.position = "absolute";
  4468. this._loadingTextDiv.style.left = "0";
  4469. this._loadingTextDiv.style.top = "50%";
  4470. this._loadingTextDiv.style.marginTop = "80px";
  4471. this._loadingTextDiv.style.width = "100%";
  4472. this._loadingTextDiv.style.height = "20px";
  4473. this._loadingTextDiv.style.fontFamily = "Arial";
  4474. this._loadingTextDiv.style.fontSize = "14px";
  4475. this._loadingTextDiv.style.color = "white";
  4476. this._loadingTextDiv.style.textAlign = "center";
  4477. this._loadingTextDiv.innerHTML = "Loading";
  4478. this._loadingDiv.appendChild(this._loadingTextDiv);
  4479. // Loading img
  4480. var imgBack = new Image();
  4481. 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==";
  4482. imgBack.style.position = "absolute";
  4483. imgBack.style.left = "50%";
  4484. imgBack.style.top = "50%";
  4485. imgBack.style.marginLeft = "-50px";
  4486. imgBack.style.marginTop = "-50px";
  4487. imgBack.style.transition = "transform 1.0s ease";
  4488. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4489. var deg = 360;
  4490. var onTransitionEnd = function () {
  4491. deg += 360;
  4492. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4493. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4494. };
  4495. imgBack.addEventListener("transitionend", onTransitionEnd);
  4496. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4497. this._loadingDiv.appendChild(imgBack);
  4498. // front image
  4499. var imgFront = new Image();
  4500. 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=";
  4501. imgFront.style.position = "absolute";
  4502. imgFront.style.left = "50%";
  4503. imgFront.style.top = "50%";
  4504. imgFront.style.marginLeft = "-50px";
  4505. imgFront.style.marginTop = "-50px";
  4506. this._loadingDiv.appendChild(imgFront);
  4507. // Resize
  4508. this._resizeLoadingUI = function () {
  4509. var canvasRect = _this.getRenderingCanvasClientRect();
  4510. _this._loadingDiv.style.position = "absolute";
  4511. _this._loadingDiv.style.left = canvasRect.left + "px";
  4512. _this._loadingDiv.style.top = canvasRect.top + "px";
  4513. _this._loadingDiv.style.width = canvasRect.width + "px";
  4514. _this._loadingDiv.style.height = canvasRect.height + "px";
  4515. };
  4516. this._resizeLoadingUI();
  4517. window.addEventListener("resize", this._resizeLoadingUI);
  4518. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4519. document.body.appendChild(this._loadingDiv);
  4520. setTimeout(function () {
  4521. _this._loadingDiv.style.opacity = "1";
  4522. imgBack.style.transform = "rotateZ(360deg)";
  4523. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4524. }, 0);
  4525. };
  4526. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4527. set: function (text) {
  4528. if (!this._loadingDiv) {
  4529. return;
  4530. }
  4531. this._loadingTextDiv.innerHTML = text;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4537. get: function () {
  4538. return this._loadingDivBackgroundColor;
  4539. },
  4540. set: function (color) {
  4541. this._loadingDivBackgroundColor = color;
  4542. if (!this._loadingDiv) {
  4543. return;
  4544. }
  4545. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4546. },
  4547. enumerable: true,
  4548. configurable: true
  4549. });
  4550. Engine.prototype.hideLoadingUI = function () {
  4551. var _this = this;
  4552. if (!this._loadingDiv) {
  4553. return;
  4554. }
  4555. var onTransitionEnd = function () {
  4556. if (!_this._loadingDiv) {
  4557. return;
  4558. }
  4559. document.body.removeChild(_this._loadingDiv);
  4560. window.removeEventListener("resize", _this._resizeLoadingUI);
  4561. _this._loadingDiv = null;
  4562. };
  4563. this._loadingDiv.style.opacity = "0";
  4564. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4565. };
  4566. // FPS
  4567. Engine.prototype.getFps = function () {
  4568. return this.fps;
  4569. };
  4570. Engine.prototype.getDeltaTime = function () {
  4571. return this.deltaTime;
  4572. };
  4573. Engine.prototype._measureFps = function () {
  4574. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4575. var length = this.previousFramesDuration.length;
  4576. if (length >= 2) {
  4577. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4578. }
  4579. if (length >= this.fpsRange) {
  4580. if (length > this.fpsRange) {
  4581. this.previousFramesDuration.splice(0, 1);
  4582. length = this.previousFramesDuration.length;
  4583. }
  4584. var sum = 0;
  4585. for (var id = 0; id < length - 1; id++) {
  4586. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4587. }
  4588. this.fps = 1000.0 / (sum / (length - 1));
  4589. }
  4590. };
  4591. // Statics
  4592. Engine.isSupported = function () {
  4593. try {
  4594. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4595. if (navigator.isCocoonJS) {
  4596. return true;
  4597. }
  4598. var tempcanvas = document.createElement("canvas");
  4599. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4600. return gl != null && !!window.WebGLRenderingContext;
  4601. } catch (e) {
  4602. return false;
  4603. }
  4604. };
  4605. Engine._ALPHA_DISABLE = 0;
  4606. Engine._ALPHA_ADD = 1;
  4607. Engine._ALPHA_COMBINE = 2;
  4608. Engine._DELAYLOADSTATE_NONE = 0;
  4609. Engine._DELAYLOADSTATE_LOADED = 1;
  4610. Engine._DELAYLOADSTATE_LOADING = 2;
  4611. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4612. Engine._TEXTUREFORMAT_ALPHA = 0;
  4613. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4614. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4615. Engine._TEXTUREFORMAT_RGB = 4;
  4616. Engine._TEXTUREFORMAT_RGBA = 4;
  4617. Engine.Epsilon = 0.001;
  4618. Engine.CollisionsEpsilon = 0.001;
  4619. Engine.ShadersRepository = "Babylon/Shaders/";
  4620. return Engine;
  4621. })();
  4622. BABYLON.Engine = Engine;
  4623. })(BABYLON || (BABYLON = {}));
  4624. //# sourceMappingURL=babylon.engine.js.map
  4625. var BABYLON;
  4626. (function (BABYLON) {
  4627. var Node = (function () {
  4628. function Node(name, scene) {
  4629. this.state = "";
  4630. this.animations = new Array();
  4631. this._childrenFlag = -1;
  4632. this._isEnabled = true;
  4633. this._isReady = true;
  4634. this._currentRenderId = -1;
  4635. this.name = name;
  4636. this.id = name;
  4637. this._scene = scene;
  4638. this._initCache();
  4639. }
  4640. Node.prototype.getScene = function () {
  4641. return this._scene;
  4642. };
  4643. Node.prototype.getEngine = function () {
  4644. return this._scene.getEngine();
  4645. };
  4646. // override it in derived class
  4647. Node.prototype.getWorldMatrix = function () {
  4648. return BABYLON.Matrix.Identity();
  4649. };
  4650. // override it in derived class if you add new variables to the cache
  4651. // and call the parent class method
  4652. Node.prototype._initCache = function () {
  4653. this._cache = {};
  4654. this._cache.parent = undefined;
  4655. };
  4656. Node.prototype.updateCache = function (force) {
  4657. if (!force && this.isSynchronized())
  4658. return;
  4659. this._cache.parent = this.parent;
  4660. this._updateCache();
  4661. };
  4662. // override it in derived class if you add new variables to the cache
  4663. // and call the parent class method if !ignoreParentClass
  4664. Node.prototype._updateCache = function (ignoreParentClass) {
  4665. };
  4666. // override it in derived class if you add new variables to the cache
  4667. Node.prototype._isSynchronized = function () {
  4668. return true;
  4669. };
  4670. Node.prototype.isSynchronizedWithParent = function () {
  4671. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4672. };
  4673. Node.prototype.isSynchronized = function (updateCache) {
  4674. var check = this.hasNewParent();
  4675. check = check || !this.isSynchronizedWithParent();
  4676. check = check || !this._isSynchronized();
  4677. if (updateCache)
  4678. this.updateCache(true);
  4679. return !check;
  4680. };
  4681. Node.prototype.hasNewParent = function (update) {
  4682. if (this._cache.parent === this.parent)
  4683. return false;
  4684. if (update)
  4685. this._cache.parent = this.parent;
  4686. return true;
  4687. };
  4688. Node.prototype.isReady = function () {
  4689. return this._isReady;
  4690. };
  4691. Node.prototype.isEnabled = function () {
  4692. if (!this._isEnabled) {
  4693. return false;
  4694. }
  4695. if (this.parent) {
  4696. return this.parent.isEnabled();
  4697. }
  4698. return true;
  4699. };
  4700. Node.prototype.setEnabled = function (value) {
  4701. this._isEnabled = value;
  4702. };
  4703. Node.prototype.isDescendantOf = function (ancestor) {
  4704. if (this.parent) {
  4705. if (this.parent === ancestor) {
  4706. return true;
  4707. }
  4708. return this.parent.isDescendantOf(ancestor);
  4709. }
  4710. return false;
  4711. };
  4712. Node.prototype._getDescendants = function (list, results) {
  4713. for (var index = 0; index < list.length; index++) {
  4714. var item = list[index];
  4715. if (item.isDescendantOf(this)) {
  4716. results.push(item);
  4717. }
  4718. }
  4719. };
  4720. Node.prototype.getDescendants = function () {
  4721. var results = [];
  4722. this._getDescendants(this._scene.meshes, results);
  4723. this._getDescendants(this._scene.lights, results);
  4724. this._getDescendants(this._scene.cameras, results);
  4725. return results;
  4726. };
  4727. Node.prototype._setReady = function (state) {
  4728. if (state == this._isReady) {
  4729. return;
  4730. }
  4731. if (!state) {
  4732. this._isReady = false;
  4733. return;
  4734. }
  4735. this._isReady = true;
  4736. if (this.onReady) {
  4737. this.onReady(this);
  4738. }
  4739. };
  4740. return Node;
  4741. })();
  4742. BABYLON.Node = Node;
  4743. })(BABYLON || (BABYLON = {}));
  4744. //# sourceMappingURL=babylon.node.js.map
  4745. var BABYLON;
  4746. (function (BABYLON) {
  4747. var BoundingSphere = (function () {
  4748. function BoundingSphere(minimum, maximum) {
  4749. this.minimum = minimum;
  4750. this.maximum = maximum;
  4751. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4752. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4753. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4754. this.radius = distance * 0.5;
  4755. this.centerWorld = BABYLON.Vector3.Zero();
  4756. this._update(BABYLON.Matrix.Identity());
  4757. }
  4758. // Methods
  4759. BoundingSphere.prototype._update = function (world) {
  4760. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4761. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4762. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4763. };
  4764. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4765. for (var i = 0; i < 6; i++) {
  4766. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4767. return false;
  4768. }
  4769. return true;
  4770. };
  4771. BoundingSphere.prototype.intersectsPoint = function (point) {
  4772. var x = this.centerWorld.x - point.x;
  4773. var y = this.centerWorld.y - point.y;
  4774. var z = this.centerWorld.z - point.z;
  4775. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4776. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4777. return false;
  4778. return true;
  4779. };
  4780. // Statics
  4781. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4782. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4783. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4784. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4785. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4786. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4787. return false;
  4788. return true;
  4789. };
  4790. return BoundingSphere;
  4791. })();
  4792. BABYLON.BoundingSphere = BoundingSphere;
  4793. })(BABYLON || (BABYLON = {}));
  4794. //# sourceMappingURL=babylon.boundingSphere.js.map
  4795. var BABYLON;
  4796. (function (BABYLON) {
  4797. var BoundingBox = (function () {
  4798. function BoundingBox(minimum, maximum) {
  4799. this.minimum = minimum;
  4800. this.maximum = maximum;
  4801. this.vectors = new Array();
  4802. this.vectorsWorld = new Array();
  4803. // Bounding vectors
  4804. this.vectors.push(this.minimum.clone());
  4805. this.vectors.push(this.maximum.clone());
  4806. this.vectors.push(this.minimum.clone());
  4807. this.vectors[2].x = this.maximum.x;
  4808. this.vectors.push(this.minimum.clone());
  4809. this.vectors[3].y = this.maximum.y;
  4810. this.vectors.push(this.minimum.clone());
  4811. this.vectors[4].z = this.maximum.z;
  4812. this.vectors.push(this.maximum.clone());
  4813. this.vectors[5].z = this.minimum.z;
  4814. this.vectors.push(this.maximum.clone());
  4815. this.vectors[6].x = this.minimum.x;
  4816. this.vectors.push(this.maximum.clone());
  4817. this.vectors[7].y = this.minimum.y;
  4818. // OBB
  4819. this.center = this.maximum.add(this.minimum).scale(0.5);
  4820. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4821. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4822. for (var index = 0; index < this.vectors.length; index++) {
  4823. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4824. }
  4825. this.minimumWorld = BABYLON.Vector3.Zero();
  4826. this.maximumWorld = BABYLON.Vector3.Zero();
  4827. this._update(BABYLON.Matrix.Identity());
  4828. }
  4829. // Methods
  4830. BoundingBox.prototype.getWorldMatrix = function () {
  4831. return this._worldMatrix;
  4832. };
  4833. BoundingBox.prototype._update = function (world) {
  4834. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4835. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4836. for (var index = 0; index < this.vectors.length; index++) {
  4837. var v = this.vectorsWorld[index];
  4838. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4839. if (v.x < this.minimumWorld.x)
  4840. this.minimumWorld.x = v.x;
  4841. if (v.y < this.minimumWorld.y)
  4842. this.minimumWorld.y = v.y;
  4843. if (v.z < this.minimumWorld.z)
  4844. this.minimumWorld.z = v.z;
  4845. if (v.x > this.maximumWorld.x)
  4846. this.maximumWorld.x = v.x;
  4847. if (v.y > this.maximumWorld.y)
  4848. this.maximumWorld.y = v.y;
  4849. if (v.z > this.maximumWorld.z)
  4850. this.maximumWorld.z = v.z;
  4851. }
  4852. // OBB
  4853. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4854. this.center.scaleInPlace(0.5);
  4855. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4856. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4858. this._worldMatrix = world;
  4859. };
  4860. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4861. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4862. };
  4863. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4864. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4865. };
  4866. BoundingBox.prototype.intersectsPoint = function (point) {
  4867. var delta = BABYLON.Engine.Epsilon;
  4868. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4869. return false;
  4870. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4871. return false;
  4872. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4873. return false;
  4874. return true;
  4875. };
  4876. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4877. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4878. };
  4879. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4880. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4881. return false;
  4882. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4883. return false;
  4884. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4885. return false;
  4886. return true;
  4887. };
  4888. // Statics
  4889. BoundingBox.Intersects = function (box0, box1) {
  4890. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4891. return false;
  4892. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4893. return false;
  4894. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4895. return false;
  4896. return true;
  4897. };
  4898. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4899. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4900. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4901. return (num <= (sphereRadius * sphereRadius));
  4902. };
  4903. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4904. for (var p = 0; p < 6; p++) {
  4905. for (var i = 0; i < 8; i++) {
  4906. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4907. return false;
  4908. }
  4909. }
  4910. }
  4911. return true;
  4912. };
  4913. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4914. for (var p = 0; p < 6; p++) {
  4915. var inCount = 8;
  4916. for (var i = 0; i < 8; i++) {
  4917. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4918. --inCount;
  4919. } else {
  4920. break;
  4921. }
  4922. }
  4923. if (inCount == 0)
  4924. return false;
  4925. }
  4926. return true;
  4927. };
  4928. return BoundingBox;
  4929. })();
  4930. BABYLON.BoundingBox = BoundingBox;
  4931. })(BABYLON || (BABYLON = {}));
  4932. //# sourceMappingURL=babylon.boundingBox.js.map
  4933. var BABYLON;
  4934. (function (BABYLON) {
  4935. var computeBoxExtents = function (axis, box) {
  4936. var p = BABYLON.Vector3.Dot(box.center, axis);
  4937. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4938. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4939. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4940. var r = r0 + r1 + r2;
  4941. return {
  4942. min: p - r,
  4943. max: p + r
  4944. };
  4945. };
  4946. var extentsOverlap = function (min0, max0, min1, max1) {
  4947. return !(min0 > max1 || min1 > max0);
  4948. };
  4949. var axisOverlap = function (axis, box0, box1) {
  4950. var result0 = computeBoxExtents(axis, box0);
  4951. var result1 = computeBoxExtents(axis, box1);
  4952. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4953. };
  4954. var BoundingInfo = (function () {
  4955. function BoundingInfo(minimum, maximum) {
  4956. this.minimum = minimum;
  4957. this.maximum = maximum;
  4958. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4959. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4960. }
  4961. // Methods
  4962. BoundingInfo.prototype._update = function (world) {
  4963. this.boundingBox._update(world);
  4964. this.boundingSphere._update(world);
  4965. };
  4966. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4967. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4968. return false;
  4969. return this.boundingBox.isInFrustum(frustumPlanes);
  4970. };
  4971. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4972. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4973. };
  4974. BoundingInfo.prototype._checkCollision = function (collider) {
  4975. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4976. };
  4977. BoundingInfo.prototype.intersectsPoint = function (point) {
  4978. if (!this.boundingSphere.centerWorld) {
  4979. return false;
  4980. }
  4981. if (!this.boundingSphere.intersectsPoint(point)) {
  4982. return false;
  4983. }
  4984. if (!this.boundingBox.intersectsPoint(point)) {
  4985. return false;
  4986. }
  4987. return true;
  4988. };
  4989. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4990. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4991. return false;
  4992. }
  4993. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4994. return false;
  4995. }
  4996. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4997. return false;
  4998. }
  4999. if (!precise) {
  5000. return true;
  5001. }
  5002. var box0 = this.boundingBox;
  5003. var box1 = boundingInfo.boundingBox;
  5004. if (!axisOverlap(box0.directions[0], box0, box1))
  5005. return false;
  5006. if (!axisOverlap(box0.directions[1], box0, box1))
  5007. return false;
  5008. if (!axisOverlap(box0.directions[2], box0, box1))
  5009. return false;
  5010. if (!axisOverlap(box1.directions[0], box0, box1))
  5011. return false;
  5012. if (!axisOverlap(box1.directions[1], box0, box1))
  5013. return false;
  5014. if (!axisOverlap(box1.directions[2], box0, box1))
  5015. return false;
  5016. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5017. return false;
  5018. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5019. return false;
  5020. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5021. return false;
  5022. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5023. return false;
  5024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5025. return false;
  5026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5027. return false;
  5028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5029. return false;
  5030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5031. return false;
  5032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5033. return false;
  5034. return true;
  5035. };
  5036. return BoundingInfo;
  5037. })();
  5038. BABYLON.BoundingInfo = BoundingInfo;
  5039. })(BABYLON || (BABYLON = {}));
  5040. //# sourceMappingURL=babylon.boundingInfo.js.map
  5041. var BABYLON;
  5042. (function (BABYLON) {
  5043. var Light = (function (_super) {
  5044. __extends(Light, _super);
  5045. function Light(name, scene) {
  5046. _super.call(this, name, scene);
  5047. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5048. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5049. this.intensity = 1.0;
  5050. this.range = Number.MAX_VALUE;
  5051. this.includedOnlyMeshes = new Array();
  5052. this.excludedMeshes = new Array();
  5053. this._excludedMeshesIds = new Array();
  5054. this._includedOnlyMeshesIds = new Array();
  5055. scene.lights.push(this);
  5056. }
  5057. Light.prototype.getShadowGenerator = function () {
  5058. return this._shadowGenerator;
  5059. };
  5060. Light.prototype.getAbsolutePosition = function () {
  5061. return BABYLON.Vector3.Zero();
  5062. };
  5063. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5064. };
  5065. Light.prototype._getWorldMatrix = function () {
  5066. return BABYLON.Matrix.Identity();
  5067. };
  5068. Light.prototype.canAffectMesh = function (mesh) {
  5069. if (!mesh) {
  5070. return true;
  5071. }
  5072. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5073. return false;
  5074. }
  5075. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5076. return false;
  5077. }
  5078. return true;
  5079. };
  5080. Light.prototype.getWorldMatrix = function () {
  5081. this._currentRenderId = this.getScene().getRenderId();
  5082. var worldMatrix = this._getWorldMatrix();
  5083. if (this.parent && this.parent.getWorldMatrix) {
  5084. if (!this._parentedWorldMatrix) {
  5085. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5086. }
  5087. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5088. return this._parentedWorldMatrix;
  5089. }
  5090. return worldMatrix;
  5091. };
  5092. Light.prototype.dispose = function () {
  5093. if (this._shadowGenerator) {
  5094. this._shadowGenerator.dispose();
  5095. this._shadowGenerator = null;
  5096. }
  5097. // Remove from scene
  5098. var index = this.getScene().lights.indexOf(this);
  5099. this.getScene().lights.splice(index, 1);
  5100. };
  5101. return Light;
  5102. })(BABYLON.Node);
  5103. BABYLON.Light = Light;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.light.js.map
  5106. var BABYLON;
  5107. (function (BABYLON) {
  5108. var PointLight = (function (_super) {
  5109. __extends(PointLight, _super);
  5110. function PointLight(name, position, scene) {
  5111. _super.call(this, name, scene);
  5112. this.position = position;
  5113. }
  5114. PointLight.prototype.getAbsolutePosition = function () {
  5115. return this._transformedPosition ? this._transformedPosition : this.position;
  5116. };
  5117. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5118. if (this.parent && this.parent.getWorldMatrix) {
  5119. if (!this._transformedPosition) {
  5120. this._transformedPosition = BABYLON.Vector3.Zero();
  5121. }
  5122. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5123. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5124. return;
  5125. }
  5126. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5127. };
  5128. PointLight.prototype.getShadowGenerator = function () {
  5129. return null;
  5130. };
  5131. PointLight.prototype._getWorldMatrix = function () {
  5132. if (!this._worldMatrix) {
  5133. this._worldMatrix = BABYLON.Matrix.Identity();
  5134. }
  5135. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5136. return this._worldMatrix;
  5137. };
  5138. return PointLight;
  5139. })(BABYLON.Light);
  5140. BABYLON.PointLight = PointLight;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.pointLight.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. var SpotLight = (function (_super) {
  5146. __extends(SpotLight, _super);
  5147. function SpotLight(name, position, direction, angle, exponent, scene) {
  5148. _super.call(this, name, scene);
  5149. this.position = position;
  5150. this.direction = direction;
  5151. this.angle = angle;
  5152. this.exponent = exponent;
  5153. }
  5154. SpotLight.prototype.getAbsolutePosition = function () {
  5155. return this._transformedPosition ? this._transformedPosition : this.position;
  5156. };
  5157. SpotLight.prototype.setDirectionToTarget = function (target) {
  5158. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5159. return this.direction;
  5160. };
  5161. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5162. var normalizeDirection;
  5163. if (this.parent && this.parent.getWorldMatrix) {
  5164. if (!this._transformedDirection) {
  5165. this._transformedDirection = BABYLON.Vector3.Zero();
  5166. }
  5167. if (!this._transformedPosition) {
  5168. this._transformedPosition = BABYLON.Vector3.Zero();
  5169. }
  5170. var parentWorldMatrix = this.parent.getWorldMatrix();
  5171. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5172. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5173. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5174. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5175. } else {
  5176. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5177. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5178. }
  5179. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5180. };
  5181. SpotLight.prototype._getWorldMatrix = function () {
  5182. if (!this._worldMatrix) {
  5183. this._worldMatrix = BABYLON.Matrix.Identity();
  5184. }
  5185. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5186. return this._worldMatrix;
  5187. };
  5188. return SpotLight;
  5189. })(BABYLON.Light);
  5190. BABYLON.SpotLight = SpotLight;
  5191. })(BABYLON || (BABYLON = {}));
  5192. //# sourceMappingURL=babylon.spotLight.js.map
  5193. var BABYLON;
  5194. (function (BABYLON) {
  5195. var DirectionalLight = (function (_super) {
  5196. __extends(DirectionalLight, _super);
  5197. function DirectionalLight(name, direction, scene) {
  5198. _super.call(this, name, scene);
  5199. this.direction = direction;
  5200. this.position = direction.scale(-1);
  5201. }
  5202. DirectionalLight.prototype.getAbsolutePosition = function () {
  5203. return this._transformedPosition ? this._transformedPosition : this.position;
  5204. };
  5205. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5206. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5207. return this.direction;
  5208. };
  5209. DirectionalLight.prototype._computeTransformedPosition = function () {
  5210. if (this.parent && this.parent.getWorldMatrix) {
  5211. if (!this._transformedPosition) {
  5212. this._transformedPosition = BABYLON.Vector3.Zero();
  5213. }
  5214. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5215. return true;
  5216. }
  5217. return false;
  5218. };
  5219. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5220. if (this.parent && this.parent.getWorldMatrix) {
  5221. if (!this._transformedDirection) {
  5222. this._transformedDirection = BABYLON.Vector3.Zero();
  5223. }
  5224. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5225. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5226. return;
  5227. }
  5228. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5229. };
  5230. DirectionalLight.prototype._getWorldMatrix = function () {
  5231. if (!this._worldMatrix) {
  5232. this._worldMatrix = BABYLON.Matrix.Identity();
  5233. }
  5234. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5235. return this._worldMatrix;
  5236. };
  5237. return DirectionalLight;
  5238. })(BABYLON.Light);
  5239. BABYLON.DirectionalLight = DirectionalLight;
  5240. })(BABYLON || (BABYLON = {}));
  5241. //# sourceMappingURL=babylon.directionalLight.js.map
  5242. var BABYLON;
  5243. (function (BABYLON) {
  5244. var ShadowGenerator = (function () {
  5245. function ShadowGenerator(mapSize, light) {
  5246. var _this = this;
  5247. // Members
  5248. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5249. this._darkness = 0;
  5250. this._transparencyShadow = false;
  5251. this._viewMatrix = BABYLON.Matrix.Zero();
  5252. this._projectionMatrix = BABYLON.Matrix.Zero();
  5253. this._transformMatrix = BABYLON.Matrix.Zero();
  5254. this._worldViewProjection = BABYLON.Matrix.Zero();
  5255. this._light = light;
  5256. this._scene = light.getScene();
  5257. light._shadowGenerator = this;
  5258. // Render target
  5259. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5260. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5261. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5262. this._shadowMap.renderParticles = false;
  5263. // Custom render function
  5264. var renderSubMesh = function (subMesh) {
  5265. var mesh = subMesh.getRenderingMesh();
  5266. var scene = _this._scene;
  5267. var engine = scene.getEngine();
  5268. // Culling
  5269. engine.setState(subMesh.getMaterial().backFaceCulling);
  5270. // Managing instances
  5271. var batch = mesh._getInstancesRenderList(subMesh._id);
  5272. if (batch.mustReturn) {
  5273. return;
  5274. }
  5275. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5276. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5277. engine.enableEffect(_this._effect);
  5278. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5279. var material = subMesh.getMaterial();
  5280. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5281. // Alpha test
  5282. if (material && material.needAlphaTesting()) {
  5283. var alphaTexture = material.getAlphaTestTexture();
  5284. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5285. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5286. }
  5287. // Bones
  5288. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5289. if (useBones) {
  5290. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5291. }
  5292. if (hardwareInstancedRendering) {
  5293. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5294. } else {
  5295. if (batch.renderSelf[subMesh._id]) {
  5296. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5297. // Draw
  5298. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5299. }
  5300. if (batch.visibleInstances[subMesh._id]) {
  5301. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5302. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5303. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5304. // Draw
  5305. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5306. }
  5307. }
  5308. }
  5309. } else {
  5310. // Need to reset refresh rate of the shadowMap
  5311. _this._shadowMap.resetRefreshCounter();
  5312. }
  5313. };
  5314. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5315. var index;
  5316. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5317. renderSubMesh(opaqueSubMeshes.data[index]);
  5318. }
  5319. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5320. renderSubMesh(alphaTestSubMeshes.data[index]);
  5321. }
  5322. if (_this._transparencyShadow) {
  5323. for (index = 0; index < transparentSubMeshes.length; index++) {
  5324. renderSubMesh(transparentSubMeshes.data[index]);
  5325. }
  5326. }
  5327. };
  5328. }
  5329. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5330. // Static
  5331. get: function () {
  5332. return ShadowGenerator._FILTER_NONE;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5338. get: function () {
  5339. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5345. get: function () {
  5346. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5352. get: function () {
  5353. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5354. },
  5355. set: function (value) {
  5356. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5357. },
  5358. enumerable: true,
  5359. configurable: true
  5360. });
  5361. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5362. get: function () {
  5363. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5364. },
  5365. set: function (value) {
  5366. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5367. },
  5368. enumerable: true,
  5369. configurable: true
  5370. });
  5371. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5372. var defines = [];
  5373. if (this.useVarianceShadowMap) {
  5374. defines.push("#define VSM");
  5375. }
  5376. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5377. var mesh = subMesh.getMesh();
  5378. var scene = mesh.getScene();
  5379. var material = subMesh.getMaterial();
  5380. // Alpha test
  5381. if (material && material.needAlphaTesting()) {
  5382. defines.push("#define ALPHATEST");
  5383. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5384. attribs.push(BABYLON.VertexBuffer.UVKind);
  5385. defines.push("#define UV1");
  5386. }
  5387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5389. defines.push("#define UV2");
  5390. }
  5391. }
  5392. // Bones
  5393. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5396. defines.push("#define BONES");
  5397. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5398. }
  5399. // Instances
  5400. if (useInstances) {
  5401. defines.push("#define INSTANCES");
  5402. attribs.push("world0");
  5403. attribs.push("world1");
  5404. attribs.push("world2");
  5405. attribs.push("world3");
  5406. }
  5407. // Get correct effect
  5408. var join = defines.join("\n");
  5409. if (this._cachedDefines != join) {
  5410. this._cachedDefines = join;
  5411. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5412. }
  5413. return this._effect.isReady();
  5414. };
  5415. ShadowGenerator.prototype.getShadowMap = function () {
  5416. return this._shadowMap;
  5417. };
  5418. ShadowGenerator.prototype.getLight = function () {
  5419. return this._light;
  5420. };
  5421. // Methods
  5422. ShadowGenerator.prototype.getTransformMatrix = function () {
  5423. var lightPosition = this._light.position;
  5424. var lightDirection = this._light.direction;
  5425. if (this._light._computeTransformedPosition()) {
  5426. lightPosition = this._light._transformedPosition;
  5427. }
  5428. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5429. this._cachedPosition = lightPosition.clone();
  5430. this._cachedDirection = lightDirection.clone();
  5431. var activeCamera = this._scene.activeCamera;
  5432. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5433. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5434. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5435. }
  5436. return this._transformMatrix;
  5437. };
  5438. ShadowGenerator.prototype.getDarkness = function () {
  5439. return this._darkness;
  5440. };
  5441. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5442. if (darkness >= 1.0)
  5443. this._darkness = 1.0;
  5444. else if (darkness <= 0.0)
  5445. this._darkness = 0.0;
  5446. else
  5447. this._darkness = darkness;
  5448. };
  5449. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5450. this._transparencyShadow = hasShadow;
  5451. };
  5452. ShadowGenerator.prototype.dispose = function () {
  5453. this._shadowMap.dispose();
  5454. };
  5455. ShadowGenerator._FILTER_NONE = 0;
  5456. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5457. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5458. return ShadowGenerator;
  5459. })();
  5460. BABYLON.ShadowGenerator = ShadowGenerator;
  5461. })(BABYLON || (BABYLON = {}));
  5462. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5463. var BABYLON;
  5464. (function (BABYLON) {
  5465. var HemisphericLight = (function (_super) {
  5466. __extends(HemisphericLight, _super);
  5467. function HemisphericLight(name, direction, scene) {
  5468. _super.call(this, name, scene);
  5469. this.direction = direction;
  5470. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5471. }
  5472. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5473. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5474. return this.direction;
  5475. };
  5476. HemisphericLight.prototype.getShadowGenerator = function () {
  5477. return null;
  5478. };
  5479. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5480. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5481. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5482. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5483. };
  5484. HemisphericLight.prototype._getWorldMatrix = function () {
  5485. if (!this._worldMatrix) {
  5486. this._worldMatrix = BABYLON.Matrix.Identity();
  5487. }
  5488. return this._worldMatrix;
  5489. };
  5490. return HemisphericLight;
  5491. })(BABYLON.Light);
  5492. BABYLON.HemisphericLight = HemisphericLight;
  5493. })(BABYLON || (BABYLON = {}));
  5494. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5495. var BABYLON;
  5496. (function (BABYLON) {
  5497. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5498. if (boxMin.x > sphereCenter.x + sphereRadius)
  5499. return false;
  5500. if (sphereCenter.x - sphereRadius > boxMax.x)
  5501. return false;
  5502. if (boxMin.y > sphereCenter.y + sphereRadius)
  5503. return false;
  5504. if (sphereCenter.y - sphereRadius > boxMax.y)
  5505. return false;
  5506. if (boxMin.z > sphereCenter.z + sphereRadius)
  5507. return false;
  5508. if (sphereCenter.z - sphereRadius > boxMax.z)
  5509. return false;
  5510. return true;
  5511. };
  5512. var getLowestRoot = function (a, b, c, maxR) {
  5513. var determinant = b * b - 4.0 * a * c;
  5514. var result = { root: 0, found: false };
  5515. if (determinant < 0)
  5516. return result;
  5517. var sqrtD = Math.sqrt(determinant);
  5518. var r1 = (-b - sqrtD) / (2.0 * a);
  5519. var r2 = (-b + sqrtD) / (2.0 * a);
  5520. if (r1 > r2) {
  5521. var temp = r2;
  5522. r2 = r1;
  5523. r1 = temp;
  5524. }
  5525. if (r1 > 0 && r1 < maxR) {
  5526. result.root = r1;
  5527. result.found = true;
  5528. return result;
  5529. }
  5530. if (r2 > 0 && r2 < maxR) {
  5531. result.root = r2;
  5532. result.found = true;
  5533. return result;
  5534. }
  5535. return result;
  5536. };
  5537. var Collider = (function () {
  5538. function Collider() {
  5539. this.radius = new BABYLON.Vector3(1, 1, 1);
  5540. this.retry = 0;
  5541. this.basePointWorld = BABYLON.Vector3.Zero();
  5542. this.velocityWorld = BABYLON.Vector3.Zero();
  5543. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5544. this._collisionPoint = BABYLON.Vector3.Zero();
  5545. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5546. this._tempVector = BABYLON.Vector3.Zero();
  5547. this._tempVector2 = BABYLON.Vector3.Zero();
  5548. this._tempVector3 = BABYLON.Vector3.Zero();
  5549. this._tempVector4 = BABYLON.Vector3.Zero();
  5550. this._edge = BABYLON.Vector3.Zero();
  5551. this._baseToVertex = BABYLON.Vector3.Zero();
  5552. this._destinationPoint = BABYLON.Vector3.Zero();
  5553. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5554. this._displacementVector = BABYLON.Vector3.Zero();
  5555. }
  5556. // Methods
  5557. Collider.prototype._initialize = function (source, dir, e) {
  5558. this.velocity = dir;
  5559. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5560. this.basePoint = source;
  5561. source.multiplyToRef(this.radius, this.basePointWorld);
  5562. dir.multiplyToRef(this.radius, this.velocityWorld);
  5563. this.velocityWorldLength = this.velocityWorld.length();
  5564. this.epsilon = e;
  5565. this.collisionFound = false;
  5566. };
  5567. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5568. pa.subtractToRef(point, this._tempVector);
  5569. pb.subtractToRef(point, this._tempVector2);
  5570. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5571. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5572. if (d < 0)
  5573. return false;
  5574. pc.subtractToRef(point, this._tempVector3);
  5575. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5576. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5577. if (d < 0)
  5578. return false;
  5579. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5580. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5581. return d >= 0;
  5582. };
  5583. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5584. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5585. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5586. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5587. return false;
  5588. }
  5589. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5590. return false;
  5591. return true;
  5592. };
  5593. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5594. var t0;
  5595. var embeddedInPlane = false;
  5596. if (!subMesh._trianglePlanes) {
  5597. subMesh._trianglePlanes = [];
  5598. }
  5599. if (!subMesh._trianglePlanes[faceIndex]) {
  5600. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5601. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5602. }
  5603. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5604. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5605. return;
  5606. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5607. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5608. if (normalDotVelocity == 0) {
  5609. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5610. return;
  5611. embeddedInPlane = true;
  5612. t0 = 0;
  5613. } else {
  5614. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5615. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5616. if (t0 > t1) {
  5617. var temp = t1;
  5618. t1 = t0;
  5619. t0 = temp;
  5620. }
  5621. if (t0 > 1.0 || t1 < 0.0)
  5622. return;
  5623. if (t0 < 0)
  5624. t0 = 0;
  5625. if (t0 > 1.0)
  5626. t0 = 1.0;
  5627. }
  5628. this._collisionPoint.copyFromFloats(0, 0, 0);
  5629. var found = false;
  5630. var t = 1.0;
  5631. if (!embeddedInPlane) {
  5632. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5633. this.velocity.scaleToRef(t0, this._tempVector);
  5634. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5635. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5636. found = true;
  5637. t = t0;
  5638. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5639. }
  5640. }
  5641. if (!found) {
  5642. var velocitySquaredLength = this.velocity.lengthSquared();
  5643. var a = velocitySquaredLength;
  5644. this.basePoint.subtractToRef(p1, this._tempVector);
  5645. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5646. var c = this._tempVector.lengthSquared() - 1.0;
  5647. var lowestRoot = getLowestRoot(a, b, c, t);
  5648. if (lowestRoot.found) {
  5649. t = lowestRoot.root;
  5650. found = true;
  5651. this._collisionPoint.copyFrom(p1);
  5652. }
  5653. this.basePoint.subtractToRef(p2, this._tempVector);
  5654. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5655. c = this._tempVector.lengthSquared() - 1.0;
  5656. lowestRoot = getLowestRoot(a, b, c, t);
  5657. if (lowestRoot.found) {
  5658. t = lowestRoot.root;
  5659. found = true;
  5660. this._collisionPoint.copyFrom(p2);
  5661. }
  5662. this.basePoint.subtractToRef(p3, this._tempVector);
  5663. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5664. c = this._tempVector.lengthSquared() - 1.0;
  5665. lowestRoot = getLowestRoot(a, b, c, t);
  5666. if (lowestRoot.found) {
  5667. t = lowestRoot.root;
  5668. found = true;
  5669. this._collisionPoint.copyFrom(p3);
  5670. }
  5671. p2.subtractToRef(p1, this._edge);
  5672. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5673. var edgeSquaredLength = this._edge.lengthSquared();
  5674. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5675. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5676. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5677. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5678. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5679. lowestRoot = getLowestRoot(a, b, c, t);
  5680. if (lowestRoot.found) {
  5681. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5682. if (f >= 0.0 && f <= 1.0) {
  5683. t = lowestRoot.root;
  5684. found = true;
  5685. this._edge.scaleInPlace(f);
  5686. p1.addToRef(this._edge, this._collisionPoint);
  5687. }
  5688. }
  5689. p3.subtractToRef(p2, this._edge);
  5690. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5691. edgeSquaredLength = this._edge.lengthSquared();
  5692. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5693. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5694. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5695. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5696. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5697. lowestRoot = getLowestRoot(a, b, c, t);
  5698. if (lowestRoot.found) {
  5699. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5700. if (f >= 0.0 && f <= 1.0) {
  5701. t = lowestRoot.root;
  5702. found = true;
  5703. this._edge.scaleInPlace(f);
  5704. p2.addToRef(this._edge, this._collisionPoint);
  5705. }
  5706. }
  5707. p1.subtractToRef(p3, this._edge);
  5708. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5709. edgeSquaredLength = this._edge.lengthSquared();
  5710. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5711. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5712. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5713. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5714. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5715. lowestRoot = getLowestRoot(a, b, c, t);
  5716. if (lowestRoot.found) {
  5717. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5718. if (f >= 0.0 && f <= 1.0) {
  5719. t = lowestRoot.root;
  5720. found = true;
  5721. this._edge.scaleInPlace(f);
  5722. p3.addToRef(this._edge, this._collisionPoint);
  5723. }
  5724. }
  5725. }
  5726. if (found) {
  5727. var distToCollision = t * this.velocity.length();
  5728. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5729. if (!this.intersectionPoint) {
  5730. this.intersectionPoint = this._collisionPoint.clone();
  5731. } else {
  5732. this.intersectionPoint.copyFrom(this._collisionPoint);
  5733. }
  5734. this.nearestDistance = distToCollision;
  5735. this.collisionFound = true;
  5736. this.collidedMesh = subMesh.getMesh();
  5737. }
  5738. }
  5739. };
  5740. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5741. for (var i = indexStart; i < indexEnd; i += 3) {
  5742. var p1 = pts[indices[i] - decal];
  5743. var p2 = pts[indices[i + 1] - decal];
  5744. var p3 = pts[indices[i + 2] - decal];
  5745. this._testTriangle(i, subMesh, p3, p2, p1);
  5746. }
  5747. };
  5748. Collider.prototype._getResponse = function (pos, vel) {
  5749. pos.addToRef(vel, this._destinationPoint);
  5750. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5751. this.basePoint.addToRef(vel, pos);
  5752. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5753. this._slidePlaneNormal.normalize();
  5754. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5755. pos.addInPlace(this._displacementVector);
  5756. this.intersectionPoint.addInPlace(this._displacementVector);
  5757. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5758. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5759. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5760. };
  5761. return Collider;
  5762. })();
  5763. BABYLON.Collider = Collider;
  5764. })(BABYLON || (BABYLON = {}));
  5765. //# sourceMappingURL=babylon.collider.js.map
  5766. var BABYLON;
  5767. (function (BABYLON) {
  5768. var Camera = (function (_super) {
  5769. __extends(Camera, _super);
  5770. function Camera(name, position, scene) {
  5771. _super.call(this, name, scene);
  5772. this.position = position;
  5773. // Members
  5774. this.upVector = BABYLON.Vector3.Up();
  5775. this.orthoLeft = null;
  5776. this.orthoRight = null;
  5777. this.orthoBottom = null;
  5778. this.orthoTop = null;
  5779. this.fov = 0.8;
  5780. this.minZ = 1.0;
  5781. this.maxZ = 10000.0;
  5782. this.inertia = 0.9;
  5783. this.mode = Camera.PERSPECTIVE_CAMERA;
  5784. this.isIntermediate = false;
  5785. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5786. this.subCameras = [];
  5787. this.layerMask = 0xFFFFFFFF;
  5788. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5789. this._projectionMatrix = new BABYLON.Matrix();
  5790. this._postProcesses = new Array();
  5791. this._postProcessesTakenIndices = [];
  5792. scene.cameras.push(this);
  5793. if (!scene.activeCamera) {
  5794. scene.activeCamera = this;
  5795. }
  5796. }
  5797. //Cache
  5798. Camera.prototype._initCache = function () {
  5799. _super.prototype._initCache.call(this);
  5800. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5801. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5802. this._cache.mode = undefined;
  5803. this._cache.minZ = undefined;
  5804. this._cache.maxZ = undefined;
  5805. this._cache.fov = undefined;
  5806. this._cache.aspectRatio = undefined;
  5807. this._cache.orthoLeft = undefined;
  5808. this._cache.orthoRight = undefined;
  5809. this._cache.orthoBottom = undefined;
  5810. this._cache.orthoTop = undefined;
  5811. this._cache.renderWidth = undefined;
  5812. this._cache.renderHeight = undefined;
  5813. };
  5814. Camera.prototype._updateCache = function (ignoreParentClass) {
  5815. if (!ignoreParentClass) {
  5816. _super.prototype._updateCache.call(this);
  5817. }
  5818. var engine = this.getEngine();
  5819. this._cache.position.copyFrom(this.position);
  5820. this._cache.upVector.copyFrom(this.upVector);
  5821. this._cache.mode = this.mode;
  5822. this._cache.minZ = this.minZ;
  5823. this._cache.maxZ = this.maxZ;
  5824. this._cache.fov = this.fov;
  5825. this._cache.aspectRatio = engine.getAspectRatio(this);
  5826. this._cache.orthoLeft = this.orthoLeft;
  5827. this._cache.orthoRight = this.orthoRight;
  5828. this._cache.orthoBottom = this.orthoBottom;
  5829. this._cache.orthoTop = this.orthoTop;
  5830. this._cache.renderWidth = engine.getRenderWidth();
  5831. this._cache.renderHeight = engine.getRenderHeight();
  5832. };
  5833. Camera.prototype._updateFromScene = function () {
  5834. this.updateCache();
  5835. this._update();
  5836. };
  5837. // Synchronized
  5838. Camera.prototype._isSynchronized = function () {
  5839. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5840. };
  5841. Camera.prototype._isSynchronizedViewMatrix = function () {
  5842. if (!_super.prototype._isSynchronized.call(this))
  5843. return false;
  5844. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5845. };
  5846. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5847. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5848. if (!check) {
  5849. return false;
  5850. }
  5851. var engine = this.getEngine();
  5852. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5853. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5854. } else {
  5855. 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();
  5856. }
  5857. return check;
  5858. };
  5859. // Controls
  5860. Camera.prototype.attachControl = function (element) {
  5861. };
  5862. Camera.prototype.detachControl = function (element) {
  5863. };
  5864. Camera.prototype._update = function () {
  5865. };
  5866. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5867. if (typeof insertAt === "undefined") { insertAt = null; }
  5868. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5869. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5870. return 0;
  5871. }
  5872. if (insertAt == null || insertAt < 0) {
  5873. this._postProcesses.push(postProcess);
  5874. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5875. return this._postProcesses.length - 1;
  5876. }
  5877. var add = 0;
  5878. if (this._postProcesses[insertAt]) {
  5879. var start = this._postProcesses.length - 1;
  5880. for (var i = start; i >= insertAt + 1; --i) {
  5881. this._postProcesses[i + 1] = this._postProcesses[i];
  5882. }
  5883. add = 1;
  5884. }
  5885. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5886. if (this._postProcessesTakenIndices[i] < insertAt) {
  5887. continue;
  5888. }
  5889. start = this._postProcessesTakenIndices.length - 1;
  5890. for (var j = start; j >= i; --j) {
  5891. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5892. }
  5893. this._postProcessesTakenIndices[i] = insertAt;
  5894. break;
  5895. }
  5896. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5897. this._postProcessesTakenIndices.push(insertAt);
  5898. }
  5899. var result = insertAt + add;
  5900. this._postProcesses[result] = postProcess;
  5901. return result;
  5902. };
  5903. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5904. if (typeof atIndices === "undefined") { atIndices = null; }
  5905. var result = [];
  5906. if (!atIndices) {
  5907. var length = this._postProcesses.length;
  5908. for (var i = 0; i < length; i++) {
  5909. if (this._postProcesses[i] !== postProcess) {
  5910. continue;
  5911. }
  5912. delete this._postProcesses[i];
  5913. var index = this._postProcessesTakenIndices.indexOf(i);
  5914. this._postProcessesTakenIndices.splice(index, 1);
  5915. }
  5916. } else {
  5917. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5918. for (i = 0; i < atIndices.length; i++) {
  5919. var foundPostProcess = this._postProcesses[atIndices[i]];
  5920. if (foundPostProcess !== postProcess) {
  5921. result.push(i);
  5922. continue;
  5923. }
  5924. delete this._postProcesses[atIndices[i]];
  5925. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5926. this._postProcessesTakenIndices.splice(index, 1);
  5927. }
  5928. }
  5929. return result;
  5930. };
  5931. Camera.prototype.getWorldMatrix = function () {
  5932. if (!this._worldMatrix) {
  5933. this._worldMatrix = BABYLON.Matrix.Identity();
  5934. }
  5935. var viewMatrix = this.getViewMatrix();
  5936. viewMatrix.invertToRef(this._worldMatrix);
  5937. return this._worldMatrix;
  5938. };
  5939. Camera.prototype._getViewMatrix = function () {
  5940. return BABYLON.Matrix.Identity();
  5941. };
  5942. Camera.prototype.getViewMatrix = function () {
  5943. this._computedViewMatrix = this._computeViewMatrix();
  5944. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5945. return this._computedViewMatrix;
  5946. }
  5947. if (!this._worldMatrix) {
  5948. this._worldMatrix = BABYLON.Matrix.Identity();
  5949. }
  5950. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5951. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5952. this._computedViewMatrix.invert();
  5953. this._currentRenderId = this.getScene().getRenderId();
  5954. return this._computedViewMatrix;
  5955. };
  5956. Camera.prototype._computeViewMatrix = function (force) {
  5957. if (!force && this._isSynchronizedViewMatrix()) {
  5958. return this._computedViewMatrix;
  5959. }
  5960. this._computedViewMatrix = this._getViewMatrix();
  5961. if (!this.parent || !this.parent.getWorldMatrix) {
  5962. this._currentRenderId = this.getScene().getRenderId();
  5963. }
  5964. return this._computedViewMatrix;
  5965. };
  5966. Camera.prototype.getProjectionMatrix = function (force) {
  5967. if (!force && this._isSynchronizedProjectionMatrix()) {
  5968. return this._projectionMatrix;
  5969. }
  5970. var engine = this.getEngine();
  5971. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5972. if (this.minZ <= 0) {
  5973. this.minZ = 0.1;
  5974. }
  5975. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5976. return this._projectionMatrix;
  5977. }
  5978. var halfWidth = engine.getRenderWidth() / 2.0;
  5979. var halfHeight = engine.getRenderHeight() / 2.0;
  5980. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5981. return this._projectionMatrix;
  5982. };
  5983. Camera.prototype.dispose = function () {
  5984. // Remove from scene
  5985. var index = this.getScene().cameras.indexOf(this);
  5986. this.getScene().cameras.splice(index, 1);
  5987. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5988. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5989. }
  5990. };
  5991. Camera.PERSPECTIVE_CAMERA = 0;
  5992. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5993. return Camera;
  5994. })(BABYLON.Node);
  5995. BABYLON.Camera = Camera;
  5996. })(BABYLON || (BABYLON = {}));
  5997. //# sourceMappingURL=babylon.camera.js.map
  5998. var BABYLON;
  5999. (function (BABYLON) {
  6000. var TargetCamera = (function (_super) {
  6001. __extends(TargetCamera, _super);
  6002. function TargetCamera(name, position, scene) {
  6003. _super.call(this, name, position, scene);
  6004. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6005. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6006. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6007. this.speed = 2.0;
  6008. this.noRotationConstraint = false;
  6009. this.lockedTarget = null;
  6010. this._currentTarget = BABYLON.Vector3.Zero();
  6011. this._viewMatrix = BABYLON.Matrix.Zero();
  6012. this._camMatrix = BABYLON.Matrix.Zero();
  6013. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6014. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6015. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6016. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6017. this._lookAtTemp = BABYLON.Matrix.Zero();
  6018. this._tempMatrix = BABYLON.Matrix.Zero();
  6019. }
  6020. TargetCamera.prototype._getLockedTargetPosition = function () {
  6021. if (!this.lockedTarget) {
  6022. return null;
  6023. }
  6024. return this.lockedTarget.position || this.lockedTarget;
  6025. };
  6026. // Cache
  6027. TargetCamera.prototype._initCache = function () {
  6028. _super.prototype._initCache.call(this);
  6029. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6030. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6031. };
  6032. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6033. if (!ignoreParentClass) {
  6034. _super.prototype._updateCache.call(this);
  6035. }
  6036. var lockedTargetPosition = this._getLockedTargetPosition();
  6037. if (!lockedTargetPosition) {
  6038. this._cache.lockedTarget = null;
  6039. } else {
  6040. if (!this._cache.lockedTarget) {
  6041. this._cache.lockedTarget = lockedTargetPosition.clone();
  6042. } else {
  6043. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6044. }
  6045. }
  6046. this._cache.rotation.copyFrom(this.rotation);
  6047. };
  6048. // Synchronized
  6049. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6050. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6051. return false;
  6052. }
  6053. var lockedTargetPosition = this._getLockedTargetPosition();
  6054. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6055. };
  6056. // Methods
  6057. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6058. var engine = this.getEngine();
  6059. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6060. };
  6061. // Target
  6062. TargetCamera.prototype.setTarget = function (target) {
  6063. this.upVector.normalize();
  6064. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6065. this._camMatrix.invert();
  6066. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6067. var vDir = target.subtract(this.position);
  6068. if (vDir.x >= 0.0) {
  6069. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6070. } else {
  6071. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6072. }
  6073. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6074. if (isNaN(this.rotation.x)) {
  6075. this.rotation.x = 0;
  6076. }
  6077. if (isNaN(this.rotation.y)) {
  6078. this.rotation.y = 0;
  6079. }
  6080. if (isNaN(this.rotation.z)) {
  6081. this.rotation.z = 0;
  6082. }
  6083. };
  6084. TargetCamera.prototype.getTarget = function () {
  6085. return this._currentTarget;
  6086. };
  6087. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6088. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6089. };
  6090. TargetCamera.prototype._updatePosition = function () {
  6091. this.position.addInPlace(this.cameraDirection);
  6092. };
  6093. TargetCamera.prototype._update = function () {
  6094. var needToMove = this._decideIfNeedsToMove();
  6095. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6096. // Move
  6097. if (needToMove) {
  6098. this._updatePosition();
  6099. }
  6100. // Rotate
  6101. if (needToRotate) {
  6102. this.rotation.x += this.cameraRotation.x;
  6103. this.rotation.y += this.cameraRotation.y;
  6104. if (!this.noRotationConstraint) {
  6105. var limit = (Math.PI / 2) * 0.95;
  6106. if (this.rotation.x > limit)
  6107. this.rotation.x = limit;
  6108. if (this.rotation.x < -limit)
  6109. this.rotation.x = -limit;
  6110. }
  6111. }
  6112. // Inertia
  6113. if (needToMove) {
  6114. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6115. this.cameraDirection.x = 0;
  6116. }
  6117. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6118. this.cameraDirection.y = 0;
  6119. }
  6120. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6121. this.cameraDirection.z = 0;
  6122. }
  6123. this.cameraDirection.scaleInPlace(this.inertia);
  6124. }
  6125. if (needToRotate) {
  6126. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6127. this.cameraRotation.x = 0;
  6128. }
  6129. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6130. this.cameraRotation.y = 0;
  6131. }
  6132. this.cameraRotation.scaleInPlace(this.inertia);
  6133. }
  6134. };
  6135. TargetCamera.prototype._getViewMatrix = function () {
  6136. if (!this.lockedTarget) {
  6137. // Compute
  6138. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6139. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6140. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6141. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6142. this._lookAtTemp.invert();
  6143. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6144. } else {
  6145. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6146. }
  6147. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6148. // Computing target and final matrix
  6149. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6150. } else {
  6151. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6152. }
  6153. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6154. return this._viewMatrix;
  6155. };
  6156. return TargetCamera;
  6157. })(BABYLON.Camera);
  6158. BABYLON.TargetCamera = TargetCamera;
  6159. })(BABYLON || (BABYLON = {}));
  6160. //# sourceMappingURL=babylon.targetCamera.js.map
  6161. var BABYLON;
  6162. (function (BABYLON) {
  6163. var FollowCamera = (function (_super) {
  6164. __extends(FollowCamera, _super);
  6165. function FollowCamera(name, position, scene) {
  6166. _super.call(this, name, position, scene);
  6167. this.radius = 12;
  6168. this.rotationOffset = 0;
  6169. this.heightOffset = 4;
  6170. this.cameraAcceleration = 0.05;
  6171. this.maxCameraSpeed = 20;
  6172. }
  6173. FollowCamera.prototype.getRadians = function (degrees) {
  6174. return degrees * Math.PI / 180;
  6175. };
  6176. FollowCamera.prototype.follow = function (cameraTarget) {
  6177. if (!cameraTarget)
  6178. return;
  6179. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6180. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6181. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6182. var dx = targetX - this.position.x;
  6183. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6184. var dz = (targetZ) - this.position.z;
  6185. var vx = dx * this.cameraAcceleration * 2;
  6186. var vy = dy * this.cameraAcceleration;
  6187. var vz = dz * this.cameraAcceleration * 2;
  6188. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6189. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6190. }
  6191. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6192. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6193. }
  6194. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6195. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6196. }
  6197. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6198. this.setTarget(cameraTarget.position);
  6199. };
  6200. FollowCamera.prototype._update = function () {
  6201. _super.prototype._update.call(this);
  6202. this.follow(this.target);
  6203. };
  6204. return FollowCamera;
  6205. })(BABYLON.TargetCamera);
  6206. BABYLON.FollowCamera = FollowCamera;
  6207. })(BABYLON || (BABYLON = {}));
  6208. //# sourceMappingURL=babylon.followCamera.js.map
  6209. var BABYLON;
  6210. (function (BABYLON) {
  6211. var FreeCamera = (function (_super) {
  6212. __extends(FreeCamera, _super);
  6213. function FreeCamera(name, position, scene) {
  6214. _super.call(this, name, position, scene);
  6215. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6216. this.keysUp = [38];
  6217. this.keysDown = [40];
  6218. this.keysLeft = [37];
  6219. this.keysRight = [39];
  6220. this.checkCollisions = false;
  6221. this.applyGravity = false;
  6222. this.angularSensibility = 2000.0;
  6223. this._keys = [];
  6224. this._collider = new BABYLON.Collider();
  6225. this._needMoveForGravity = true;
  6226. this._oldPosition = BABYLON.Vector3.Zero();
  6227. this._diffPosition = BABYLON.Vector3.Zero();
  6228. this._newPosition = BABYLON.Vector3.Zero();
  6229. }
  6230. // Controls
  6231. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6232. var _this = this;
  6233. var previousPosition;
  6234. var engine = this.getEngine();
  6235. if (this._attachedElement) {
  6236. return;
  6237. }
  6238. this._attachedElement = element;
  6239. if (this._onMouseDown === undefined) {
  6240. this._onMouseDown = function (evt) {
  6241. previousPosition = {
  6242. x: evt.clientX,
  6243. y: evt.clientY
  6244. };
  6245. if (!noPreventDefault) {
  6246. evt.preventDefault();
  6247. }
  6248. };
  6249. this._onMouseUp = function (evt) {
  6250. previousPosition = null;
  6251. if (!noPreventDefault) {
  6252. evt.preventDefault();
  6253. }
  6254. };
  6255. this._onMouseOut = function (evt) {
  6256. previousPosition = null;
  6257. _this._keys = [];
  6258. if (!noPreventDefault) {
  6259. evt.preventDefault();
  6260. }
  6261. };
  6262. this._onMouseMove = function (evt) {
  6263. if (!previousPosition && !engine.isPointerLock) {
  6264. return;
  6265. }
  6266. var offsetX;
  6267. var offsetY;
  6268. if (!engine.isPointerLock) {
  6269. offsetX = evt.clientX - previousPosition.x;
  6270. offsetY = evt.clientY - previousPosition.y;
  6271. } else {
  6272. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6273. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6274. }
  6275. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6276. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6277. previousPosition = {
  6278. x: evt.clientX,
  6279. y: evt.clientY
  6280. };
  6281. if (!noPreventDefault) {
  6282. evt.preventDefault();
  6283. }
  6284. };
  6285. this._onKeyDown = function (evt) {
  6286. 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) {
  6287. var index = _this._keys.indexOf(evt.keyCode);
  6288. if (index === -1) {
  6289. _this._keys.push(evt.keyCode);
  6290. }
  6291. if (!noPreventDefault) {
  6292. evt.preventDefault();
  6293. }
  6294. }
  6295. };
  6296. this._onKeyUp = function (evt) {
  6297. 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) {
  6298. var index = _this._keys.indexOf(evt.keyCode);
  6299. if (index >= 0) {
  6300. _this._keys.splice(index, 1);
  6301. }
  6302. if (!noPreventDefault) {
  6303. evt.preventDefault();
  6304. }
  6305. }
  6306. };
  6307. this._onLostFocus = function () {
  6308. _this._keys = [];
  6309. };
  6310. this._reset = function () {
  6311. _this._keys = [];
  6312. previousPosition = null;
  6313. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6314. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6315. };
  6316. }
  6317. element.addEventListener("mousedown", this._onMouseDown, false);
  6318. element.addEventListener("mouseup", this._onMouseUp, false);
  6319. element.addEventListener("mouseout", this._onMouseOut, false);
  6320. element.addEventListener("mousemove", this._onMouseMove, false);
  6321. BABYLON.Tools.RegisterTopRootEvents([
  6322. { name: "keydown", handler: this._onKeyDown },
  6323. { name: "keyup", handler: this._onKeyUp },
  6324. { name: "blur", handler: this._onLostFocus }
  6325. ]);
  6326. };
  6327. FreeCamera.prototype.detachControl = function (element) {
  6328. if (this._attachedElement != element) {
  6329. return;
  6330. }
  6331. element.removeEventListener("mousedown", this._onMouseDown);
  6332. element.removeEventListener("mouseup", this._onMouseUp);
  6333. element.removeEventListener("mouseout", this._onMouseOut);
  6334. element.removeEventListener("mousemove", this._onMouseMove);
  6335. BABYLON.Tools.UnregisterTopRootEvents([
  6336. { name: "keydown", handler: this._onKeyDown },
  6337. { name: "keyup", handler: this._onKeyUp },
  6338. { name: "blur", handler: this._onLostFocus }
  6339. ]);
  6340. this._attachedElement = null;
  6341. if (this._reset) {
  6342. this._reset();
  6343. }
  6344. };
  6345. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6346. var globalPosition;
  6347. if (this.parent) {
  6348. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6349. } else {
  6350. globalPosition = this.position;
  6351. }
  6352. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6353. this._collider.radius = this.ellipsoid;
  6354. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6355. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6356. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6357. this.position.addInPlace(this._diffPosition);
  6358. if (this.onCollide) {
  6359. this.onCollide(this._collider.collidedMesh);
  6360. }
  6361. }
  6362. };
  6363. FreeCamera.prototype._checkInputs = function () {
  6364. if (!this._localDirection) {
  6365. this._localDirection = BABYLON.Vector3.Zero();
  6366. this._transformedDirection = BABYLON.Vector3.Zero();
  6367. }
  6368. for (var index = 0; index < this._keys.length; index++) {
  6369. var keyCode = this._keys[index];
  6370. var speed = this._computeLocalCameraSpeed();
  6371. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6372. this._localDirection.copyFromFloats(-speed, 0, 0);
  6373. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6374. this._localDirection.copyFromFloats(0, 0, speed);
  6375. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6376. this._localDirection.copyFromFloats(speed, 0, 0);
  6377. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6378. this._localDirection.copyFromFloats(0, 0, -speed);
  6379. }
  6380. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6381. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6382. this.cameraDirection.addInPlace(this._transformedDirection);
  6383. }
  6384. };
  6385. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6386. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6387. };
  6388. FreeCamera.prototype._updatePosition = function () {
  6389. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6390. this._collideWithWorld(this.cameraDirection);
  6391. if (this.applyGravity) {
  6392. var oldPosition = this.position;
  6393. this._collideWithWorld(this.getScene().gravity);
  6394. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6395. }
  6396. } else {
  6397. this.position.addInPlace(this.cameraDirection);
  6398. }
  6399. };
  6400. FreeCamera.prototype._update = function () {
  6401. this._checkInputs();
  6402. _super.prototype._update.call(this);
  6403. };
  6404. return FreeCamera;
  6405. })(BABYLON.TargetCamera);
  6406. BABYLON.FreeCamera = FreeCamera;
  6407. })(BABYLON || (BABYLON = {}));
  6408. //# sourceMappingURL=babylon.freeCamera.js.map
  6409. var BABYLON;
  6410. (function (BABYLON) {
  6411. // We're mainly based on the logic defined into the FreeCamera code
  6412. var TouchCamera = (function (_super) {
  6413. __extends(TouchCamera, _super);
  6414. function TouchCamera(name, position, scene) {
  6415. _super.call(this, name, position, scene);
  6416. this._offsetX = null;
  6417. this._offsetY = null;
  6418. this._pointerCount = 0;
  6419. this._pointerPressed = [];
  6420. this.angularSensibility = 200000.0;
  6421. this.moveSensibility = 500.0;
  6422. }
  6423. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6424. var _this = this;
  6425. var previousPosition;
  6426. if (this._attachedCanvas) {
  6427. return;
  6428. }
  6429. this._attachedCanvas = canvas;
  6430. if (this._onPointerDown === undefined) {
  6431. this._onPointerDown = function (evt) {
  6432. if (!noPreventDefault) {
  6433. evt.preventDefault();
  6434. }
  6435. _this._pointerPressed.push(evt.pointerId);
  6436. if (_this._pointerPressed.length !== 1) {
  6437. return;
  6438. }
  6439. previousPosition = {
  6440. x: evt.clientX,
  6441. y: evt.clientY
  6442. };
  6443. };
  6444. this._onPointerUp = function (evt) {
  6445. if (!noPreventDefault) {
  6446. evt.preventDefault();
  6447. }
  6448. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6449. if (index === -1) {
  6450. return;
  6451. }
  6452. _this._pointerPressed.splice(index, 1);
  6453. if (index != 0) {
  6454. return;
  6455. }
  6456. previousPosition = null;
  6457. _this._offsetX = null;
  6458. _this._offsetY = null;
  6459. };
  6460. this._onPointerMove = function (evt) {
  6461. if (!noPreventDefault) {
  6462. evt.preventDefault();
  6463. }
  6464. if (!previousPosition) {
  6465. return;
  6466. }
  6467. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6468. if (index != 0) {
  6469. return;
  6470. }
  6471. _this._offsetX = evt.clientX - previousPosition.x;
  6472. _this._offsetY = -(evt.clientY - previousPosition.y);
  6473. };
  6474. this._onLostFocus = function () {
  6475. _this._offsetX = null;
  6476. _this._offsetY = null;
  6477. };
  6478. }
  6479. canvas.addEventListener("pointerdown", this._onPointerDown);
  6480. canvas.addEventListener("pointerup", this._onPointerUp);
  6481. canvas.addEventListener("pointerout", this._onPointerUp);
  6482. canvas.addEventListener("pointermove", this._onPointerMove);
  6483. BABYLON.Tools.RegisterTopRootEvents([
  6484. { name: "blur", handler: this._onLostFocus }
  6485. ]);
  6486. };
  6487. TouchCamera.prototype.detachControl = function (canvas) {
  6488. if (this._attachedCanvas != canvas) {
  6489. return;
  6490. }
  6491. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6492. canvas.removeEventListener("pointerup", this._onPointerUp);
  6493. canvas.removeEventListener("pointerout", this._onPointerUp);
  6494. canvas.removeEventListener("pointermove", this._onPointerMove);
  6495. BABYLON.Tools.UnregisterTopRootEvents([
  6496. { name: "blur", handler: this._onLostFocus }
  6497. ]);
  6498. this._attachedCanvas = null;
  6499. };
  6500. TouchCamera.prototype._checkInputs = function () {
  6501. if (!this._offsetX) {
  6502. return;
  6503. }
  6504. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6505. if (this._pointerPressed.length > 1) {
  6506. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6507. } else {
  6508. var speed = this._computeLocalCameraSpeed();
  6509. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6510. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6511. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6512. }
  6513. };
  6514. return TouchCamera;
  6515. })(BABYLON.FreeCamera);
  6516. BABYLON.TouchCamera = TouchCamera;
  6517. })(BABYLON || (BABYLON = {}));
  6518. //# sourceMappingURL=babylon.touchCamera.js.map
  6519. var BABYLON;
  6520. (function (BABYLON) {
  6521. // We're mainly based on the logic defined into the FreeCamera code
  6522. var DeviceOrientationCamera = (function (_super) {
  6523. __extends(DeviceOrientationCamera, _super);
  6524. function DeviceOrientationCamera(name, position, scene) {
  6525. var _this = this;
  6526. _super.call(this, name, position, scene);
  6527. this._offsetX = null;
  6528. this._offsetY = null;
  6529. this._orientationGamma = 0;
  6530. this._orientationBeta = 0;
  6531. this._initialOrientationGamma = 0;
  6532. this._initialOrientationBeta = 0;
  6533. this.angularSensibility = 10000.0;
  6534. this.moveSensibility = 50.0;
  6535. window.addEventListener("resize", function () {
  6536. _this._initialOrientationGamma = null;
  6537. }, false);
  6538. }
  6539. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6540. var _this = this;
  6541. if (this._attachedCanvas) {
  6542. return;
  6543. }
  6544. this._attachedCanvas = canvas;
  6545. if (!this._orientationChanged) {
  6546. this._orientationChanged = function (evt) {
  6547. if (!_this._initialOrientationGamma) {
  6548. _this._initialOrientationGamma = evt.gamma;
  6549. _this._initialOrientationBeta = evt.beta;
  6550. }
  6551. _this._orientationGamma = evt.gamma;
  6552. _this._orientationBeta = evt.beta;
  6553. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6554. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6555. };
  6556. }
  6557. window.addEventListener("deviceorientation", this._orientationChanged);
  6558. };
  6559. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6560. if (this._attachedCanvas != canvas) {
  6561. return;
  6562. }
  6563. window.removeEventListener("deviceorientation", this._orientationChanged);
  6564. this._attachedCanvas = null;
  6565. this._orientationGamma = 0;
  6566. this._orientationBeta = 0;
  6567. this._initialOrientationGamma = 0;
  6568. this._initialOrientationBeta = 0;
  6569. };
  6570. DeviceOrientationCamera.prototype._checkInputs = function () {
  6571. if (!this._offsetX) {
  6572. return;
  6573. }
  6574. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6575. var speed = this._computeLocalCameraSpeed();
  6576. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6577. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6578. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6579. };
  6580. return DeviceOrientationCamera;
  6581. })(BABYLON.FreeCamera);
  6582. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6583. })(BABYLON || (BABYLON = {}));
  6584. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6585. var BABYLON;
  6586. (function (BABYLON) {
  6587. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6588. var ArcRotateCamera = (function (_super) {
  6589. __extends(ArcRotateCamera, _super);
  6590. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6591. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6592. this.alpha = alpha;
  6593. this.beta = beta;
  6594. this.radius = radius;
  6595. this.target = target;
  6596. this.inertialAlphaOffset = 0;
  6597. this.inertialBetaOffset = 0;
  6598. this.inertialRadiusOffset = 0;
  6599. this.lowerAlphaLimit = null;
  6600. this.upperAlphaLimit = null;
  6601. this.lowerBetaLimit = 0.01;
  6602. this.upperBetaLimit = Math.PI;
  6603. this.lowerRadiusLimit = null;
  6604. this.upperRadiusLimit = null;
  6605. this.angularSensibility = 1000.0;
  6606. this.wheelPrecision = 3.0;
  6607. this.keysUp = [38];
  6608. this.keysDown = [40];
  6609. this.keysLeft = [37];
  6610. this.keysRight = [39];
  6611. this.zoomOnFactor = 1;
  6612. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6613. this._keys = [];
  6614. this._viewMatrix = new BABYLON.Matrix();
  6615. this.checkCollisions = false;
  6616. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6617. this._collider = new BABYLON.Collider();
  6618. this._previousPosition = BABYLON.Vector3.Zero();
  6619. this._collisionVelocity = BABYLON.Vector3.Zero();
  6620. this._newPosition = BABYLON.Vector3.Zero();
  6621. // Pinch
  6622. // value for pinch step scaling
  6623. // set to 20 by default
  6624. this.pinchPrecision = 20;
  6625. this.getViewMatrix();
  6626. }
  6627. ArcRotateCamera.prototype._getTargetPosition = function () {
  6628. return this.target.position || this.target;
  6629. };
  6630. // Cache
  6631. ArcRotateCamera.prototype._initCache = function () {
  6632. _super.prototype._initCache.call(this);
  6633. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6634. this._cache.alpha = undefined;
  6635. this._cache.beta = undefined;
  6636. this._cache.radius = undefined;
  6637. this._cache.targetScreenOffset = undefined;
  6638. };
  6639. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6640. if (!ignoreParentClass) {
  6641. _super.prototype._updateCache.call(this);
  6642. }
  6643. this._cache.target.copyFrom(this._getTargetPosition());
  6644. this._cache.alpha = this.alpha;
  6645. this._cache.beta = this.beta;
  6646. this._cache.radius = this.radius;
  6647. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6648. };
  6649. // Synchronized
  6650. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6651. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6652. return false;
  6653. 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);
  6654. };
  6655. // Methods
  6656. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6657. var _this = this;
  6658. var previousPosition;
  6659. var pointerId;
  6660. // to know if pinch started
  6661. var pinchStarted = false;
  6662. // two pinch point on X
  6663. // that will use for find if user action is pinch open or pinch close
  6664. var pinchPointX1, pinchPointX2;
  6665. if (this._attachedElement) {
  6666. return;
  6667. }
  6668. this._attachedElement = element;
  6669. var engine = this.getEngine();
  6670. if (this._onPointerDown === undefined) {
  6671. this._onPointerDown = function (evt) {
  6672. if (pointerId) {
  6673. return;
  6674. }
  6675. pointerId = evt.pointerId;
  6676. previousPosition = {
  6677. x: evt.clientX,
  6678. y: evt.clientY
  6679. };
  6680. if (!noPreventDefault) {
  6681. evt.preventDefault();
  6682. }
  6683. };
  6684. this._onPointerUp = function (evt) {
  6685. previousPosition = null;
  6686. pointerId = null;
  6687. if (!noPreventDefault) {
  6688. evt.preventDefault();
  6689. }
  6690. };
  6691. this._onPointerMove = function (evt) {
  6692. if (!previousPosition) {
  6693. return;
  6694. }
  6695. if (pointerId !== evt.pointerId) {
  6696. return;
  6697. }
  6698. // return pinch is started
  6699. if (pinchStarted) {
  6700. return;
  6701. }
  6702. var offsetX = evt.clientX - previousPosition.x;
  6703. var offsetY = evt.clientY - previousPosition.y;
  6704. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6705. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6706. previousPosition = {
  6707. x: evt.clientX,
  6708. y: evt.clientY
  6709. };
  6710. if (!noPreventDefault) {
  6711. evt.preventDefault();
  6712. }
  6713. };
  6714. this._onMouseMove = function (evt) {
  6715. if (!engine.isPointerLock) {
  6716. return;
  6717. }
  6718. // return pinch is started
  6719. if (pinchStarted) {
  6720. return;
  6721. }
  6722. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6723. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6724. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6725. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6726. if (!noPreventDefault) {
  6727. evt.preventDefault();
  6728. }
  6729. };
  6730. this._wheel = function (event) {
  6731. var delta = 0;
  6732. if (event.wheelDelta) {
  6733. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6734. } else if (event.detail) {
  6735. delta = -event.detail / _this.wheelPrecision;
  6736. }
  6737. if (delta)
  6738. _this.inertialRadiusOffset += delta;
  6739. if (event.preventDefault) {
  6740. if (!noPreventDefault) {
  6741. event.preventDefault();
  6742. }
  6743. }
  6744. };
  6745. this._onKeyDown = function (evt) {
  6746. 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) {
  6747. var index = _this._keys.indexOf(evt.keyCode);
  6748. if (index === -1) {
  6749. _this._keys.push(evt.keyCode);
  6750. }
  6751. if (evt.preventDefault) {
  6752. if (!noPreventDefault) {
  6753. evt.preventDefault();
  6754. }
  6755. }
  6756. }
  6757. };
  6758. this._onKeyUp = function (evt) {
  6759. 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) {
  6760. var index = _this._keys.indexOf(evt.keyCode);
  6761. if (index >= 0) {
  6762. _this._keys.splice(index, 1);
  6763. }
  6764. if (evt.preventDefault) {
  6765. if (!noPreventDefault) {
  6766. evt.preventDefault();
  6767. }
  6768. }
  6769. }
  6770. };
  6771. this._onLostFocus = function () {
  6772. _this._keys = [];
  6773. pointerId = null;
  6774. };
  6775. this._onGestureStart = function (e) {
  6776. if (window.MSGesture === undefined) {
  6777. return;
  6778. }
  6779. if (!_this._MSGestureHandler) {
  6780. _this._MSGestureHandler = new MSGesture();
  6781. _this._MSGestureHandler.target = element;
  6782. }
  6783. _this._MSGestureHandler.addPointer(e.pointerId);
  6784. };
  6785. this._onGesture = function (e) {
  6786. _this.radius *= e.scale;
  6787. if (e.preventDefault) {
  6788. if (!noPreventDefault) {
  6789. e.stopPropagation();
  6790. e.preventDefault();
  6791. }
  6792. }
  6793. };
  6794. this._reset = function () {
  6795. _this._keys = [];
  6796. _this.inertialAlphaOffset = 0;
  6797. _this.inertialBetaOffset = 0;
  6798. _this.inertialRadiusOffset = 0;
  6799. previousPosition = null;
  6800. pointerId = null;
  6801. };
  6802. this._touchStart = function (event) {
  6803. if (event.touches.length === 2) {
  6804. //-- start pinch if two fingers on the screen
  6805. pinchStarted = true;
  6806. _this._pinchStart(event);
  6807. }
  6808. };
  6809. this._touchMove = function (event) {
  6810. if (pinchStarted) {
  6811. //-- make scaling
  6812. _this._pinchMove(event);
  6813. }
  6814. };
  6815. this._touchEnd = function (event) {
  6816. if (pinchStarted) {
  6817. //-- end of pinch
  6818. _this._pinchEnd(event);
  6819. }
  6820. };
  6821. this._pinchStart = function (event) {
  6822. // save origin touch point
  6823. pinchPointX1 = event.touches[0].clientX;
  6824. pinchPointX2 = event.touches[1].clientX;
  6825. // block the camera
  6826. // if not it rotate around target during pinch
  6827. pinchStarted = true;
  6828. };
  6829. this._pinchMove = function (event) {
  6830. // variable for new camera's radius
  6831. var delta = 0;
  6832. // variables to know if pinch open or pinch close
  6833. var direction = 1;
  6834. var distanceXOrigine, distanceXNow;
  6835. if (event.touches.length !== 2)
  6836. return;
  6837. // calculate absolute distances of the two fingers
  6838. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6839. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6840. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6841. if (distanceXNow < distanceXOrigine) {
  6842. direction = -1;
  6843. }
  6844. // calculate new radius
  6845. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6846. // set new radius
  6847. _this.inertialRadiusOffset -= delta;
  6848. // save origin touch point
  6849. pinchPointX1 = event.touches[0].clientX;
  6850. pinchPointX2 = event.touches[1].clientX;
  6851. };
  6852. this._pinchEnd = function (event) {
  6853. // cancel pinch and deblock camera rotation
  6854. pinchStarted = false;
  6855. };
  6856. }
  6857. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6858. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6859. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6860. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6861. element.addEventListener("mousemove", this._onMouseMove, false);
  6862. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6863. element.addEventListener("MSGestureChange", this._onGesture, false);
  6864. element.addEventListener('mousewheel', this._wheel, false);
  6865. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6866. // pinch
  6867. element.addEventListener('touchstart', this._touchStart, false);
  6868. element.addEventListener('touchmove', this._touchMove, false);
  6869. element.addEventListener('touchend', this._touchEnd, false);
  6870. BABYLON.Tools.RegisterTopRootEvents([
  6871. { name: "keydown", handler: this._onKeyDown },
  6872. { name: "keyup", handler: this._onKeyUp },
  6873. { name: "blur", handler: this._onLostFocus }
  6874. ]);
  6875. };
  6876. ArcRotateCamera.prototype.detachControl = function (element) {
  6877. if (this._attachedElement != element) {
  6878. return;
  6879. }
  6880. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6881. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6882. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6883. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6884. element.removeEventListener("mousemove", this._onMouseMove);
  6885. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6886. element.removeEventListener("MSGestureChange", this._onGesture);
  6887. element.removeEventListener('mousewheel', this._wheel);
  6888. element.removeEventListener('DOMMouseScroll', this._wheel);
  6889. // pinch
  6890. element.removeEventListener('touchstart', this._touchStart);
  6891. element.removeEventListener('touchmove', this._touchMove);
  6892. element.removeEventListener('touchend', this._touchEnd);
  6893. BABYLON.Tools.UnregisterTopRootEvents([
  6894. { name: "keydown", handler: this._onKeyDown },
  6895. { name: "keyup", handler: this._onKeyUp },
  6896. { name: "blur", handler: this._onLostFocus }
  6897. ]);
  6898. this._MSGestureHandler = null;
  6899. this._attachedElement = null;
  6900. if (this._reset) {
  6901. this._reset();
  6902. }
  6903. };
  6904. ArcRotateCamera.prototype._update = function () {
  6905. for (var index = 0; index < this._keys.length; index++) {
  6906. var keyCode = this._keys[index];
  6907. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6908. this.inertialAlphaOffset -= 0.01;
  6909. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6910. this.inertialBetaOffset -= 0.01;
  6911. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6912. this.inertialAlphaOffset += 0.01;
  6913. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6914. this.inertialBetaOffset += 0.01;
  6915. }
  6916. }
  6917. // Inertia
  6918. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6919. this.alpha += this.inertialAlphaOffset;
  6920. this.beta += this.inertialBetaOffset;
  6921. this.radius -= this.inertialRadiusOffset;
  6922. this.inertialAlphaOffset *= this.inertia;
  6923. this.inertialBetaOffset *= this.inertia;
  6924. this.inertialRadiusOffset *= this.inertia;
  6925. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6926. this.inertialAlphaOffset = 0;
  6927. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6928. this.inertialBetaOffset = 0;
  6929. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6930. this.inertialRadiusOffset = 0;
  6931. }
  6932. // Limits
  6933. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6934. this.alpha = this.lowerAlphaLimit;
  6935. }
  6936. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6937. this.alpha = this.upperAlphaLimit;
  6938. }
  6939. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6940. this.beta = this.lowerBetaLimit;
  6941. }
  6942. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6943. this.beta = this.upperBetaLimit;
  6944. }
  6945. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6946. this.radius = this.lowerRadiusLimit;
  6947. }
  6948. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6949. this.radius = this.upperRadiusLimit;
  6950. }
  6951. };
  6952. ArcRotateCamera.prototype.setPosition = function (position) {
  6953. var radiusv3 = position.subtract(this._getTargetPosition());
  6954. this.radius = radiusv3.length();
  6955. // Alpha
  6956. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6957. if (radiusv3.z < 0) {
  6958. this.alpha = 2 * Math.PI - this.alpha;
  6959. }
  6960. // Beta
  6961. this.beta = Math.acos(radiusv3.y / this.radius);
  6962. };
  6963. ArcRotateCamera.prototype._getViewMatrix = function () {
  6964. // Compute
  6965. var cosa = Math.cos(this.alpha);
  6966. var sina = Math.sin(this.alpha);
  6967. var cosb = Math.cos(this.beta);
  6968. var sinb = Math.sin(this.beta);
  6969. var target = this._getTargetPosition();
  6970. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6971. if (this.checkCollisions) {
  6972. this._collider.radius = this.collisionRadius;
  6973. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6974. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6975. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6976. this.position.copyFrom(this._previousPosition);
  6977. this.alpha = this._previousAlpha;
  6978. this.beta = this._previousBeta;
  6979. this.radius = this._previousRadius;
  6980. if (this.onCollide) {
  6981. this.onCollide(this._collider.collidedMesh);
  6982. }
  6983. }
  6984. }
  6985. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6986. this._previousAlpha = this.alpha;
  6987. this._previousBeta = this.beta;
  6988. this._previousRadius = this.radius;
  6989. this._previousPosition.copyFrom(this.position);
  6990. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6991. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6992. return this._viewMatrix;
  6993. };
  6994. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6995. meshes = meshes || this.getScene().meshes;
  6996. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6997. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6998. this.radius = distance * this.zoomOnFactor;
  6999. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7000. };
  7001. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7002. var meshesOrMinMaxVector;
  7003. var distance;
  7004. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7005. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7006. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7007. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7008. } else {
  7009. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7010. distance = meshesOrMinMaxVectorAndDistance.distance;
  7011. }
  7012. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7013. this.maxZ = distance * 2;
  7014. };
  7015. return ArcRotateCamera;
  7016. })(BABYLON.Camera);
  7017. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7018. })(BABYLON || (BABYLON = {}));
  7019. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7020. var BABYLON;
  7021. (function (BABYLON) {
  7022. var Scene = (function () {
  7023. // Constructor
  7024. function Scene(engine) {
  7025. // Members
  7026. this.autoClear = true;
  7027. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7028. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7029. this.forceWireframe = false;
  7030. this.forcePointsCloud = false;
  7031. this.forceShowBoundingBoxes = false;
  7032. this.animationsEnabled = true;
  7033. this.cameraToUseForPointers = null;
  7034. // Fog
  7035. this.fogEnabled = true;
  7036. this.fogMode = Scene.FOGMODE_NONE;
  7037. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7038. this.fogDensity = 0.1;
  7039. this.fogStart = 0;
  7040. this.fogEnd = 1000.0;
  7041. // Lights
  7042. this.shadowsEnabled = true;
  7043. this.lightsEnabled = true;
  7044. this.lights = new Array();
  7045. // Cameras
  7046. this.cameras = new Array();
  7047. this.activeCameras = new Array();
  7048. // Meshes
  7049. this.meshes = new Array();
  7050. // Geometries
  7051. this._geometries = new Array();
  7052. this.materials = new Array();
  7053. this.multiMaterials = new Array();
  7054. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7055. // Textures
  7056. this.texturesEnabled = true;
  7057. this.textures = new Array();
  7058. // Particles
  7059. this.particlesEnabled = true;
  7060. this.particleSystems = new Array();
  7061. // Sprites
  7062. this.spriteManagers = new Array();
  7063. // Layers
  7064. this.layers = new Array();
  7065. // Skeletons
  7066. this.skeletonsEnabled = true;
  7067. this.skeletons = new Array();
  7068. // Lens flares
  7069. this.lensFlaresEnabled = true;
  7070. this.lensFlareSystems = new Array();
  7071. // Collisions
  7072. this.collisionsEnabled = true;
  7073. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7074. // Postprocesses
  7075. this.postProcessesEnabled = true;
  7076. // Customs render targets
  7077. this.renderTargetsEnabled = true;
  7078. this.customRenderTargets = new Array();
  7079. // Imported meshes
  7080. this.importedMeshesFiles = new Array();
  7081. this._actionManagers = new Array();
  7082. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7083. // Procedural textures
  7084. this.proceduralTexturesEnabled = true;
  7085. this._proceduralTextures = new Array();
  7086. this.soundTracks = new Array();
  7087. this._totalVertices = 0;
  7088. this._activeVertices = 0;
  7089. this._activeParticles = 0;
  7090. this._lastFrameDuration = 0;
  7091. this._evaluateActiveMeshesDuration = 0;
  7092. this._renderTargetsDuration = 0;
  7093. this._particlesDuration = 0;
  7094. this._renderDuration = 0;
  7095. this._spritesDuration = 0;
  7096. this._animationRatio = 0;
  7097. this._renderId = 0;
  7098. this._executeWhenReadyTimeoutId = -1;
  7099. this._toBeDisposed = new BABYLON.SmartArray(256);
  7100. this._onReadyCallbacks = new Array();
  7101. this._pendingData = [];
  7102. this._onBeforeRenderCallbacks = new Array();
  7103. this._onAfterRenderCallbacks = new Array();
  7104. this._activeMeshes = new BABYLON.SmartArray(256);
  7105. this._processedMaterials = new BABYLON.SmartArray(256);
  7106. this._renderTargets = new BABYLON.SmartArray(256);
  7107. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7108. this._activeSkeletons = new BABYLON.SmartArray(32);
  7109. this._activeBones = 0;
  7110. this._activeAnimatables = new Array();
  7111. this._transformMatrix = BABYLON.Matrix.Zero();
  7112. this._scaledPosition = BABYLON.Vector3.Zero();
  7113. this._scaledVelocity = BABYLON.Vector3.Zero();
  7114. this._engine = engine;
  7115. engine.scenes.push(this);
  7116. this._renderingManager = new BABYLON.RenderingManager(this);
  7117. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7118. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7119. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7120. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7121. this.attachControl();
  7122. this._debugLayer = new BABYLON.DebugLayer(this);
  7123. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7124. }
  7125. Object.defineProperty(Scene.prototype, "debugLayer", {
  7126. // Properties
  7127. get: function () {
  7128. return this._debugLayer;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7134. get: function () {
  7135. return this._meshUnderPointer;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. Object.defineProperty(Scene.prototype, "pointerX", {
  7141. get: function () {
  7142. return this._pointerX;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(Scene.prototype, "pointerY", {
  7148. get: function () {
  7149. return this._pointerY;
  7150. },
  7151. enumerable: true,
  7152. configurable: true
  7153. });
  7154. Scene.prototype.getCachedMaterial = function () {
  7155. return this._cachedMaterial;
  7156. };
  7157. Scene.prototype.getBoundingBoxRenderer = function () {
  7158. return this._boundingBoxRenderer;
  7159. };
  7160. Scene.prototype.getOutlineRenderer = function () {
  7161. return this._outlineRenderer;
  7162. };
  7163. Scene.prototype.getEngine = function () {
  7164. return this._engine;
  7165. };
  7166. Scene.prototype.getTotalVertices = function () {
  7167. return this._totalVertices;
  7168. };
  7169. Scene.prototype.getActiveVertices = function () {
  7170. return this._activeVertices;
  7171. };
  7172. Scene.prototype.getActiveParticles = function () {
  7173. return this._activeParticles;
  7174. };
  7175. Scene.prototype.getActiveBones = function () {
  7176. return this._activeBones;
  7177. };
  7178. // Stats
  7179. Scene.prototype.getLastFrameDuration = function () {
  7180. return this._lastFrameDuration;
  7181. };
  7182. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7183. return this._evaluateActiveMeshesDuration;
  7184. };
  7185. Scene.prototype.getActiveMeshes = function () {
  7186. return this._activeMeshes;
  7187. };
  7188. Scene.prototype.getRenderTargetsDuration = function () {
  7189. return this._renderTargetsDuration;
  7190. };
  7191. Scene.prototype.getRenderDuration = function () {
  7192. return this._renderDuration;
  7193. };
  7194. Scene.prototype.getParticlesDuration = function () {
  7195. return this._particlesDuration;
  7196. };
  7197. Scene.prototype.getSpritesDuration = function () {
  7198. return this._spritesDuration;
  7199. };
  7200. Scene.prototype.getAnimationRatio = function () {
  7201. return this._animationRatio;
  7202. };
  7203. Scene.prototype.getRenderId = function () {
  7204. return this._renderId;
  7205. };
  7206. Scene.prototype._updatePointerPosition = function (evt) {
  7207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7208. this._pointerX = evt.clientX - canvasRect.left;
  7209. this._pointerY = evt.clientY - canvasRect.top;
  7210. if (this.cameraToUseForPointers) {
  7211. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7212. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7213. }
  7214. };
  7215. // Pointers handling
  7216. Scene.prototype.attachControl = function () {
  7217. var _this = this;
  7218. this._onPointerMove = function (evt) {
  7219. var canvas = _this._engine.getRenderingCanvas();
  7220. _this._updatePointerPosition(evt);
  7221. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7222. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7223. }, false, _this.cameraToUseForPointers);
  7224. if (pickResult.hit) {
  7225. _this._meshUnderPointer = pickResult.pickedMesh;
  7226. _this.setPointerOverMesh(pickResult.pickedMesh);
  7227. canvas.style.cursor = "pointer";
  7228. } else {
  7229. _this.setPointerOverMesh(null);
  7230. canvas.style.cursor = "";
  7231. _this._meshUnderPointer = null;
  7232. }
  7233. };
  7234. this._onPointerDown = function (evt) {
  7235. var predicate = null;
  7236. if (!_this.onPointerDown) {
  7237. predicate = function (mesh) {
  7238. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7239. };
  7240. }
  7241. _this._updatePointerPosition(evt);
  7242. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7243. if (pickResult.hit) {
  7244. if (pickResult.pickedMesh.actionManager) {
  7245. switch (evt.button) {
  7246. case 0:
  7247. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7248. break;
  7249. case 1:
  7250. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7251. break;
  7252. case 2:
  7253. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7254. break;
  7255. }
  7256. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7257. }
  7258. }
  7259. if (_this.onPointerDown) {
  7260. _this.onPointerDown(evt, pickResult);
  7261. }
  7262. };
  7263. this._onKeyDown = function (evt) {
  7264. if (_this.actionManager) {
  7265. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7266. }
  7267. };
  7268. this._onKeyUp = function (evt) {
  7269. if (_this.actionManager) {
  7270. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7271. }
  7272. };
  7273. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7274. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7275. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7276. window.addEventListener("keydown", this._onKeyDown, false);
  7277. window.addEventListener("keyup", this._onKeyUp, false);
  7278. };
  7279. Scene.prototype.detachControl = function () {
  7280. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7281. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7282. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7283. window.removeEventListener("keydown", this._onKeyDown);
  7284. window.removeEventListener("keyup", this._onKeyUp);
  7285. };
  7286. // Ready
  7287. Scene.prototype.isReady = function () {
  7288. if (this._pendingData.length > 0) {
  7289. return false;
  7290. }
  7291. for (var index = 0; index < this._geometries.length; index++) {
  7292. var geometry = this._geometries[index];
  7293. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7294. return false;
  7295. }
  7296. }
  7297. for (index = 0; index < this.meshes.length; index++) {
  7298. var mesh = this.meshes[index];
  7299. if (!mesh.isReady()) {
  7300. return false;
  7301. }
  7302. var mat = mesh.material;
  7303. if (mat) {
  7304. if (!mat.isReady(mesh)) {
  7305. return false;
  7306. }
  7307. }
  7308. }
  7309. return true;
  7310. };
  7311. Scene.prototype.resetCachedMaterial = function () {
  7312. this._cachedMaterial = null;
  7313. };
  7314. Scene.prototype.registerBeforeRender = function (func) {
  7315. this._onBeforeRenderCallbacks.push(func);
  7316. };
  7317. Scene.prototype.unregisterBeforeRender = function (func) {
  7318. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7319. if (index > -1) {
  7320. this._onBeforeRenderCallbacks.splice(index, 1);
  7321. }
  7322. };
  7323. Scene.prototype.registerAfterRender = function (func) {
  7324. this._onAfterRenderCallbacks.push(func);
  7325. };
  7326. Scene.prototype.unregisterAfterRender = function (func) {
  7327. var index = this._onAfterRenderCallbacks.indexOf(func);
  7328. if (index > -1) {
  7329. this._onAfterRenderCallbacks.splice(index, 1);
  7330. }
  7331. };
  7332. Scene.prototype._addPendingData = function (data) {
  7333. this._pendingData.push(data);
  7334. };
  7335. Scene.prototype._removePendingData = function (data) {
  7336. var index = this._pendingData.indexOf(data);
  7337. if (index !== -1) {
  7338. this._pendingData.splice(index, 1);
  7339. }
  7340. };
  7341. Scene.prototype.getWaitingItemsCount = function () {
  7342. return this._pendingData.length;
  7343. };
  7344. Scene.prototype.executeWhenReady = function (func) {
  7345. var _this = this;
  7346. this._onReadyCallbacks.push(func);
  7347. if (this._executeWhenReadyTimeoutId !== -1) {
  7348. return;
  7349. }
  7350. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7351. _this._checkIsReady();
  7352. }, 150);
  7353. };
  7354. Scene.prototype._checkIsReady = function () {
  7355. var _this = this;
  7356. if (this.isReady()) {
  7357. this._onReadyCallbacks.forEach(function (func) {
  7358. func();
  7359. });
  7360. this._onReadyCallbacks = [];
  7361. this._executeWhenReadyTimeoutId = -1;
  7362. return;
  7363. }
  7364. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7365. _this._checkIsReady();
  7366. }, 150);
  7367. };
  7368. // Animations
  7369. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7370. if (speedRatio === undefined) {
  7371. speedRatio = 1.0;
  7372. }
  7373. this.stopAnimation(target);
  7374. if (!animatable) {
  7375. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7376. }
  7377. // Local animations
  7378. if (target.animations) {
  7379. animatable.appendAnimations(target, target.animations);
  7380. }
  7381. // Children animations
  7382. if (target.getAnimatables) {
  7383. var animatables = target.getAnimatables();
  7384. for (var index = 0; index < animatables.length; index++) {
  7385. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7386. }
  7387. }
  7388. return animatable;
  7389. };
  7390. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7391. if (speedRatio === undefined) {
  7392. speedRatio = 1.0;
  7393. }
  7394. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7395. return animatable;
  7396. };
  7397. Scene.prototype.getAnimatableByTarget = function (target) {
  7398. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7399. if (this._activeAnimatables[index].target === target) {
  7400. return this._activeAnimatables[index];
  7401. }
  7402. }
  7403. return null;
  7404. };
  7405. Scene.prototype.stopAnimation = function (target) {
  7406. var animatable = this.getAnimatableByTarget(target);
  7407. if (animatable) {
  7408. animatable.stop();
  7409. }
  7410. };
  7411. Scene.prototype._animate = function () {
  7412. if (!this.animationsEnabled) {
  7413. return;
  7414. }
  7415. if (!this._animationStartDate) {
  7416. this._animationStartDate = BABYLON.Tools.Now;
  7417. }
  7418. // Getting time
  7419. var now = BABYLON.Tools.Now;
  7420. var delay = now - this._animationStartDate;
  7421. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7422. if (!this._activeAnimatables[index]._animate(delay)) {
  7423. this._activeAnimatables.splice(index, 1);
  7424. index--;
  7425. }
  7426. }
  7427. };
  7428. // Matrix
  7429. Scene.prototype.getViewMatrix = function () {
  7430. return this._viewMatrix;
  7431. };
  7432. Scene.prototype.getProjectionMatrix = function () {
  7433. return this._projectionMatrix;
  7434. };
  7435. Scene.prototype.getTransformMatrix = function () {
  7436. return this._transformMatrix;
  7437. };
  7438. Scene.prototype.setTransformMatrix = function (view, projection) {
  7439. this._viewMatrix = view;
  7440. this._projectionMatrix = projection;
  7441. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7442. };
  7443. // Methods
  7444. Scene.prototype.setActiveCameraByID = function (id) {
  7445. var camera = this.getCameraByID(id);
  7446. if (camera) {
  7447. this.activeCamera = camera;
  7448. return camera;
  7449. }
  7450. return null;
  7451. };
  7452. Scene.prototype.setActiveCameraByName = function (name) {
  7453. var camera = this.getCameraByName(name);
  7454. if (camera) {
  7455. this.activeCamera = camera;
  7456. return camera;
  7457. }
  7458. return null;
  7459. };
  7460. Scene.prototype.getMaterialByID = function (id) {
  7461. for (var index = 0; index < this.materials.length; index++) {
  7462. if (this.materials[index].id === id) {
  7463. return this.materials[index];
  7464. }
  7465. }
  7466. return null;
  7467. };
  7468. Scene.prototype.getMaterialByName = function (name) {
  7469. for (var index = 0; index < this.materials.length; index++) {
  7470. if (this.materials[index].name === name) {
  7471. return this.materials[index];
  7472. }
  7473. }
  7474. return null;
  7475. };
  7476. Scene.prototype.getCameraByID = function (id) {
  7477. for (var index = 0; index < this.cameras.length; index++) {
  7478. if (this.cameras[index].id === id) {
  7479. return this.cameras[index];
  7480. }
  7481. }
  7482. return null;
  7483. };
  7484. Scene.prototype.getCameraByName = function (name) {
  7485. for (var index = 0; index < this.cameras.length; index++) {
  7486. if (this.cameras[index].name === name) {
  7487. return this.cameras[index];
  7488. }
  7489. }
  7490. return null;
  7491. };
  7492. Scene.prototype.getLightByName = function (name) {
  7493. for (var index = 0; index < this.lights.length; index++) {
  7494. if (this.lights[index].name === name) {
  7495. return this.lights[index];
  7496. }
  7497. }
  7498. return null;
  7499. };
  7500. Scene.prototype.getLightByID = function (id) {
  7501. for (var index = 0; index < this.lights.length; index++) {
  7502. if (this.lights[index].id === id) {
  7503. return this.lights[index];
  7504. }
  7505. }
  7506. return null;
  7507. };
  7508. Scene.prototype.getGeometryByID = function (id) {
  7509. for (var index = 0; index < this._geometries.length; index++) {
  7510. if (this._geometries[index].id === id) {
  7511. return this._geometries[index];
  7512. }
  7513. }
  7514. return null;
  7515. };
  7516. Scene.prototype.pushGeometry = function (geometry, force) {
  7517. if (!force && this.getGeometryByID(geometry.id)) {
  7518. return false;
  7519. }
  7520. this._geometries.push(geometry);
  7521. return true;
  7522. };
  7523. Scene.prototype.getGeometries = function () {
  7524. return this._geometries;
  7525. };
  7526. Scene.prototype.getMeshByID = function (id) {
  7527. for (var index = 0; index < this.meshes.length; index++) {
  7528. if (this.meshes[index].id === id) {
  7529. return this.meshes[index];
  7530. }
  7531. }
  7532. return null;
  7533. };
  7534. Scene.prototype.getLastMeshByID = function (id) {
  7535. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7536. if (this.meshes[index].id === id) {
  7537. return this.meshes[index];
  7538. }
  7539. }
  7540. return null;
  7541. };
  7542. Scene.prototype.getLastEntryByID = function (id) {
  7543. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7544. if (this.meshes[index].id === id) {
  7545. return this.meshes[index];
  7546. }
  7547. }
  7548. for (index = this.cameras.length - 1; index >= 0; index--) {
  7549. if (this.cameras[index].id === id) {
  7550. return this.cameras[index];
  7551. }
  7552. }
  7553. for (index = this.lights.length - 1; index >= 0; index--) {
  7554. if (this.lights[index].id === id) {
  7555. return this.lights[index];
  7556. }
  7557. }
  7558. return null;
  7559. };
  7560. Scene.prototype.getMeshByName = function (name) {
  7561. for (var index = 0; index < this.meshes.length; index++) {
  7562. if (this.meshes[index].name === name) {
  7563. return this.meshes[index];
  7564. }
  7565. }
  7566. return null;
  7567. };
  7568. Scene.prototype.getLastSkeletonByID = function (id) {
  7569. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7570. if (this.skeletons[index].id === id) {
  7571. return this.skeletons[index];
  7572. }
  7573. }
  7574. return null;
  7575. };
  7576. Scene.prototype.getSkeletonById = function (id) {
  7577. for (var index = 0; index < this.skeletons.length; index++) {
  7578. if (this.skeletons[index].id === id) {
  7579. return this.skeletons[index];
  7580. }
  7581. }
  7582. return null;
  7583. };
  7584. Scene.prototype.getSkeletonByName = function (name) {
  7585. for (var index = 0; index < this.skeletons.length; index++) {
  7586. if (this.skeletons[index].name === name) {
  7587. return this.skeletons[index];
  7588. }
  7589. }
  7590. return null;
  7591. };
  7592. Scene.prototype.isActiveMesh = function (mesh) {
  7593. return (this._activeMeshes.indexOf(mesh) !== -1);
  7594. };
  7595. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7596. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7597. var material = subMesh.getMaterial();
  7598. if (mesh.showSubMeshesBoundingBox) {
  7599. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7600. }
  7601. if (material) {
  7602. // Render targets
  7603. if (material.getRenderTargetTextures) {
  7604. if (this._processedMaterials.indexOf(material) === -1) {
  7605. this._processedMaterials.push(material);
  7606. this._renderTargets.concat(material.getRenderTargetTextures());
  7607. }
  7608. }
  7609. // Dispatch
  7610. this._activeVertices += subMesh.indexCount;
  7611. this._renderingManager.dispatch(subMesh);
  7612. }
  7613. }
  7614. };
  7615. Scene.prototype._evaluateActiveMeshes = function () {
  7616. this._activeMeshes.reset();
  7617. this._renderingManager.reset();
  7618. this._processedMaterials.reset();
  7619. this._activeParticleSystems.reset();
  7620. this._activeSkeletons.reset();
  7621. this._boundingBoxRenderer.reset();
  7622. if (!this._frustumPlanes) {
  7623. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7624. } else {
  7625. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7626. }
  7627. // Meshes
  7628. var meshes;
  7629. var len;
  7630. if (this._selectionOctree) {
  7631. var selection = this._selectionOctree.select(this._frustumPlanes);
  7632. meshes = selection.data;
  7633. len = selection.length;
  7634. } else {
  7635. len = this.meshes.length;
  7636. meshes = this.meshes;
  7637. }
  7638. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7639. var mesh = meshes[meshIndex];
  7640. if (mesh.isBlocked) {
  7641. continue;
  7642. }
  7643. this._totalVertices += mesh.getTotalVertices();
  7644. if (!mesh.isReady()) {
  7645. continue;
  7646. }
  7647. mesh.computeWorldMatrix();
  7648. // Intersections
  7649. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7650. this._meshesForIntersections.pushNoDuplicate(mesh);
  7651. }
  7652. // Switch to current LOD
  7653. var meshLOD = mesh.getLOD(this.activeCamera);
  7654. if (!meshLOD) {
  7655. continue;
  7656. }
  7657. mesh._preActivate();
  7658. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7659. this._activeMeshes.push(mesh);
  7660. mesh._activate(this._renderId);
  7661. this._activeMesh(meshLOD);
  7662. }
  7663. }
  7664. // Particle systems
  7665. var beforeParticlesDate = BABYLON.Tools.Now;
  7666. if (this.particlesEnabled) {
  7667. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7668. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7669. var particleSystem = this.particleSystems[particleIndex];
  7670. if (!particleSystem.isStarted()) {
  7671. continue;
  7672. }
  7673. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7674. this._activeParticleSystems.push(particleSystem);
  7675. particleSystem.animate();
  7676. }
  7677. }
  7678. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7679. }
  7680. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7681. };
  7682. Scene.prototype._activeMesh = function (mesh) {
  7683. if (mesh.skeleton && this.skeletonsEnabled) {
  7684. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7685. }
  7686. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7687. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7688. }
  7689. if (mesh && mesh.subMeshes) {
  7690. // Submeshes Octrees
  7691. var len;
  7692. var subMeshes;
  7693. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7694. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7695. len = intersections.length;
  7696. subMeshes = intersections.data;
  7697. } else {
  7698. subMeshes = mesh.subMeshes;
  7699. len = subMeshes.length;
  7700. }
  7701. for (var subIndex = 0; subIndex < len; subIndex++) {
  7702. var subMesh = subMeshes[subIndex];
  7703. this._evaluateSubMesh(subMesh, mesh);
  7704. }
  7705. }
  7706. };
  7707. Scene.prototype.updateTransformMatrix = function (force) {
  7708. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7709. };
  7710. Scene.prototype._renderForCamera = function (camera) {
  7711. var engine = this._engine;
  7712. this.activeCamera = camera;
  7713. if (!this.activeCamera)
  7714. throw new Error("Active camera not set");
  7715. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7716. // Viewport
  7717. engine.setViewport(this.activeCamera.viewport);
  7718. // Camera
  7719. this._renderId++;
  7720. this.updateTransformMatrix();
  7721. if (this.beforeCameraRender) {
  7722. this.beforeCameraRender(this.activeCamera);
  7723. }
  7724. // Meshes
  7725. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7726. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7727. this._evaluateActiveMeshes();
  7728. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7729. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7730. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7731. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7732. skeleton.prepare();
  7733. this._activeBones += skeleton.bones.length;
  7734. }
  7735. // Render targets
  7736. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7737. if (this.renderTargetsEnabled) {
  7738. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7739. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7740. var renderTarget = this._renderTargets.data[renderIndex];
  7741. if (renderTarget._shouldRender()) {
  7742. this._renderId++;
  7743. renderTarget.render();
  7744. }
  7745. }
  7746. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7747. this._renderId++;
  7748. }
  7749. if (this._renderTargets.length > 0) {
  7750. engine.restoreDefaultFramebuffer();
  7751. }
  7752. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7753. // Prepare Frame
  7754. this.postProcessManager._prepareFrame();
  7755. var beforeRenderDate = BABYLON.Tools.Now;
  7756. // Backgrounds
  7757. if (this.layers.length) {
  7758. engine.setDepthBuffer(false);
  7759. var layerIndex;
  7760. var layer;
  7761. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7762. layer = this.layers[layerIndex];
  7763. if (layer.isBackground) {
  7764. layer.render();
  7765. }
  7766. }
  7767. engine.setDepthBuffer(true);
  7768. }
  7769. // Render
  7770. BABYLON.Tools.StartPerformanceCounter("Main render");
  7771. this._renderingManager.render(null, null, true, true);
  7772. BABYLON.Tools.EndPerformanceCounter("Main render");
  7773. // Bounding boxes
  7774. this._boundingBoxRenderer.render();
  7775. // Lens flares
  7776. if (this.lensFlaresEnabled) {
  7777. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7778. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7779. this.lensFlareSystems[lensFlareSystemIndex].render();
  7780. }
  7781. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7782. }
  7783. // Foregrounds
  7784. if (this.layers.length) {
  7785. engine.setDepthBuffer(false);
  7786. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7787. layer = this.layers[layerIndex];
  7788. if (!layer.isBackground) {
  7789. layer.render();
  7790. }
  7791. }
  7792. engine.setDepthBuffer(true);
  7793. }
  7794. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7795. // Finalize frame
  7796. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7797. // Update camera
  7798. this.activeCamera._updateFromScene();
  7799. // Reset some special arrays
  7800. this._renderTargets.reset();
  7801. if (this.afterCameraRender) {
  7802. this.afterCameraRender(this.activeCamera);
  7803. }
  7804. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7805. };
  7806. Scene.prototype._processSubCameras = function (camera) {
  7807. if (camera.subCameras.length === 0) {
  7808. this._renderForCamera(camera);
  7809. return;
  7810. }
  7811. for (var index = 0; index < camera.subCameras.length; index++) {
  7812. this._renderForCamera(camera.subCameras[index]);
  7813. }
  7814. this.activeCamera = camera;
  7815. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7816. // Update camera
  7817. this.activeCamera._updateFromScene();
  7818. };
  7819. Scene.prototype._checkIntersections = function () {
  7820. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7821. var sourceMesh = this._meshesForIntersections.data[index];
  7822. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7823. var action = sourceMesh.actionManager.actions[actionIndex];
  7824. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7825. var otherMesh = action.getTriggerParameter();
  7826. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7827. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7828. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7829. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7830. sourceMesh._intersectionsInProgress.push(otherMesh);
  7831. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7832. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7833. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7834. if (indexOfOther > -1) {
  7835. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7836. }
  7837. }
  7838. }
  7839. }
  7840. }
  7841. };
  7842. Scene.prototype.render = function () {
  7843. var startDate = BABYLON.Tools.Now;
  7844. this._particlesDuration = 0;
  7845. this._spritesDuration = 0;
  7846. this._activeParticles = 0;
  7847. this._renderDuration = 0;
  7848. this._renderTargetsDuration = 0;
  7849. this._evaluateActiveMeshesDuration = 0;
  7850. this._totalVertices = 0;
  7851. this._activeVertices = 0;
  7852. this._activeBones = 0;
  7853. this.getEngine().resetDrawCalls();
  7854. this._meshesForIntersections.reset();
  7855. this.resetCachedMaterial();
  7856. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7857. // Actions
  7858. if (this.actionManager) {
  7859. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7860. }
  7861. // Before render
  7862. if (this.beforeRender) {
  7863. this.beforeRender();
  7864. }
  7865. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7866. this._onBeforeRenderCallbacks[callbackIndex]();
  7867. }
  7868. // Animations
  7869. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7870. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7871. this._animate();
  7872. // Physics
  7873. if (this._physicsEngine) {
  7874. BABYLON.Tools.StartPerformanceCounter("Physics");
  7875. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7876. BABYLON.Tools.EndPerformanceCounter("Physics");
  7877. }
  7878. // Customs render targets
  7879. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7880. var engine = this.getEngine();
  7881. if (this.renderTargetsEnabled) {
  7882. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7883. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7884. var renderTarget = this.customRenderTargets[customIndex];
  7885. if (renderTarget._shouldRender()) {
  7886. this._renderId++;
  7887. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7888. if (!this.activeCamera)
  7889. throw new Error("Active camera not set");
  7890. // Viewport
  7891. engine.setViewport(this.activeCamera.viewport);
  7892. // Camera
  7893. this.updateTransformMatrix();
  7894. renderTarget.render();
  7895. }
  7896. }
  7897. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7898. this._renderId++;
  7899. }
  7900. if (this.customRenderTargets.length > 0) {
  7901. engine.restoreDefaultFramebuffer();
  7902. }
  7903. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7904. // Procedural textures
  7905. if (this.proceduralTexturesEnabled) {
  7906. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7907. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7908. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7909. if (proceduralTexture._shouldRender()) {
  7910. proceduralTexture.render();
  7911. }
  7912. }
  7913. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7914. }
  7915. // Clear
  7916. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7917. // Shadows
  7918. if (this.shadowsEnabled) {
  7919. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7920. var light = this.lights[lightIndex];
  7921. var shadowGenerator = light.getShadowGenerator();
  7922. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7923. this._renderTargets.push(shadowGenerator.getShadowMap());
  7924. }
  7925. }
  7926. }
  7927. // RenderPipeline
  7928. this.postProcessRenderPipelineManager.update();
  7929. // Multi-cameras?
  7930. if (this.activeCameras.length > 0) {
  7931. var currentRenderId = this._renderId;
  7932. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7933. this._renderId = currentRenderId;
  7934. this._processSubCameras(this.activeCameras[cameraIndex]);
  7935. }
  7936. } else {
  7937. if (!this.activeCamera) {
  7938. throw new Error("No camera defined");
  7939. }
  7940. this._processSubCameras(this.activeCamera);
  7941. }
  7942. // Intersection checks
  7943. this._checkIntersections();
  7944. // Update the audio listener attached to the camera
  7945. this._updateAudioParameters();
  7946. // After render
  7947. if (this.afterRender) {
  7948. this.afterRender();
  7949. }
  7950. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7951. this._onAfterRenderCallbacks[callbackIndex]();
  7952. }
  7953. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7954. this._toBeDisposed.data[index].dispose();
  7955. this._toBeDisposed[index] = null;
  7956. }
  7957. this._toBeDisposed.reset();
  7958. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7959. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7960. };
  7961. Scene.prototype._updateAudioParameters = function () {
  7962. var listeningCamera;
  7963. var audioEngine = this._engine.getAudioEngine();
  7964. if (this.activeCameras.length > 0) {
  7965. listeningCamera = this.activeCameras[0];
  7966. } else {
  7967. listeningCamera = this.activeCamera;
  7968. }
  7969. if (listeningCamera && audioEngine.canUseWebAudio) {
  7970. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7971. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7972. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7973. cameraDirection.normalize();
  7974. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7975. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7976. var sound = this.mainSoundTrack.soundCollection[i];
  7977. if (sound.useCustomAttenuation) {
  7978. sound.updateDistanceFromListener();
  7979. }
  7980. }
  7981. for (var i = 0; i < this.soundTracks.length; i++) {
  7982. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7983. var sound = this.soundTracks[i].soundCollection[j];
  7984. if (sound.useCustomAttenuation) {
  7985. sound.updateDistanceFromListener();
  7986. }
  7987. }
  7988. }
  7989. }
  7990. };
  7991. Scene.prototype.dispose = function () {
  7992. this.beforeRender = null;
  7993. this.afterRender = null;
  7994. this.skeletons = [];
  7995. this._boundingBoxRenderer.dispose();
  7996. // Debug layer
  7997. this.debugLayer.hide();
  7998. // Events
  7999. if (this.onDispose) {
  8000. this.onDispose();
  8001. }
  8002. this._onBeforeRenderCallbacks = [];
  8003. this._onAfterRenderCallbacks = [];
  8004. this.detachControl();
  8005. // Detach cameras
  8006. var canvas = this._engine.getRenderingCanvas();
  8007. var index;
  8008. for (index = 0; index < this.cameras.length; index++) {
  8009. this.cameras[index].detachControl(canvas);
  8010. }
  8011. while (this.lights.length) {
  8012. this.lights[0].dispose();
  8013. }
  8014. while (this.meshes.length) {
  8015. this.meshes[0].dispose(true);
  8016. }
  8017. while (this.cameras.length) {
  8018. this.cameras[0].dispose();
  8019. }
  8020. while (this.materials.length) {
  8021. this.materials[0].dispose();
  8022. }
  8023. while (this.particleSystems.length) {
  8024. this.particleSystems[0].dispose();
  8025. }
  8026. while (this.spriteManagers.length) {
  8027. this.spriteManagers[0].dispose();
  8028. }
  8029. while (this.layers.length) {
  8030. this.layers[0].dispose();
  8031. }
  8032. while (this.textures.length) {
  8033. this.textures[0].dispose();
  8034. }
  8035. // Post-processes
  8036. this.postProcessManager.dispose();
  8037. // Physics
  8038. if (this._physicsEngine) {
  8039. this.disablePhysicsEngine();
  8040. }
  8041. // Remove from engine
  8042. index = this._engine.scenes.indexOf(this);
  8043. if (index > -1) {
  8044. this._engine.scenes.splice(index, 1);
  8045. }
  8046. this._engine.wipeCaches();
  8047. };
  8048. // Collisions
  8049. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8050. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8051. position.divideToRef(collider.radius, this._scaledPosition);
  8052. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8053. collider.retry = 0;
  8054. collider.initialVelocity = this._scaledVelocity;
  8055. collider.initialPosition = this._scaledPosition;
  8056. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8057. finalPosition.multiplyInPlace(collider.radius);
  8058. };
  8059. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8060. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8061. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8062. if (collider.retry >= maximumRetry) {
  8063. finalPosition.copyFrom(position);
  8064. return;
  8065. }
  8066. collider._initialize(position, velocity, closeDistance);
  8067. for (var index = 0; index < this.meshes.length; index++) {
  8068. var mesh = this.meshes[index];
  8069. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8070. mesh._checkCollision(collider);
  8071. }
  8072. }
  8073. if (!collider.collisionFound) {
  8074. position.addToRef(velocity, finalPosition);
  8075. return;
  8076. }
  8077. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8078. collider._getResponse(position, velocity);
  8079. }
  8080. if (velocity.length() <= closeDistance) {
  8081. finalPosition.copyFrom(position);
  8082. return;
  8083. }
  8084. collider.retry++;
  8085. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8086. };
  8087. // Octrees
  8088. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8089. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8090. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8091. if (!this._selectionOctree) {
  8092. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8093. }
  8094. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8095. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8096. for (var index = 0; index < this.meshes.length; index++) {
  8097. var mesh = this.meshes[index];
  8098. mesh.computeWorldMatrix(true);
  8099. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8100. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8101. BABYLON.Tools.CheckExtends(minBox, min, max);
  8102. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8103. }
  8104. // Update octree
  8105. this._selectionOctree.update(min, max, this.meshes);
  8106. return this._selectionOctree;
  8107. };
  8108. // Picking
  8109. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8110. var engine = this._engine;
  8111. if (!camera) {
  8112. if (!this.activeCamera)
  8113. throw new Error("Active camera not set");
  8114. camera = this.activeCamera;
  8115. }
  8116. var cameraViewport = camera.viewport;
  8117. var viewport = cameraViewport.toGlobal(engine);
  8118. // Moving coordinates to local viewport world
  8119. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8120. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8121. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8122. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8123. };
  8124. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8125. var pickingInfo = null;
  8126. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8127. var mesh = this.meshes[meshIndex];
  8128. if (predicate) {
  8129. if (!predicate(mesh)) {
  8130. continue;
  8131. }
  8132. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8133. continue;
  8134. }
  8135. var world = mesh.getWorldMatrix();
  8136. var ray = rayFunction(world);
  8137. var result = mesh.intersects(ray, fastCheck);
  8138. if (!result || !result.hit)
  8139. continue;
  8140. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8141. continue;
  8142. pickingInfo = result;
  8143. if (fastCheck) {
  8144. break;
  8145. }
  8146. }
  8147. return pickingInfo || new BABYLON.PickingInfo();
  8148. };
  8149. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8150. var _this = this;
  8151. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8152. /// <param name="x">X position on screen</param>
  8153. /// <param name="y">Y position on screen</param>
  8154. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  8155. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8156. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  8157. return this._internalPick(function (world) {
  8158. return _this.createPickingRay(x, y, world, camera);
  8159. }, predicate, fastCheck);
  8160. };
  8161. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8162. var _this = this;
  8163. return this._internalPick(function (world) {
  8164. if (!_this._pickWithRayInverseMatrix) {
  8165. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8166. }
  8167. world.invertToRef(_this._pickWithRayInverseMatrix);
  8168. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8169. }, predicate, fastCheck);
  8170. };
  8171. Scene.prototype.setPointerOverMesh = function (mesh) {
  8172. if (this._pointerOverMesh === mesh) {
  8173. return;
  8174. }
  8175. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8176. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8177. }
  8178. this._pointerOverMesh = mesh;
  8179. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8180. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8181. }
  8182. };
  8183. Scene.prototype.getPointerOverMesh = function () {
  8184. return this._pointerOverMesh;
  8185. };
  8186. // Physics
  8187. Scene.prototype.getPhysicsEngine = function () {
  8188. return this._physicsEngine;
  8189. };
  8190. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8191. if (this._physicsEngine) {
  8192. return true;
  8193. }
  8194. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8195. if (!this._physicsEngine.isSupported()) {
  8196. this._physicsEngine = null;
  8197. return false;
  8198. }
  8199. this._physicsEngine._initialize(gravity);
  8200. return true;
  8201. };
  8202. Scene.prototype.disablePhysicsEngine = function () {
  8203. if (!this._physicsEngine) {
  8204. return;
  8205. }
  8206. this._physicsEngine.dispose();
  8207. this._physicsEngine = undefined;
  8208. };
  8209. Scene.prototype.isPhysicsEnabled = function () {
  8210. return this._physicsEngine !== undefined;
  8211. };
  8212. Scene.prototype.setGravity = function (gravity) {
  8213. if (!this._physicsEngine) {
  8214. return;
  8215. }
  8216. this._physicsEngine._setGravity(gravity);
  8217. };
  8218. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8219. if (parts.parts) {
  8220. options = parts;
  8221. parts = parts.parts;
  8222. }
  8223. if (!this._physicsEngine) {
  8224. return null;
  8225. }
  8226. for (var index = 0; index < parts.length; index++) {
  8227. var mesh = parts[index].mesh;
  8228. mesh._physicImpostor = parts[index].impostor;
  8229. mesh._physicsMass = options.mass / parts.length;
  8230. mesh._physicsFriction = options.friction;
  8231. mesh._physicRestitution = options.restitution;
  8232. }
  8233. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8234. };
  8235. //ANY
  8236. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8237. for (var index = 0; index < compound.parts.length; index++) {
  8238. var mesh = compound.parts[index].mesh;
  8239. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8240. this._physicsEngine._unregisterMesh(mesh);
  8241. }
  8242. };
  8243. // Tags
  8244. Scene.prototype._getByTags = function (list, tagsQuery) {
  8245. if (tagsQuery === undefined) {
  8246. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8247. return list;
  8248. }
  8249. var listByTags = [];
  8250. for (var i in list) {
  8251. var item = list[i];
  8252. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8253. listByTags.push(item);
  8254. }
  8255. }
  8256. return listByTags;
  8257. };
  8258. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8259. return this._getByTags(this.meshes, tagsQuery);
  8260. };
  8261. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8262. return this._getByTags(this.cameras, tagsQuery);
  8263. };
  8264. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8265. return this._getByTags(this.lights, tagsQuery);
  8266. };
  8267. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8268. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8269. };
  8270. Scene.FOGMODE_NONE = 0;
  8271. Scene.FOGMODE_EXP = 1;
  8272. Scene.FOGMODE_EXP2 = 2;
  8273. Scene.FOGMODE_LINEAR = 3;
  8274. Scene.MinDeltaTime = 1.0;
  8275. Scene.MaxDeltaTime = 1000.0;
  8276. return Scene;
  8277. })();
  8278. BABYLON.Scene = Scene;
  8279. })(BABYLON || (BABYLON = {}));
  8280. //# sourceMappingURL=babylon.scene.js.map
  8281. var BABYLON;
  8282. (function (BABYLON) {
  8283. var VertexBuffer = (function () {
  8284. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8285. if (engine instanceof BABYLON.Mesh) {
  8286. this._engine = engine.getScene().getEngine();
  8287. } else {
  8288. this._engine = engine;
  8289. }
  8290. this._updatable = updatable;
  8291. this._data = data;
  8292. if (!postponeInternalCreation) {
  8293. this.create();
  8294. }
  8295. this._kind = kind;
  8296. if (stride) {
  8297. this._strideSize = stride;
  8298. return;
  8299. }
  8300. switch (kind) {
  8301. case VertexBuffer.PositionKind:
  8302. this._strideSize = 3;
  8303. break;
  8304. case VertexBuffer.NormalKind:
  8305. this._strideSize = 3;
  8306. break;
  8307. case VertexBuffer.UVKind:
  8308. this._strideSize = 2;
  8309. break;
  8310. case VertexBuffer.UV2Kind:
  8311. this._strideSize = 2;
  8312. break;
  8313. case VertexBuffer.ColorKind:
  8314. this._strideSize = 4;
  8315. break;
  8316. case VertexBuffer.MatricesIndicesKind:
  8317. this._strideSize = 4;
  8318. break;
  8319. case VertexBuffer.MatricesWeightsKind:
  8320. this._strideSize = 4;
  8321. break;
  8322. }
  8323. }
  8324. // Properties
  8325. VertexBuffer.prototype.isUpdatable = function () {
  8326. return this._updatable;
  8327. };
  8328. VertexBuffer.prototype.getData = function () {
  8329. return this._data;
  8330. };
  8331. VertexBuffer.prototype.getBuffer = function () {
  8332. return this._buffer;
  8333. };
  8334. VertexBuffer.prototype.getStrideSize = function () {
  8335. return this._strideSize;
  8336. };
  8337. // Methods
  8338. VertexBuffer.prototype.create = function (data) {
  8339. if (!data && this._buffer) {
  8340. return;
  8341. }
  8342. data = data || this._data;
  8343. if (!this._buffer) {
  8344. if (this._updatable) {
  8345. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8346. } else {
  8347. this._buffer = this._engine.createVertexBuffer(data);
  8348. }
  8349. }
  8350. if (this._updatable) {
  8351. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8352. this._data = data;
  8353. }
  8354. };
  8355. VertexBuffer.prototype.update = function (data) {
  8356. this.create(data);
  8357. };
  8358. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8359. if (!this._buffer) {
  8360. return;
  8361. }
  8362. if (this._updatable) {
  8363. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8364. this._data = null;
  8365. }
  8366. };
  8367. VertexBuffer.prototype.dispose = function () {
  8368. if (!this._buffer) {
  8369. return;
  8370. }
  8371. if (this._engine._releaseBuffer(this._buffer)) {
  8372. this._buffer = null;
  8373. }
  8374. };
  8375. Object.defineProperty(VertexBuffer, "PositionKind", {
  8376. get: function () {
  8377. return VertexBuffer._PositionKind;
  8378. },
  8379. enumerable: true,
  8380. configurable: true
  8381. });
  8382. Object.defineProperty(VertexBuffer, "NormalKind", {
  8383. get: function () {
  8384. return VertexBuffer._NormalKind;
  8385. },
  8386. enumerable: true,
  8387. configurable: true
  8388. });
  8389. Object.defineProperty(VertexBuffer, "UVKind", {
  8390. get: function () {
  8391. return VertexBuffer._UVKind;
  8392. },
  8393. enumerable: true,
  8394. configurable: true
  8395. });
  8396. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8397. get: function () {
  8398. return VertexBuffer._UV2Kind;
  8399. },
  8400. enumerable: true,
  8401. configurable: true
  8402. });
  8403. Object.defineProperty(VertexBuffer, "ColorKind", {
  8404. get: function () {
  8405. return VertexBuffer._ColorKind;
  8406. },
  8407. enumerable: true,
  8408. configurable: true
  8409. });
  8410. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8411. get: function () {
  8412. return VertexBuffer._MatricesIndicesKind;
  8413. },
  8414. enumerable: true,
  8415. configurable: true
  8416. });
  8417. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8418. get: function () {
  8419. return VertexBuffer._MatricesWeightsKind;
  8420. },
  8421. enumerable: true,
  8422. configurable: true
  8423. });
  8424. VertexBuffer._PositionKind = "position";
  8425. VertexBuffer._NormalKind = "normal";
  8426. VertexBuffer._UVKind = "uv";
  8427. VertexBuffer._UV2Kind = "uv2";
  8428. VertexBuffer._ColorKind = "color";
  8429. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8430. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8431. return VertexBuffer;
  8432. })();
  8433. BABYLON.VertexBuffer = VertexBuffer;
  8434. })(BABYLON || (BABYLON = {}));
  8435. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8436. var BABYLON;
  8437. (function (BABYLON) {
  8438. var AbstractMesh = (function (_super) {
  8439. __extends(AbstractMesh, _super);
  8440. function AbstractMesh(name, scene) {
  8441. _super.call(this, name, scene);
  8442. // Properties
  8443. this.position = new BABYLON.Vector3(0, 0, 0);
  8444. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8445. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8446. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8447. this.visibility = 1.0;
  8448. this.alphaIndex = Number.MAX_VALUE;
  8449. this.infiniteDistance = false;
  8450. this.isVisible = true;
  8451. this.isPickable = true;
  8452. this.showBoundingBox = false;
  8453. this.showSubMeshesBoundingBox = false;
  8454. this.onDispose = null;
  8455. this.checkCollisions = false;
  8456. this.isBlocker = false;
  8457. this.renderingGroupId = 0;
  8458. this.receiveShadows = false;
  8459. this.renderOutline = false;
  8460. this.outlineColor = BABYLON.Color3.Red();
  8461. this.outlineWidth = 0.02;
  8462. this.renderOverlay = false;
  8463. this.overlayColor = BABYLON.Color3.Red();
  8464. this.overlayAlpha = 0.5;
  8465. this.hasVertexAlpha = false;
  8466. this.useVertexColors = true;
  8467. this.applyFog = true;
  8468. this.useOctreeForRenderingSelection = true;
  8469. this.useOctreeForPicking = true;
  8470. this.useOctreeForCollisions = true;
  8471. this.layerMask = 0xFFFFFFFF;
  8472. // Physics
  8473. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8474. // Collisions
  8475. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8476. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8477. this._collider = new BABYLON.Collider();
  8478. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8479. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8480. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8481. // Cache
  8482. this._localScaling = BABYLON.Matrix.Zero();
  8483. this._localRotation = BABYLON.Matrix.Zero();
  8484. this._localTranslation = BABYLON.Matrix.Zero();
  8485. this._localBillboard = BABYLON.Matrix.Zero();
  8486. this._localPivotScaling = BABYLON.Matrix.Zero();
  8487. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8488. this._localWorld = BABYLON.Matrix.Zero();
  8489. this._worldMatrix = BABYLON.Matrix.Zero();
  8490. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8491. this._absolutePosition = BABYLON.Vector3.Zero();
  8492. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8493. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8494. this._isDirty = false;
  8495. this._pivotMatrix = BABYLON.Matrix.Identity();
  8496. this._isDisposed = false;
  8497. this._renderId = 0;
  8498. this._intersectionsInProgress = new Array();
  8499. this._onAfterWorldMatrixUpdate = new Array();
  8500. scene.meshes.push(this);
  8501. }
  8502. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8503. get: function () {
  8504. return AbstractMesh._BILLBOARDMODE_NONE;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8510. get: function () {
  8511. return AbstractMesh._BILLBOARDMODE_X;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8517. get: function () {
  8518. return AbstractMesh._BILLBOARDMODE_Y;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8524. get: function () {
  8525. return AbstractMesh._BILLBOARDMODE_Z;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8531. get: function () {
  8532. return AbstractMesh._BILLBOARDMODE_ALL;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8538. // Methods
  8539. get: function () {
  8540. return false;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. AbstractMesh.prototype.getLOD = function (camera) {
  8546. return this;
  8547. };
  8548. AbstractMesh.prototype.getTotalVertices = function () {
  8549. return 0;
  8550. };
  8551. AbstractMesh.prototype.getIndices = function () {
  8552. return null;
  8553. };
  8554. AbstractMesh.prototype.getVerticesData = function (kind) {
  8555. return null;
  8556. };
  8557. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8558. return false;
  8559. };
  8560. AbstractMesh.prototype.getBoundingInfo = function () {
  8561. if (this._masterMesh) {
  8562. return this._masterMesh.getBoundingInfo();
  8563. }
  8564. if (!this._boundingInfo) {
  8565. this._updateBoundingInfo();
  8566. }
  8567. return this._boundingInfo;
  8568. };
  8569. AbstractMesh.prototype._preActivate = function () {
  8570. };
  8571. AbstractMesh.prototype._activate = function (renderId) {
  8572. this._renderId = renderId;
  8573. };
  8574. AbstractMesh.prototype.getWorldMatrix = function () {
  8575. if (this._masterMesh) {
  8576. return this._masterMesh.getWorldMatrix();
  8577. }
  8578. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8579. this.computeWorldMatrix();
  8580. }
  8581. return this._worldMatrix;
  8582. };
  8583. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8584. get: function () {
  8585. return this._worldMatrix;
  8586. },
  8587. enumerable: true,
  8588. configurable: true
  8589. });
  8590. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8591. get: function () {
  8592. return this._absolutePosition;
  8593. },
  8594. enumerable: true,
  8595. configurable: true
  8596. });
  8597. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8598. if (!this.rotationQuaternion) {
  8599. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8600. this.rotation = BABYLON.Vector3.Zero();
  8601. }
  8602. if (!space || space == 0 /* LOCAL */) {
  8603. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8604. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8605. } else {
  8606. if (this.parent) {
  8607. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8608. invertParentWorldMatrix.invert();
  8609. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8610. }
  8611. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8612. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8613. }
  8614. };
  8615. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8616. var displacementVector = axis.scale(distance);
  8617. if (!space || space == 0 /* LOCAL */) {
  8618. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8619. this.setPositionWithLocalVector(tempV3);
  8620. } else {
  8621. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8622. }
  8623. };
  8624. AbstractMesh.prototype.getAbsolutePosition = function () {
  8625. this.computeWorldMatrix();
  8626. return this._absolutePosition;
  8627. };
  8628. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8629. if (!absolutePosition) {
  8630. return;
  8631. }
  8632. var absolutePositionX;
  8633. var absolutePositionY;
  8634. var absolutePositionZ;
  8635. if (absolutePosition.x === undefined) {
  8636. if (arguments.length < 3) {
  8637. return;
  8638. }
  8639. absolutePositionX = arguments[0];
  8640. absolutePositionY = arguments[1];
  8641. absolutePositionZ = arguments[2];
  8642. } else {
  8643. absolutePositionX = absolutePosition.x;
  8644. absolutePositionY = absolutePosition.y;
  8645. absolutePositionZ = absolutePosition.z;
  8646. }
  8647. if (this.parent) {
  8648. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8649. invertParentWorldMatrix.invert();
  8650. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8651. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8652. } else {
  8653. this.position.x = absolutePositionX;
  8654. this.position.y = absolutePositionY;
  8655. this.position.z = absolutePositionZ;
  8656. }
  8657. };
  8658. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8659. this._pivotMatrix = matrix;
  8660. this._cache.pivotMatrixUpdated = true;
  8661. };
  8662. AbstractMesh.prototype.getPivotMatrix = function () {
  8663. return this._pivotMatrix;
  8664. };
  8665. AbstractMesh.prototype._isSynchronized = function () {
  8666. if (this._isDirty) {
  8667. return false;
  8668. }
  8669. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8670. return false;
  8671. if (this._cache.pivotMatrixUpdated) {
  8672. return false;
  8673. }
  8674. if (this.infiniteDistance) {
  8675. return false;
  8676. }
  8677. if (!this._cache.position.equals(this.position))
  8678. return false;
  8679. if (this.rotationQuaternion) {
  8680. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8681. return false;
  8682. } else {
  8683. if (!this._cache.rotation.equals(this.rotation))
  8684. return false;
  8685. }
  8686. if (!this._cache.scaling.equals(this.scaling))
  8687. return false;
  8688. return true;
  8689. };
  8690. AbstractMesh.prototype._initCache = function () {
  8691. _super.prototype._initCache.call(this);
  8692. this._cache.localMatrixUpdated = false;
  8693. this._cache.position = BABYLON.Vector3.Zero();
  8694. this._cache.scaling = BABYLON.Vector3.Zero();
  8695. this._cache.rotation = BABYLON.Vector3.Zero();
  8696. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8697. };
  8698. AbstractMesh.prototype.markAsDirty = function (property) {
  8699. if (property === "rotation") {
  8700. this.rotationQuaternion = null;
  8701. }
  8702. this._currentRenderId = Number.MAX_VALUE;
  8703. this._isDirty = true;
  8704. };
  8705. AbstractMesh.prototype._updateBoundingInfo = function () {
  8706. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8707. this._boundingInfo._update(this.worldMatrixFromCache);
  8708. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8709. };
  8710. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8711. if (!this.subMeshes) {
  8712. return;
  8713. }
  8714. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8715. var subMesh = this.subMeshes[subIndex];
  8716. subMesh.updateBoundingInfo(matrix);
  8717. }
  8718. };
  8719. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8720. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8721. return this._worldMatrix;
  8722. }
  8723. this._cache.position.copyFrom(this.position);
  8724. this._cache.scaling.copyFrom(this.scaling);
  8725. this._cache.pivotMatrixUpdated = false;
  8726. this._currentRenderId = this.getScene().getRenderId();
  8727. this._isDirty = false;
  8728. // Scaling
  8729. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8730. // Rotation
  8731. if (this.rotationQuaternion) {
  8732. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8733. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8734. } else {
  8735. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8736. this._cache.rotation.copyFrom(this.rotation);
  8737. }
  8738. // Translation
  8739. if (this.infiniteDistance && !this.parent) {
  8740. var camera = this.getScene().activeCamera;
  8741. var cameraWorldMatrix = camera.getWorldMatrix();
  8742. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8743. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8744. } else {
  8745. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8746. }
  8747. // Composing transformations
  8748. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8749. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8750. // Billboarding
  8751. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8752. var localPosition = this.position.clone();
  8753. var zero = this.getScene().activeCamera.position.clone();
  8754. if (this.parent && this.parent.position) {
  8755. localPosition.addInPlace(this.parent.position);
  8756. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8757. }
  8758. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8759. zero = this.getScene().activeCamera.position;
  8760. } else {
  8761. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8762. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8763. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8764. zero.y = localPosition.y + 0.001;
  8765. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8766. zero.z = localPosition.z + 0.001;
  8767. }
  8768. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8769. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8770. this._localBillboard.invert();
  8771. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8772. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8773. }
  8774. // Local world
  8775. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8776. // Parent
  8777. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8778. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8779. } else {
  8780. this._worldMatrix.copyFrom(this._localWorld);
  8781. }
  8782. // Bounding info
  8783. this._updateBoundingInfo();
  8784. // Absolute position
  8785. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8786. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8787. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8788. }
  8789. return this._worldMatrix;
  8790. };
  8791. /**
  8792. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8793. * @param func: callback function to add
  8794. */
  8795. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8796. this._onAfterWorldMatrixUpdate.push(func);
  8797. };
  8798. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8799. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8800. if (index > -1) {
  8801. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8802. }
  8803. };
  8804. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8805. this.computeWorldMatrix();
  8806. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8807. };
  8808. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8809. this.computeWorldMatrix();
  8810. var invLocalWorldMatrix = this._localWorld.clone();
  8811. invLocalWorldMatrix.invert();
  8812. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8813. };
  8814. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8815. this.computeWorldMatrix();
  8816. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8817. };
  8818. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8819. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8820. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8821. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8822. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8823. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8824. /// <returns>Mesh oriented towards targetMesh</returns>
  8825. yawCor = yawCor || 0; // default to zero if undefined
  8826. pitchCor = pitchCor || 0;
  8827. rollCor = rollCor || 0;
  8828. var dv = targetPoint.subtract(this.position);
  8829. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8830. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8831. var pitch = Math.atan2(dv.y, len);
  8832. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8833. };
  8834. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8835. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8836. return false;
  8837. }
  8838. return true;
  8839. };
  8840. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8841. if (!camera) {
  8842. camera = this.getScene().activeCamera;
  8843. }
  8844. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8845. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8846. return false;
  8847. }
  8848. return true;
  8849. };
  8850. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8851. if (!this._boundingInfo || !mesh._boundingInfo) {
  8852. return false;
  8853. }
  8854. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8855. };
  8856. AbstractMesh.prototype.intersectsPoint = function (point) {
  8857. if (!this._boundingInfo) {
  8858. return false;
  8859. }
  8860. return this._boundingInfo.intersectsPoint(point);
  8861. };
  8862. // Physics
  8863. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8864. var physicsEngine = this.getScene().getPhysicsEngine();
  8865. if (!physicsEngine) {
  8866. return;
  8867. }
  8868. if (impostor.impostor) {
  8869. // Old API
  8870. options = impostor;
  8871. impostor = impostor.impostor;
  8872. }
  8873. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8874. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8875. physicsEngine._unregisterMesh(this);
  8876. return;
  8877. }
  8878. options.mass = options.mass || 0;
  8879. options.friction = options.friction || 0.2;
  8880. options.restitution = options.restitution || 0.2;
  8881. this._physicImpostor = impostor;
  8882. this._physicsMass = options.mass;
  8883. this._physicsFriction = options.friction;
  8884. this._physicRestitution = options.restitution;
  8885. return physicsEngine._registerMesh(this, impostor, options);
  8886. };
  8887. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8888. if (!this._physicImpostor) {
  8889. return BABYLON.PhysicsEngine.NoImpostor;
  8890. }
  8891. return this._physicImpostor;
  8892. };
  8893. AbstractMesh.prototype.getPhysicsMass = function () {
  8894. if (!this._physicsMass) {
  8895. return 0;
  8896. }
  8897. return this._physicsMass;
  8898. };
  8899. AbstractMesh.prototype.getPhysicsFriction = function () {
  8900. if (!this._physicsFriction) {
  8901. return 0;
  8902. }
  8903. return this._physicsFriction;
  8904. };
  8905. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8906. if (!this._physicRestitution) {
  8907. return 0;
  8908. }
  8909. return this._physicRestitution;
  8910. };
  8911. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8912. if (!camera) {
  8913. camera = this.getScene().activeCamera;
  8914. }
  8915. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8916. };
  8917. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8918. if (!camera) {
  8919. camera = this.getScene().activeCamera;
  8920. }
  8921. return this.absolutePosition.subtract(camera.position).length();
  8922. };
  8923. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8924. if (!this._physicImpostor) {
  8925. return;
  8926. }
  8927. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8928. };
  8929. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8930. if (!this._physicImpostor) {
  8931. return;
  8932. }
  8933. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8934. };
  8935. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8936. if (!this._physicImpostor) {
  8937. return;
  8938. }
  8939. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8940. };
  8941. // Collisions
  8942. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8943. var globalPosition = this.getAbsolutePosition();
  8944. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8945. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8946. this._collider.radius = this.ellipsoid;
  8947. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8948. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8949. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8950. this.position.addInPlace(this._diffPositionForCollisions);
  8951. }
  8952. };
  8953. // Submeshes octree
  8954. /**
  8955. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8956. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8957. */
  8958. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8959. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8960. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8961. if (!this._submeshesOctree) {
  8962. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8963. }
  8964. this.computeWorldMatrix(true);
  8965. // Update octree
  8966. var bbox = this.getBoundingInfo().boundingBox;
  8967. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8968. return this._submeshesOctree;
  8969. };
  8970. // Collisions
  8971. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8972. this._generatePointsArray();
  8973. // Transformation
  8974. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8975. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8976. subMesh._lastColliderWorldVertices = [];
  8977. subMesh._trianglePlanes = [];
  8978. var start = subMesh.verticesStart;
  8979. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8980. for (var i = start; i < end; i++) {
  8981. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8982. }
  8983. }
  8984. // Collide
  8985. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8986. };
  8987. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8988. var subMeshes;
  8989. var len;
  8990. // Octrees
  8991. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8992. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8993. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8994. len = intersections.length;
  8995. subMeshes = intersections.data;
  8996. } else {
  8997. subMeshes = this.subMeshes;
  8998. len = subMeshes.length;
  8999. }
  9000. for (var index = 0; index < len; index++) {
  9001. var subMesh = subMeshes[index];
  9002. // Bounding test
  9003. if (len > 1 && !subMesh._checkCollision(collider))
  9004. continue;
  9005. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9006. }
  9007. };
  9008. AbstractMesh.prototype._checkCollision = function (collider) {
  9009. // Bounding box test
  9010. if (!this._boundingInfo._checkCollision(collider))
  9011. return;
  9012. // Transformation matrix
  9013. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9014. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9015. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9016. };
  9017. // Picking
  9018. AbstractMesh.prototype._generatePointsArray = function () {
  9019. return false;
  9020. };
  9021. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9022. var pickingInfo = new BABYLON.PickingInfo();
  9023. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9024. return pickingInfo;
  9025. }
  9026. if (!this._generatePointsArray()) {
  9027. return pickingInfo;
  9028. }
  9029. var intersectInfo = null;
  9030. // Octrees
  9031. var subMeshes;
  9032. var len;
  9033. if (this._submeshesOctree && this.useOctreeForPicking) {
  9034. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9035. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9036. len = intersections.length;
  9037. subMeshes = intersections.data;
  9038. } else {
  9039. subMeshes = this.subMeshes;
  9040. len = subMeshes.length;
  9041. }
  9042. for (var index = 0; index < len; index++) {
  9043. var subMesh = subMeshes[index];
  9044. // Bounding test
  9045. if (len > 1 && !subMesh.canIntersects(ray))
  9046. continue;
  9047. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9048. if (currentIntersectInfo) {
  9049. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9050. intersectInfo = currentIntersectInfo;
  9051. if (fastCheck) {
  9052. break;
  9053. }
  9054. }
  9055. }
  9056. }
  9057. if (intersectInfo) {
  9058. // Get picked point
  9059. var world = this.getWorldMatrix();
  9060. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9061. var direction = ray.direction.clone();
  9062. direction.normalize();
  9063. direction = direction.scale(intersectInfo.distance);
  9064. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9065. var pickedPoint = worldOrigin.add(worldDirection);
  9066. // Return result
  9067. pickingInfo.hit = true;
  9068. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9069. pickingInfo.pickedPoint = pickedPoint;
  9070. pickingInfo.pickedMesh = this;
  9071. pickingInfo.bu = intersectInfo.bu;
  9072. pickingInfo.bv = intersectInfo.bv;
  9073. pickingInfo.faceId = intersectInfo.faceId;
  9074. return pickingInfo;
  9075. }
  9076. return pickingInfo;
  9077. };
  9078. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9079. return null;
  9080. };
  9081. AbstractMesh.prototype.releaseSubMeshes = function () {
  9082. if (this.subMeshes) {
  9083. while (this.subMeshes.length) {
  9084. this.subMeshes[0].dispose();
  9085. }
  9086. } else {
  9087. this.subMeshes = new Array();
  9088. }
  9089. };
  9090. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9091. // Physics
  9092. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9093. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9094. }
  9095. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9096. var other = this._intersectionsInProgress[index];
  9097. var pos = other._intersectionsInProgress.indexOf(this);
  9098. other._intersectionsInProgress.splice(pos, 1);
  9099. }
  9100. this._intersectionsInProgress = [];
  9101. // SubMeshes
  9102. this.releaseSubMeshes();
  9103. // Remove from scene
  9104. var index = this.getScene().meshes.indexOf(this);
  9105. if (index != -1) {
  9106. // Remove from the scene if mesh found
  9107. this.getScene().meshes.splice(index, 1);
  9108. }
  9109. if (!doNotRecurse) {
  9110. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9111. if (this.getScene().particleSystems[index].emitter == this) {
  9112. this.getScene().particleSystems[index].dispose();
  9113. index--;
  9114. }
  9115. }
  9116. // Children
  9117. var objects = this.getScene().meshes.slice(0);
  9118. for (index = 0; index < objects.length; index++) {
  9119. if (objects[index].parent == this) {
  9120. objects[index].dispose();
  9121. }
  9122. }
  9123. } else {
  9124. for (index = 0; index < this.getScene().meshes.length; index++) {
  9125. var obj = this.getScene().meshes[index];
  9126. if (obj.parent === this) {
  9127. obj.parent = null;
  9128. obj.computeWorldMatrix(true);
  9129. }
  9130. }
  9131. }
  9132. this._onAfterWorldMatrixUpdate = [];
  9133. this._isDisposed = true;
  9134. // Callback
  9135. if (this.onDispose) {
  9136. this.onDispose();
  9137. }
  9138. };
  9139. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9140. AbstractMesh._BILLBOARDMODE_X = 1;
  9141. AbstractMesh._BILLBOARDMODE_Y = 2;
  9142. AbstractMesh._BILLBOARDMODE_Z = 4;
  9143. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9144. return AbstractMesh;
  9145. })(BABYLON.Node);
  9146. BABYLON.AbstractMesh = AbstractMesh;
  9147. })(BABYLON || (BABYLON = {}));
  9148. //# sourceMappingURL=babylon.abstractMesh.js.map
  9149. var BABYLON;
  9150. (function (BABYLON) {
  9151. var _InstancesBatch = (function () {
  9152. function _InstancesBatch() {
  9153. this.mustReturn = false;
  9154. this.visibleInstances = new Array();
  9155. this.renderSelf = new Array();
  9156. }
  9157. return _InstancesBatch;
  9158. })();
  9159. BABYLON._InstancesBatch = _InstancesBatch;
  9160. var Mesh = (function (_super) {
  9161. __extends(Mesh, _super);
  9162. /**
  9163. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9164. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9165. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9166. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9167. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9168. * When false, achieved by calling a clone(), also passing False.
  9169. * This will make creation of children, recursive.
  9170. */
  9171. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9172. if (typeof parent === "undefined") { parent = null; }
  9173. _super.call(this, name, scene);
  9174. // Members
  9175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9176. this.instances = new Array();
  9177. this._LODLevels = new Array();
  9178. this._onBeforeRenderCallbacks = new Array();
  9179. this._onAfterRenderCallbacks = new Array();
  9180. this._visibleInstances = {};
  9181. this._renderIdForInstances = new Array();
  9182. this._batchCache = new _InstancesBatch();
  9183. this._instancesBufferSize = 32 * 16 * 4;
  9184. if (source) {
  9185. // Geometry
  9186. if (source._geometry) {
  9187. source._geometry.applyToMesh(this);
  9188. }
  9189. // Deep copy
  9190. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9191. // Material
  9192. this.material = source.material;
  9193. if (!doNotCloneChildren) {
  9194. for (var index = 0; index < scene.meshes.length; index++) {
  9195. var mesh = scene.meshes[index];
  9196. if (mesh.parent === source) {
  9197. // doNotCloneChildren is always going to be False
  9198. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9199. }
  9200. }
  9201. }
  9202. for (index = 0; index < scene.particleSystems.length; index++) {
  9203. var system = scene.particleSystems[index];
  9204. if (system.emitter === source) {
  9205. system.clone(system.name, this);
  9206. }
  9207. }
  9208. this.computeWorldMatrix(true);
  9209. }
  9210. // Parent
  9211. if (parent !== null) {
  9212. this.parent = parent;
  9213. }
  9214. }
  9215. Mesh.prototype._clone = function () {
  9216. };
  9217. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9218. // Methods
  9219. get: function () {
  9220. return this._LODLevels.length > 0;
  9221. },
  9222. enumerable: true,
  9223. configurable: true
  9224. });
  9225. Mesh.prototype._sortLODLevels = function () {
  9226. this._LODLevels.sort(function (a, b) {
  9227. if (a.distance < b.distance) {
  9228. return 1;
  9229. }
  9230. if (a.distance > b.distance) {
  9231. return -1;
  9232. }
  9233. return 0;
  9234. });
  9235. };
  9236. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9237. if (mesh && mesh._masterMesh) {
  9238. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9239. return this;
  9240. }
  9241. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9242. this._LODLevels.push(level);
  9243. if (mesh) {
  9244. mesh._masterMesh = this;
  9245. }
  9246. this._sortLODLevels();
  9247. return this;
  9248. };
  9249. Mesh.prototype.removeLODLevel = function (mesh) {
  9250. for (var index = 0; index < this._LODLevels.length; index++) {
  9251. if (this._LODLevels[index].mesh === mesh) {
  9252. this._LODLevels.splice(index, 1);
  9253. if (mesh) {
  9254. mesh._masterMesh = null;
  9255. }
  9256. }
  9257. }
  9258. this._sortLODLevels();
  9259. return this;
  9260. };
  9261. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9262. if (!this._LODLevels || this._LODLevels.length === 0) {
  9263. return this;
  9264. }
  9265. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9266. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9267. return this;
  9268. }
  9269. for (var index = 0; index < this._LODLevels.length; index++) {
  9270. var level = this._LODLevels[index];
  9271. if (level.distance < distanceToCamera) {
  9272. if (level.mesh) {
  9273. level.mesh._preActivate();
  9274. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9275. }
  9276. return level.mesh;
  9277. }
  9278. }
  9279. return this;
  9280. };
  9281. Object.defineProperty(Mesh.prototype, "geometry", {
  9282. get: function () {
  9283. return this._geometry;
  9284. },
  9285. enumerable: true,
  9286. configurable: true
  9287. });
  9288. Mesh.prototype.getTotalVertices = function () {
  9289. if (!this._geometry) {
  9290. return 0;
  9291. }
  9292. return this._geometry.getTotalVertices();
  9293. };
  9294. Mesh.prototype.getVerticesData = function (kind) {
  9295. if (!this._geometry) {
  9296. return null;
  9297. }
  9298. return this._geometry.getVerticesData(kind);
  9299. };
  9300. Mesh.prototype.getVertexBuffer = function (kind) {
  9301. if (!this._geometry) {
  9302. return undefined;
  9303. }
  9304. return this._geometry.getVertexBuffer(kind);
  9305. };
  9306. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9307. if (!this._geometry) {
  9308. if (this._delayInfo) {
  9309. return this._delayInfo.indexOf(kind) !== -1;
  9310. }
  9311. return false;
  9312. }
  9313. return this._geometry.isVerticesDataPresent(kind);
  9314. };
  9315. Mesh.prototype.getVerticesDataKinds = function () {
  9316. if (!this._geometry) {
  9317. var result = [];
  9318. if (this._delayInfo) {
  9319. for (var kind in this._delayInfo) {
  9320. result.push(kind);
  9321. }
  9322. }
  9323. return result;
  9324. }
  9325. return this._geometry.getVerticesDataKinds();
  9326. };
  9327. Mesh.prototype.getTotalIndices = function () {
  9328. if (!this._geometry) {
  9329. return 0;
  9330. }
  9331. return this._geometry.getTotalIndices();
  9332. };
  9333. Mesh.prototype.getIndices = function () {
  9334. if (!this._geometry) {
  9335. return [];
  9336. }
  9337. return this._geometry.getIndices();
  9338. };
  9339. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9340. get: function () {
  9341. return this._masterMesh !== null && this._masterMesh !== undefined;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Mesh.prototype.isReady = function () {
  9347. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9348. return false;
  9349. }
  9350. return _super.prototype.isReady.call(this);
  9351. };
  9352. Mesh.prototype.isDisposed = function () {
  9353. return this._isDisposed;
  9354. };
  9355. // Methods
  9356. Mesh.prototype._preActivate = function () {
  9357. var sceneRenderId = this.getScene().getRenderId();
  9358. if (this._preActivateId == sceneRenderId) {
  9359. return;
  9360. }
  9361. this._preActivateId = sceneRenderId;
  9362. this._visibleInstances = null;
  9363. };
  9364. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9365. if (!this._visibleInstances) {
  9366. this._visibleInstances = {};
  9367. this._visibleInstances.defaultRenderId = renderId;
  9368. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9369. }
  9370. if (!this._visibleInstances[renderId]) {
  9371. this._visibleInstances[renderId] = new Array();
  9372. }
  9373. this._visibleInstances[renderId].push(instance);
  9374. };
  9375. Mesh.prototype.refreshBoundingInfo = function () {
  9376. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9377. if (data) {
  9378. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9379. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9380. }
  9381. if (this.subMeshes) {
  9382. for (var index = 0; index < this.subMeshes.length; index++) {
  9383. this.subMeshes[index].refreshBoundingInfo();
  9384. }
  9385. }
  9386. this._updateBoundingInfo();
  9387. };
  9388. Mesh.prototype._createGlobalSubMesh = function () {
  9389. var totalVertices = this.getTotalVertices();
  9390. if (!totalVertices || !this.getIndices()) {
  9391. return null;
  9392. }
  9393. this.releaseSubMeshes();
  9394. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9395. };
  9396. Mesh.prototype.subdivide = function (count) {
  9397. if (count < 1) {
  9398. return;
  9399. }
  9400. var totalIndices = this.getTotalIndices();
  9401. var subdivisionSize = (totalIndices / count) | 0;
  9402. var offset = 0;
  9403. while (subdivisionSize % 3 != 0) {
  9404. subdivisionSize++;
  9405. }
  9406. this.releaseSubMeshes();
  9407. for (var index = 0; index < count; index++) {
  9408. if (offset >= totalIndices) {
  9409. break;
  9410. }
  9411. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9412. offset += subdivisionSize;
  9413. }
  9414. this.synchronizeInstances();
  9415. };
  9416. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9417. if (kind instanceof Array) {
  9418. var temp = data;
  9419. data = kind;
  9420. kind = temp;
  9421. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9422. }
  9423. if (!this._geometry) {
  9424. var vertexData = new BABYLON.VertexData();
  9425. vertexData.set(data, kind);
  9426. var scene = this.getScene();
  9427. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9428. } else {
  9429. this._geometry.setVerticesData(kind, data, updatable, stride);
  9430. }
  9431. };
  9432. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9433. if (!this._geometry) {
  9434. return;
  9435. }
  9436. if (!makeItUnique) {
  9437. this._geometry.updateVerticesData(kind, data, updateExtends);
  9438. } else {
  9439. this.makeGeometryUnique();
  9440. this.updateVerticesData(kind, data, updateExtends, false);
  9441. }
  9442. };
  9443. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9444. if (!this._geometry) {
  9445. return;
  9446. }
  9447. if (!makeItUnique) {
  9448. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9449. } else {
  9450. this.makeGeometryUnique();
  9451. this.updateVerticesDataDirectly(kind, data, offset, false);
  9452. }
  9453. };
  9454. Mesh.prototype.makeGeometryUnique = function () {
  9455. if (!this._geometry) {
  9456. return;
  9457. }
  9458. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9459. geometry.applyToMesh(this);
  9460. };
  9461. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9462. if (!this._geometry) {
  9463. var vertexData = new BABYLON.VertexData();
  9464. vertexData.indices = indices;
  9465. var scene = this.getScene();
  9466. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9467. } else {
  9468. this._geometry.setIndices(indices, totalVertices);
  9469. }
  9470. };
  9471. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9472. var engine = this.getScene().getEngine();
  9473. // Wireframe
  9474. var indexToBind;
  9475. switch (fillMode) {
  9476. case BABYLON.Material.PointFillMode:
  9477. indexToBind = null;
  9478. break;
  9479. case BABYLON.Material.WireFrameFillMode:
  9480. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9481. break;
  9482. default:
  9483. case BABYLON.Material.TriangleFillMode:
  9484. indexToBind = this._geometry.getIndexBuffer();
  9485. break;
  9486. }
  9487. // VBOs
  9488. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9489. };
  9490. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9491. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9492. return;
  9493. }
  9494. var engine = this.getScene().getEngine();
  9495. switch (fillMode) {
  9496. case BABYLON.Material.PointFillMode:
  9497. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9498. break;
  9499. case BABYLON.Material.WireFrameFillMode:
  9500. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9501. break;
  9502. default:
  9503. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9504. }
  9505. };
  9506. Mesh.prototype.registerBeforeRender = function (func) {
  9507. this._onBeforeRenderCallbacks.push(func);
  9508. };
  9509. Mesh.prototype.unregisterBeforeRender = function (func) {
  9510. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9511. if (index > -1) {
  9512. this._onBeforeRenderCallbacks.splice(index, 1);
  9513. }
  9514. };
  9515. Mesh.prototype.registerAfterRender = function (func) {
  9516. this._onAfterRenderCallbacks.push(func);
  9517. };
  9518. Mesh.prototype.unregisterAfterRender = function (func) {
  9519. var index = this._onAfterRenderCallbacks.indexOf(func);
  9520. if (index > -1) {
  9521. this._onAfterRenderCallbacks.splice(index, 1);
  9522. }
  9523. };
  9524. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9525. var scene = this.getScene();
  9526. this._batchCache.mustReturn = false;
  9527. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9528. this._batchCache.visibleInstances[subMeshId] = null;
  9529. if (this._visibleInstances) {
  9530. var currentRenderId = scene.getRenderId();
  9531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9532. var selfRenderId = this._renderId;
  9533. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9534. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9535. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9536. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9537. }
  9538. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9539. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9540. this._batchCache.mustReturn = true;
  9541. return this._batchCache;
  9542. }
  9543. if (currentRenderId !== selfRenderId) {
  9544. this._batchCache.renderSelf[subMeshId] = false;
  9545. }
  9546. }
  9547. this._renderIdForInstances[subMeshId] = currentRenderId;
  9548. }
  9549. return this._batchCache;
  9550. };
  9551. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9552. var visibleInstances = batch.visibleInstances[subMesh._id];
  9553. var matricesCount = visibleInstances.length + 1;
  9554. var bufferSize = matricesCount * 16 * 4;
  9555. while (this._instancesBufferSize < bufferSize) {
  9556. this._instancesBufferSize *= 2;
  9557. }
  9558. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9559. if (this._worldMatricesInstancesBuffer) {
  9560. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9561. }
  9562. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9563. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9564. }
  9565. var offset = 0;
  9566. var instancesCount = 0;
  9567. var world = this.getWorldMatrix();
  9568. if (batch.renderSelf[subMesh._id]) {
  9569. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9570. offset += 16;
  9571. instancesCount++;
  9572. }
  9573. if (visibleInstances) {
  9574. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9575. var instance = visibleInstances[instanceIndex];
  9576. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9577. offset += 16;
  9578. instancesCount++;
  9579. }
  9580. }
  9581. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9582. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9583. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9584. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9585. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9586. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9587. this._draw(subMesh, fillMode, instancesCount);
  9588. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9589. };
  9590. Mesh.prototype.render = function (subMesh) {
  9591. var scene = this.getScene();
  9592. // Managing instances
  9593. var batch = this._getInstancesRenderList(subMesh._id);
  9594. if (batch.mustReturn) {
  9595. return;
  9596. }
  9597. // Checking geometry state
  9598. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9599. return;
  9600. }
  9601. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9602. this._onBeforeRenderCallbacks[callbackIndex]();
  9603. }
  9604. var engine = scene.getEngine();
  9605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9606. // Material
  9607. var effectiveMaterial = subMesh.getMaterial();
  9608. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9609. return;
  9610. }
  9611. // Outline - step 1
  9612. var savedDepthWrite = engine.getDepthWrite();
  9613. if (this.renderOutline) {
  9614. engine.setDepthWrite(false);
  9615. scene.getOutlineRenderer().render(subMesh, batch);
  9616. engine.setDepthWrite(savedDepthWrite);
  9617. }
  9618. effectiveMaterial._preBind();
  9619. var effect = effectiveMaterial.getEffect();
  9620. // Bind
  9621. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9622. this._bind(subMesh, effect, fillMode);
  9623. var world = this.getWorldMatrix();
  9624. effectiveMaterial.bind(world, this);
  9625. // Instances rendering
  9626. if (hardwareInstancedRendering) {
  9627. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9628. } else {
  9629. if (batch.renderSelf[subMesh._id]) {
  9630. // Draw
  9631. this._draw(subMesh, fillMode);
  9632. }
  9633. if (batch.visibleInstances[subMesh._id]) {
  9634. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9635. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9636. // World
  9637. world = instance.getWorldMatrix();
  9638. effectiveMaterial.bindOnlyWorldMatrix(world);
  9639. // Draw
  9640. this._draw(subMesh, fillMode);
  9641. }
  9642. }
  9643. }
  9644. // Unbind
  9645. effectiveMaterial.unbind();
  9646. // Outline - step 2
  9647. if (this.renderOutline && savedDepthWrite) {
  9648. engine.setDepthWrite(true);
  9649. engine.setColorWrite(false);
  9650. scene.getOutlineRenderer().render(subMesh, batch);
  9651. engine.setColorWrite(true);
  9652. }
  9653. // Overlay
  9654. if (this.renderOverlay) {
  9655. var currentMode = engine.getAlphaMode();
  9656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9657. scene.getOutlineRenderer().render(subMesh, batch, true);
  9658. engine.setAlphaMode(currentMode);
  9659. }
  9660. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9661. this._onAfterRenderCallbacks[callbackIndex]();
  9662. }
  9663. };
  9664. Mesh.prototype.getEmittedParticleSystems = function () {
  9665. var results = new Array();
  9666. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9667. var particleSystem = this.getScene().particleSystems[index];
  9668. if (particleSystem.emitter === this) {
  9669. results.push(particleSystem);
  9670. }
  9671. }
  9672. return results;
  9673. };
  9674. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9675. var results = new Array();
  9676. var descendants = this.getDescendants();
  9677. descendants.push(this);
  9678. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9679. var particleSystem = this.getScene().particleSystems[index];
  9680. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9681. results.push(particleSystem);
  9682. }
  9683. }
  9684. return results;
  9685. };
  9686. Mesh.prototype.getChildren = function () {
  9687. var results = [];
  9688. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9689. var mesh = this.getScene().meshes[index];
  9690. if (mesh.parent == this) {
  9691. results.push(mesh);
  9692. }
  9693. }
  9694. return results;
  9695. };
  9696. Mesh.prototype._checkDelayState = function () {
  9697. var _this = this;
  9698. var that = this;
  9699. var scene = this.getScene();
  9700. if (this._geometry) {
  9701. this._geometry.load(scene);
  9702. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9703. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9704. scene._addPendingData(that);
  9705. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9706. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9707. if (data instanceof ArrayBuffer) {
  9708. _this._delayLoadingFunction(data, _this);
  9709. } else {
  9710. _this._delayLoadingFunction(JSON.parse(data), _this);
  9711. }
  9712. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9713. scene._removePendingData(_this);
  9714. }, function () {
  9715. }, scene.database, getBinaryData);
  9716. }
  9717. };
  9718. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9719. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9720. return false;
  9721. }
  9722. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9723. return false;
  9724. }
  9725. this._checkDelayState();
  9726. return true;
  9727. };
  9728. Mesh.prototype.setMaterialByID = function (id) {
  9729. var materials = this.getScene().materials;
  9730. for (var index = 0; index < materials.length; index++) {
  9731. if (materials[index].id == id) {
  9732. this.material = materials[index];
  9733. return;
  9734. }
  9735. }
  9736. // Multi
  9737. var multiMaterials = this.getScene().multiMaterials;
  9738. for (index = 0; index < multiMaterials.length; index++) {
  9739. if (multiMaterials[index].id == id) {
  9740. this.material = multiMaterials[index];
  9741. return;
  9742. }
  9743. }
  9744. };
  9745. Mesh.prototype.getAnimatables = function () {
  9746. var results = [];
  9747. if (this.material) {
  9748. results.push(this.material);
  9749. }
  9750. if (this.skeleton) {
  9751. results.push(this.skeleton);
  9752. }
  9753. return results;
  9754. };
  9755. // Geometry
  9756. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9757. // Position
  9758. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9759. return;
  9760. }
  9761. this._resetPointsArrayCache();
  9762. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9763. var temp = [];
  9764. for (var index = 0; index < data.length; index += 3) {
  9765. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9766. }
  9767. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9768. // Normals
  9769. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9770. return;
  9771. }
  9772. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9773. for (index = 0; index < data.length; index += 3) {
  9774. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9775. }
  9776. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9777. };
  9778. // Cache
  9779. Mesh.prototype._resetPointsArrayCache = function () {
  9780. this._positions = null;
  9781. };
  9782. Mesh.prototype._generatePointsArray = function () {
  9783. if (this._positions)
  9784. return true;
  9785. this._positions = [];
  9786. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9787. if (!data) {
  9788. return false;
  9789. }
  9790. for (var index = 0; index < data.length; index += 3) {
  9791. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9792. }
  9793. return true;
  9794. };
  9795. // Clone
  9796. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9797. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9798. };
  9799. // Dispose
  9800. Mesh.prototype.dispose = function (doNotRecurse) {
  9801. if (this._geometry) {
  9802. this._geometry.releaseForMesh(this, true);
  9803. }
  9804. // Instances
  9805. if (this._worldMatricesInstancesBuffer) {
  9806. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9807. this._worldMatricesInstancesBuffer = null;
  9808. }
  9809. while (this.instances.length) {
  9810. this.instances[0].dispose();
  9811. }
  9812. _super.prototype.dispose.call(this, doNotRecurse);
  9813. };
  9814. // Geometric tools
  9815. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9816. var _this = this;
  9817. var scene = this.getScene();
  9818. var onload = function (img) {
  9819. // Getting height map data
  9820. var canvas = document.createElement("canvas");
  9821. var context = canvas.getContext("2d");
  9822. var heightMapWidth = img.width;
  9823. var heightMapHeight = img.height;
  9824. canvas.width = heightMapWidth;
  9825. canvas.height = heightMapHeight;
  9826. context.drawImage(img, 0, 0);
  9827. // Create VertexData from map data
  9828. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9829. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9830. };
  9831. BABYLON.Tools.LoadImage(url, onload, function () {
  9832. }, scene.database);
  9833. };
  9834. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9835. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9836. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9837. return;
  9838. }
  9839. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9840. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9841. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9842. var position = BABYLON.Vector3.Zero();
  9843. var normal = BABYLON.Vector3.Zero();
  9844. var uv = BABYLON.Vector2.Zero();
  9845. for (var index = 0; index < positions.length; index += 3) {
  9846. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9847. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9848. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9849. // Compute height
  9850. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9851. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9852. var pos = (u + v * heightMapWidth) * 4;
  9853. var r = buffer[pos] / 255.0;
  9854. var g = buffer[pos + 1] / 255.0;
  9855. var b = buffer[pos + 2] / 255.0;
  9856. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9857. normal.normalize();
  9858. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9859. position = position.add(normal);
  9860. position.toArray(positions, index);
  9861. }
  9862. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9863. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9864. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9865. };
  9866. Mesh.prototype.convertToFlatShadedMesh = function () {
  9867. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9868. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9869. var kinds = this.getVerticesDataKinds();
  9870. var vbs = [];
  9871. var data = [];
  9872. var newdata = [];
  9873. var updatableNormals = false;
  9874. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9875. var kind = kinds[kindIndex];
  9876. var vertexBuffer = this.getVertexBuffer(kind);
  9877. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9878. updatableNormals = vertexBuffer.isUpdatable();
  9879. kinds.splice(kindIndex, 1);
  9880. kindIndex--;
  9881. continue;
  9882. }
  9883. vbs[kind] = vertexBuffer;
  9884. data[kind] = vbs[kind].getData();
  9885. newdata[kind] = [];
  9886. }
  9887. // Save previous submeshes
  9888. var previousSubmeshes = this.subMeshes.slice(0);
  9889. var indices = this.getIndices();
  9890. var totalIndices = this.getTotalIndices();
  9891. for (index = 0; index < totalIndices; index++) {
  9892. var vertexIndex = indices[index];
  9893. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9894. kind = kinds[kindIndex];
  9895. var stride = vbs[kind].getStrideSize();
  9896. for (var offset = 0; offset < stride; offset++) {
  9897. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9898. }
  9899. }
  9900. }
  9901. // Updating faces & normal
  9902. var normals = [];
  9903. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9904. for (var index = 0; index < totalIndices; index += 3) {
  9905. indices[index] = index;
  9906. indices[index + 1] = index + 1;
  9907. indices[index + 2] = index + 2;
  9908. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9909. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9910. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9911. var p1p2 = p1.subtract(p2);
  9912. var p3p2 = p3.subtract(p2);
  9913. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9914. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9915. normals.push(normal.x);
  9916. normals.push(normal.y);
  9917. normals.push(normal.z);
  9918. }
  9919. }
  9920. this.setIndices(indices);
  9921. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9922. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9923. kind = kinds[kindIndex];
  9924. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9925. }
  9926. // Updating submeshes
  9927. this.releaseSubMeshes();
  9928. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9929. var previousOne = previousSubmeshes[submeshIndex];
  9930. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9931. }
  9932. this.synchronizeInstances();
  9933. };
  9934. // Instances
  9935. Mesh.prototype.createInstance = function (name) {
  9936. return new BABYLON.InstancedMesh(name, this);
  9937. };
  9938. Mesh.prototype.synchronizeInstances = function () {
  9939. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9940. var instance = this.instances[instanceIndex];
  9941. instance._syncSubMeshes();
  9942. }
  9943. };
  9944. // Statics
  9945. Mesh.CreateBox = function (name, size, scene, updatable) {
  9946. var box = new BABYLON.Mesh(name, scene);
  9947. var vertexData = BABYLON.VertexData.CreateBox(size);
  9948. vertexData.applyToMesh(box, updatable);
  9949. return box;
  9950. };
  9951. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9952. var sphere = new BABYLON.Mesh(name, scene);
  9953. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9954. vertexData.applyToMesh(sphere, updatable);
  9955. return sphere;
  9956. };
  9957. // Cylinder and cone (Code inspired by SharpDX.org)
  9958. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9959. // subdivisions is a new parameter, we need to support old signature
  9960. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9961. if (scene !== undefined) {
  9962. updatable = scene;
  9963. }
  9964. scene = subdivisions;
  9965. subdivisions = 1;
  9966. }
  9967. var cylinder = new BABYLON.Mesh(name, scene);
  9968. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9969. vertexData.applyToMesh(cylinder, updatable);
  9970. return cylinder;
  9971. };
  9972. // Torus (Code from SharpDX.org)
  9973. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9974. var torus = new BABYLON.Mesh(name, scene);
  9975. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9976. vertexData.applyToMesh(torus, updatable);
  9977. return torus;
  9978. };
  9979. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9980. var torusKnot = new BABYLON.Mesh(name, scene);
  9981. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9982. vertexData.applyToMesh(torusKnot, updatable);
  9983. return torusKnot;
  9984. };
  9985. // Lines
  9986. Mesh.CreateLines = function (name, points, scene, updatable) {
  9987. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9988. var vertexData = BABYLON.VertexData.CreateLines(points);
  9989. vertexData.applyToMesh(lines, updatable);
  9990. return lines;
  9991. };
  9992. // Plane & ground
  9993. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9994. var plane = new BABYLON.Mesh(name, scene);
  9995. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9996. vertexData.applyToMesh(plane, updatable);
  9997. return plane;
  9998. };
  9999. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10000. var ground = new BABYLON.GroundMesh(name, scene);
  10001. ground._setReady(false);
  10002. ground._subdivisions = subdivisions;
  10003. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10004. vertexData.applyToMesh(ground, updatable);
  10005. ground._setReady(true);
  10006. return ground;
  10007. };
  10008. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10009. var tiledGround = new BABYLON.Mesh(name, scene);
  10010. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10011. vertexData.applyToMesh(tiledGround, updatable);
  10012. return tiledGround;
  10013. };
  10014. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10015. var ground = new BABYLON.GroundMesh(name, scene);
  10016. ground._subdivisions = subdivisions;
  10017. ground._setReady(false);
  10018. var onload = function (img) {
  10019. // Getting height map data
  10020. var canvas = document.createElement("canvas");
  10021. var context = canvas.getContext("2d");
  10022. var heightMapWidth = img.width;
  10023. var heightMapHeight = img.height;
  10024. canvas.width = heightMapWidth;
  10025. canvas.height = heightMapHeight;
  10026. context.drawImage(img, 0, 0);
  10027. // Create VertexData from map data
  10028. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10029. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10030. vertexData.applyToMesh(ground, updatable);
  10031. ground._setReady(true);
  10032. };
  10033. BABYLON.Tools.LoadImage(url, onload, function () {
  10034. }, scene.database);
  10035. return ground;
  10036. };
  10037. // Tools
  10038. Mesh.MinMax = function (meshes) {
  10039. var minVector = null;
  10040. var maxVector = null;
  10041. for (var i in meshes) {
  10042. var mesh = meshes[i];
  10043. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10044. if (!minVector) {
  10045. minVector = boundingBox.minimumWorld;
  10046. maxVector = boundingBox.maximumWorld;
  10047. continue;
  10048. }
  10049. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10050. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10051. }
  10052. return {
  10053. min: minVector,
  10054. max: maxVector
  10055. };
  10056. };
  10057. Mesh.Center = function (meshesOrMinMaxVector) {
  10058. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10059. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10060. };
  10061. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10062. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10063. var source = meshes[0];
  10064. var material = source.material;
  10065. var scene = source.getScene();
  10066. if (!allow32BitsIndices) {
  10067. var totalVertices = 0;
  10068. for (var index = 0; index < meshes.length; index++) {
  10069. totalVertices += meshes[index].getTotalVertices();
  10070. if (totalVertices > 65536) {
  10071. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10072. return null;
  10073. }
  10074. }
  10075. }
  10076. // Merge
  10077. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10078. vertexData.transform(source.getWorldMatrix());
  10079. for (index = 1; index < meshes.length; index++) {
  10080. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10081. otherVertexData.transform(meshes[index].getWorldMatrix());
  10082. vertexData.merge(otherVertexData);
  10083. }
  10084. var newMesh = new Mesh(source.name + "_merged", scene);
  10085. vertexData.applyToMesh(newMesh);
  10086. // Setting properties
  10087. newMesh.material = material;
  10088. newMesh.checkCollisions = source.checkCollisions;
  10089. // Cleaning
  10090. if (disposeSource) {
  10091. for (index = 0; index < meshes.length; index++) {
  10092. meshes[index].dispose();
  10093. }
  10094. }
  10095. return newMesh;
  10096. };
  10097. return Mesh;
  10098. })(BABYLON.AbstractMesh);
  10099. BABYLON.Mesh = Mesh;
  10100. })(BABYLON || (BABYLON = {}));
  10101. //# sourceMappingURL=babylon.mesh.js.map
  10102. var BABYLON;
  10103. (function (BABYLON) {
  10104. var GroundMesh = (function (_super) {
  10105. __extends(GroundMesh, _super);
  10106. function GroundMesh(name, scene) {
  10107. _super.call(this, name, scene);
  10108. this.generateOctree = false;
  10109. this._worldInverse = new BABYLON.Matrix();
  10110. }
  10111. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10112. get: function () {
  10113. return this._subdivisions;
  10114. },
  10115. enumerable: true,
  10116. configurable: true
  10117. });
  10118. GroundMesh.prototype.optimize = function (chunksCount) {
  10119. this.subdivide(this._subdivisions);
  10120. this.createOrUpdateSubmeshesOctree(32);
  10121. };
  10122. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10123. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10124. this.getWorldMatrix().invertToRef(this._worldInverse);
  10125. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10126. var pickInfo = this.intersects(ray);
  10127. if (pickInfo.hit) {
  10128. return pickInfo.pickedPoint.y;
  10129. }
  10130. return 0;
  10131. };
  10132. return GroundMesh;
  10133. })(BABYLON.Mesh);
  10134. BABYLON.GroundMesh = GroundMesh;
  10135. })(BABYLON || (BABYLON = {}));
  10136. //# sourceMappingURL=babylon.groundMesh.js.map
  10137. var BABYLON;
  10138. (function (BABYLON) {
  10139. var InstancedMesh = (function (_super) {
  10140. __extends(InstancedMesh, _super);
  10141. function InstancedMesh(name, source) {
  10142. _super.call(this, name, source.getScene());
  10143. source.instances.push(this);
  10144. this._sourceMesh = source;
  10145. this.position.copyFrom(source.position);
  10146. this.rotation.copyFrom(source.rotation);
  10147. this.scaling.copyFrom(source.scaling);
  10148. if (source.rotationQuaternion) {
  10149. this.rotationQuaternion = source.rotationQuaternion.clone();
  10150. }
  10151. this.infiniteDistance = source.infiniteDistance;
  10152. this.setPivotMatrix(source.getPivotMatrix());
  10153. this.refreshBoundingInfo();
  10154. this._syncSubMeshes();
  10155. }
  10156. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10157. // Methods
  10158. get: function () {
  10159. return this._sourceMesh.receiveShadows;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(InstancedMesh.prototype, "material", {
  10165. get: function () {
  10166. return this._sourceMesh.material;
  10167. },
  10168. enumerable: true,
  10169. configurable: true
  10170. });
  10171. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10172. get: function () {
  10173. return this._sourceMesh.visibility;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10179. get: function () {
  10180. return this._sourceMesh.skeleton;
  10181. },
  10182. enumerable: true,
  10183. configurable: true
  10184. });
  10185. InstancedMesh.prototype.getTotalVertices = function () {
  10186. return this._sourceMesh.getTotalVertices();
  10187. };
  10188. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10189. get: function () {
  10190. return this._sourceMesh;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. InstancedMesh.prototype.getVerticesData = function (kind) {
  10196. return this._sourceMesh.getVerticesData(kind);
  10197. };
  10198. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10199. return this._sourceMesh.isVerticesDataPresent(kind);
  10200. };
  10201. InstancedMesh.prototype.getIndices = function () {
  10202. return this._sourceMesh.getIndices();
  10203. };
  10204. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10205. get: function () {
  10206. return this._sourceMesh._positions;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10212. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10213. if (data) {
  10214. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10215. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10216. }
  10217. this._updateBoundingInfo();
  10218. };
  10219. InstancedMesh.prototype._preActivate = function () {
  10220. if (this._currentLOD) {
  10221. this._currentLOD._preActivate();
  10222. }
  10223. };
  10224. InstancedMesh.prototype._activate = function (renderId) {
  10225. if (this._currentLOD) {
  10226. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10227. }
  10228. };
  10229. InstancedMesh.prototype.getLOD = function (camera) {
  10230. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10231. if (this._currentLOD === this.sourceMesh) {
  10232. return this;
  10233. }
  10234. return this._currentLOD;
  10235. };
  10236. InstancedMesh.prototype._syncSubMeshes = function () {
  10237. this.releaseSubMeshes();
  10238. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10239. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10240. }
  10241. };
  10242. InstancedMesh.prototype._generatePointsArray = function () {
  10243. return this._sourceMesh._generatePointsArray();
  10244. };
  10245. // Clone
  10246. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10247. var result = this._sourceMesh.createInstance(name);
  10248. // Deep copy
  10249. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10250. // Bounding info
  10251. this.refreshBoundingInfo();
  10252. // Parent
  10253. if (newParent) {
  10254. result.parent = newParent;
  10255. }
  10256. if (!doNotCloneChildren) {
  10257. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10258. var mesh = this.getScene().meshes[index];
  10259. if (mesh.parent == this) {
  10260. mesh.clone(mesh.name, result);
  10261. }
  10262. }
  10263. }
  10264. result.computeWorldMatrix(true);
  10265. return result;
  10266. };
  10267. // Dispoe
  10268. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10269. // Remove from mesh
  10270. var index = this._sourceMesh.instances.indexOf(this);
  10271. this._sourceMesh.instances.splice(index, 1);
  10272. _super.prototype.dispose.call(this, doNotRecurse);
  10273. };
  10274. return InstancedMesh;
  10275. })(BABYLON.AbstractMesh);
  10276. BABYLON.InstancedMesh = InstancedMesh;
  10277. })(BABYLON || (BABYLON = {}));
  10278. //# sourceMappingURL=babylon.instancedMesh.js.map
  10279. var BABYLON;
  10280. (function (BABYLON) {
  10281. var SubMesh = (function () {
  10282. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10283. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10284. this.materialIndex = materialIndex;
  10285. this.verticesStart = verticesStart;
  10286. this.verticesCount = verticesCount;
  10287. this.indexStart = indexStart;
  10288. this.indexCount = indexCount;
  10289. this._renderId = 0;
  10290. this._mesh = mesh;
  10291. this._renderingMesh = renderingMesh || mesh;
  10292. mesh.subMeshes.push(this);
  10293. this._id = mesh.subMeshes.length - 1;
  10294. if (createBoundingBox) {
  10295. this.refreshBoundingInfo();
  10296. }
  10297. }
  10298. SubMesh.prototype.getBoundingInfo = function () {
  10299. return this._boundingInfo;
  10300. };
  10301. SubMesh.prototype.getMesh = function () {
  10302. return this._mesh;
  10303. };
  10304. SubMesh.prototype.getRenderingMesh = function () {
  10305. return this._renderingMesh;
  10306. };
  10307. SubMesh.prototype.getMaterial = function () {
  10308. var rootMaterial = this._renderingMesh.material;
  10309. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10310. var multiMaterial = rootMaterial;
  10311. return multiMaterial.getSubMaterial(this.materialIndex);
  10312. }
  10313. if (!rootMaterial) {
  10314. return this._mesh.getScene().defaultMaterial;
  10315. }
  10316. return rootMaterial;
  10317. };
  10318. // Methods
  10319. SubMesh.prototype.refreshBoundingInfo = function () {
  10320. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10321. if (!data) {
  10322. this._boundingInfo = this._mesh._boundingInfo;
  10323. return;
  10324. }
  10325. var indices = this._renderingMesh.getIndices();
  10326. var extend;
  10327. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10328. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10329. } else {
  10330. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10331. }
  10332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10333. };
  10334. SubMesh.prototype._checkCollision = function (collider) {
  10335. return this._boundingInfo._checkCollision(collider);
  10336. };
  10337. SubMesh.prototype.updateBoundingInfo = function (world) {
  10338. if (!this._boundingInfo) {
  10339. this.refreshBoundingInfo();
  10340. }
  10341. this._boundingInfo._update(world);
  10342. };
  10343. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10344. return this._boundingInfo.isInFrustum(frustumPlanes);
  10345. };
  10346. SubMesh.prototype.render = function () {
  10347. this._renderingMesh.render(this);
  10348. };
  10349. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10350. if (!this._linesIndexBuffer) {
  10351. var linesIndices = [];
  10352. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10353. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10354. }
  10355. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10356. this.linesIndexCount = linesIndices.length;
  10357. }
  10358. return this._linesIndexBuffer;
  10359. };
  10360. SubMesh.prototype.canIntersects = function (ray) {
  10361. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10362. };
  10363. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10364. var intersectInfo = null;
  10365. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10366. var p0 = positions[indices[index]];
  10367. var p1 = positions[indices[index + 1]];
  10368. var p2 = positions[indices[index + 2]];
  10369. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10370. if (currentIntersectInfo) {
  10371. if (currentIntersectInfo.distance < 0) {
  10372. continue;
  10373. }
  10374. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10375. intersectInfo = currentIntersectInfo;
  10376. intersectInfo.faceId = index / 3;
  10377. if (fastCheck) {
  10378. break;
  10379. }
  10380. }
  10381. }
  10382. }
  10383. return intersectInfo;
  10384. };
  10385. // Clone
  10386. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10387. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10388. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10389. return result;
  10390. };
  10391. // Dispose
  10392. SubMesh.prototype.dispose = function () {
  10393. if (this._linesIndexBuffer) {
  10394. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10395. this._linesIndexBuffer = null;
  10396. }
  10397. // Remove from mesh
  10398. var index = this._mesh.subMeshes.indexOf(this);
  10399. this._mesh.subMeshes.splice(index, 1);
  10400. };
  10401. // Statics
  10402. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10403. var minVertexIndex = Number.MAX_VALUE;
  10404. var maxVertexIndex = -Number.MAX_VALUE;
  10405. renderingMesh = renderingMesh || mesh;
  10406. var indices = renderingMesh.getIndices();
  10407. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10408. var vertexIndex = indices[index];
  10409. if (vertexIndex < minVertexIndex)
  10410. minVertexIndex = vertexIndex;
  10411. if (vertexIndex > maxVertexIndex)
  10412. maxVertexIndex = vertexIndex;
  10413. }
  10414. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10415. };
  10416. return SubMesh;
  10417. })();
  10418. BABYLON.SubMesh = SubMesh;
  10419. })(BABYLON || (BABYLON = {}));
  10420. //# sourceMappingURL=babylon.subMesh.js.map
  10421. var BABYLON;
  10422. (function (BABYLON) {
  10423. var BaseTexture = (function () {
  10424. function BaseTexture(scene) {
  10425. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10426. this.hasAlpha = false;
  10427. this.getAlphaFromRGB = false;
  10428. this.level = 1;
  10429. this.isCube = false;
  10430. this.isRenderTarget = false;
  10431. this.animations = new Array();
  10432. this.coordinatesIndex = 0;
  10433. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10434. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10435. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10436. this.anisotropicFilteringLevel = 4;
  10437. this._scene = scene;
  10438. this._scene.textures.push(this);
  10439. }
  10440. BaseTexture.prototype.getScene = function () {
  10441. return this._scene;
  10442. };
  10443. BaseTexture.prototype.getTextureMatrix = function () {
  10444. return null;
  10445. };
  10446. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10447. return null;
  10448. };
  10449. BaseTexture.prototype.getInternalTexture = function () {
  10450. return this._texture;
  10451. };
  10452. BaseTexture.prototype.isReady = function () {
  10453. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10454. return true;
  10455. }
  10456. if (this._texture) {
  10457. return this._texture.isReady;
  10458. }
  10459. return false;
  10460. };
  10461. BaseTexture.prototype.getSize = function () {
  10462. if (this._texture._width) {
  10463. return { width: this._texture._width, height: this._texture._height };
  10464. }
  10465. if (this._texture._size) {
  10466. return { width: this._texture._size, height: this._texture._size };
  10467. }
  10468. return { width: 0, height: 0 };
  10469. };
  10470. BaseTexture.prototype.getBaseSize = function () {
  10471. if (!this.isReady())
  10472. return { width: 0, height: 0 };
  10473. if (this._texture._size) {
  10474. return { width: this._texture._size, height: this._texture._size };
  10475. }
  10476. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10477. };
  10478. BaseTexture.prototype.scale = function (ratio) {
  10479. };
  10480. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10481. get: function () {
  10482. return false;
  10483. },
  10484. enumerable: true,
  10485. configurable: true
  10486. });
  10487. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10488. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10489. for (var index = 0; index < texturesCache.length; index++) {
  10490. var texturesCacheEntry = texturesCache[index];
  10491. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10492. texturesCache.splice(index, 1);
  10493. return;
  10494. }
  10495. }
  10496. };
  10497. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10498. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10499. for (var index = 0; index < texturesCache.length; index++) {
  10500. var texturesCacheEntry = texturesCache[index];
  10501. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10502. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10503. texturesCacheEntry.references++;
  10504. return texturesCacheEntry;
  10505. }
  10506. }
  10507. }
  10508. return null;
  10509. };
  10510. BaseTexture.prototype.delayLoad = function () {
  10511. };
  10512. BaseTexture.prototype.releaseInternalTexture = function () {
  10513. if (!this._texture) {
  10514. return;
  10515. }
  10516. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10517. this._texture.references--;
  10518. // Final reference ?
  10519. if (this._texture.references === 0) {
  10520. var index = texturesCache.indexOf(this._texture);
  10521. texturesCache.splice(index, 1);
  10522. this._scene.getEngine()._releaseTexture(this._texture);
  10523. delete this._texture;
  10524. }
  10525. };
  10526. BaseTexture.prototype.clone = function () {
  10527. return null;
  10528. };
  10529. BaseTexture.prototype.dispose = function () {
  10530. // Remove from scene
  10531. var index = this._scene.textures.indexOf(this);
  10532. if (index >= 0) {
  10533. this._scene.textures.splice(index, 1);
  10534. }
  10535. if (this._texture === undefined) {
  10536. return;
  10537. }
  10538. this.releaseInternalTexture();
  10539. // Callback
  10540. if (this.onDispose) {
  10541. this.onDispose();
  10542. }
  10543. };
  10544. return BaseTexture;
  10545. })();
  10546. BABYLON.BaseTexture = BaseTexture;
  10547. })(BABYLON || (BABYLON = {}));
  10548. //# sourceMappingURL=babylon.baseTexture.js.map
  10549. var BABYLON;
  10550. (function (BABYLON) {
  10551. var RenderingGroup = (function () {
  10552. function RenderingGroup(index, scene) {
  10553. this.index = index;
  10554. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10555. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10556. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10557. this._scene = scene;
  10558. }
  10559. RenderingGroup.prototype.render = function (customRenderFunction) {
  10560. if (customRenderFunction) {
  10561. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10562. return true;
  10563. }
  10564. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10565. return false;
  10566. }
  10567. var engine = this._scene.getEngine();
  10568. // Opaque
  10569. var subIndex;
  10570. var submesh;
  10571. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10572. submesh = this._opaqueSubMeshes.data[subIndex];
  10573. submesh.render();
  10574. }
  10575. // Alpha test
  10576. engine.setAlphaTesting(true);
  10577. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10578. submesh = this._alphaTestSubMeshes.data[subIndex];
  10579. submesh.render();
  10580. }
  10581. engine.setAlphaTesting(false);
  10582. // Transparent
  10583. if (this._transparentSubMeshes.length) {
  10584. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10585. submesh = this._transparentSubMeshes.data[subIndex];
  10586. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10587. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10588. }
  10589. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10590. sortedArray.sort(function (a, b) {
  10591. // Alpha index first
  10592. if (a._alphaIndex > b._alphaIndex) {
  10593. return 1;
  10594. }
  10595. if (a._alphaIndex < b._alphaIndex) {
  10596. return -1;
  10597. }
  10598. // Then distance to camera
  10599. if (a._distanceToCamera < b._distanceToCamera) {
  10600. return 1;
  10601. }
  10602. if (a._distanceToCamera > b._distanceToCamera) {
  10603. return -1;
  10604. }
  10605. return 0;
  10606. });
  10607. // Rendering
  10608. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10609. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10610. submesh = sortedArray[subIndex];
  10611. submesh.render();
  10612. }
  10613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10614. }
  10615. return true;
  10616. };
  10617. RenderingGroup.prototype.prepare = function () {
  10618. this._opaqueSubMeshes.reset();
  10619. this._transparentSubMeshes.reset();
  10620. this._alphaTestSubMeshes.reset();
  10621. };
  10622. RenderingGroup.prototype.dispatch = function (subMesh) {
  10623. var material = subMesh.getMaterial();
  10624. var mesh = subMesh.getMesh();
  10625. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10626. this._transparentSubMeshes.push(subMesh);
  10627. } else if (material.needAlphaTesting()) {
  10628. this._alphaTestSubMeshes.push(subMesh);
  10629. } else {
  10630. this._opaqueSubMeshes.push(subMesh); // Opaque
  10631. }
  10632. };
  10633. return RenderingGroup;
  10634. })();
  10635. BABYLON.RenderingGroup = RenderingGroup;
  10636. })(BABYLON || (BABYLON = {}));
  10637. //# sourceMappingURL=babylon.renderingGroup.js.map
  10638. var BABYLON;
  10639. (function (BABYLON) {
  10640. var RenderingManager = (function () {
  10641. function RenderingManager(scene) {
  10642. this._renderingGroups = new Array();
  10643. this._scene = scene;
  10644. }
  10645. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10646. if (this._scene._activeParticleSystems.length === 0) {
  10647. return;
  10648. }
  10649. // Particles
  10650. var beforeParticlesDate = BABYLON.Tools.Now;
  10651. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10652. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10653. if (particleSystem.renderingGroupId !== index) {
  10654. continue;
  10655. }
  10656. this._clearDepthBuffer();
  10657. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10658. this._scene._activeParticles += particleSystem.render();
  10659. }
  10660. }
  10661. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10662. };
  10663. RenderingManager.prototype._renderSprites = function (index) {
  10664. if (this._scene.spriteManagers.length === 0) {
  10665. return;
  10666. }
  10667. // Sprites
  10668. var beforeSpritessDate = BABYLON.Tools.Now;
  10669. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10670. var spriteManager = this._scene.spriteManagers[id];
  10671. if (spriteManager.renderingGroupId === index) {
  10672. this._clearDepthBuffer();
  10673. spriteManager.render();
  10674. }
  10675. }
  10676. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10677. };
  10678. RenderingManager.prototype._clearDepthBuffer = function () {
  10679. if (this._depthBufferAlreadyCleaned) {
  10680. return;
  10681. }
  10682. this._scene.getEngine().clear(0, false, true);
  10683. this._depthBufferAlreadyCleaned = true;
  10684. };
  10685. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10686. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10687. this._depthBufferAlreadyCleaned = false;
  10688. var renderingGroup = this._renderingGroups[index];
  10689. if (renderingGroup) {
  10690. this._clearDepthBuffer();
  10691. if (!renderingGroup.render(customRenderFunction)) {
  10692. this._renderingGroups.splice(index, 1);
  10693. }
  10694. }
  10695. this._renderSprites(index);
  10696. if (renderParticles) {
  10697. this._renderParticles(index, activeMeshes);
  10698. }
  10699. }
  10700. };
  10701. RenderingManager.prototype.reset = function () {
  10702. for (var index in this._renderingGroups) {
  10703. var renderingGroup = this._renderingGroups[index];
  10704. renderingGroup.prepare();
  10705. }
  10706. };
  10707. RenderingManager.prototype.dispatch = function (subMesh) {
  10708. var mesh = subMesh.getMesh();
  10709. var renderingGroupId = mesh.renderingGroupId || 0;
  10710. if (!this._renderingGroups[renderingGroupId]) {
  10711. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10712. }
  10713. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10714. };
  10715. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10716. return RenderingManager;
  10717. })();
  10718. BABYLON.RenderingManager = RenderingManager;
  10719. })(BABYLON || (BABYLON = {}));
  10720. //# sourceMappingURL=babylon.renderingManager.js.map
  10721. var BABYLON;
  10722. (function (BABYLON) {
  10723. var Texture = (function (_super) {
  10724. __extends(Texture, _super);
  10725. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10726. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10727. if (typeof onLoad === "undefined") { onLoad = null; }
  10728. if (typeof onError === "undefined") { onError = null; }
  10729. if (typeof buffer === "undefined") { buffer = null; }
  10730. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10731. _super.call(this, scene);
  10732. this.uOffset = 0;
  10733. this.vOffset = 0;
  10734. this.uScale = 1.0;
  10735. this.vScale = 1.0;
  10736. this.uAng = 0;
  10737. this.vAng = 0;
  10738. this.wAng = 0;
  10739. this.name = url;
  10740. this.url = url;
  10741. this._noMipmap = noMipmap;
  10742. this._invertY = invertY;
  10743. this._samplingMode = samplingMode;
  10744. this._buffer = buffer;
  10745. this._deleteBuffer = deleteBuffer;
  10746. if (!url) {
  10747. return;
  10748. }
  10749. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10750. if (!this._texture) {
  10751. if (!scene.useDelayedTextureLoading) {
  10752. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10753. if (deleteBuffer) {
  10754. delete this._buffer;
  10755. }
  10756. } else {
  10757. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10758. }
  10759. }
  10760. }
  10761. Texture.prototype.delayLoad = function () {
  10762. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10763. return;
  10764. }
  10765. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10766. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10767. if (!this._texture) {
  10768. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10769. if (this._deleteBuffer) {
  10770. delete this._buffer;
  10771. }
  10772. }
  10773. };
  10774. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10775. x -= this.uOffset + 0.5;
  10776. y -= this.vOffset + 0.5;
  10777. z -= 0.5;
  10778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10779. t.x *= this.uScale;
  10780. t.y *= this.vScale;
  10781. t.x += 0.5;
  10782. t.y += 0.5;
  10783. t.z += 0.5;
  10784. };
  10785. Texture.prototype.getTextureMatrix = function () {
  10786. 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) {
  10787. return this._cachedTextureMatrix;
  10788. }
  10789. this._cachedUOffset = this.uOffset;
  10790. this._cachedVOffset = this.vOffset;
  10791. this._cachedUScale = this.uScale;
  10792. this._cachedVScale = this.vScale;
  10793. this._cachedUAng = this.uAng;
  10794. this._cachedVAng = this.vAng;
  10795. this._cachedWAng = this.wAng;
  10796. if (!this._cachedTextureMatrix) {
  10797. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10798. this._rowGenerationMatrix = new BABYLON.Matrix();
  10799. this._t0 = BABYLON.Vector3.Zero();
  10800. this._t1 = BABYLON.Vector3.Zero();
  10801. this._t2 = BABYLON.Vector3.Zero();
  10802. }
  10803. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10804. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10805. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10806. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10807. this._t1.subtractInPlace(this._t0);
  10808. this._t2.subtractInPlace(this._t0);
  10809. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10810. this._cachedTextureMatrix.m[0] = this._t1.x;
  10811. this._cachedTextureMatrix.m[1] = this._t1.y;
  10812. this._cachedTextureMatrix.m[2] = this._t1.z;
  10813. this._cachedTextureMatrix.m[4] = this._t2.x;
  10814. this._cachedTextureMatrix.m[5] = this._t2.y;
  10815. this._cachedTextureMatrix.m[6] = this._t2.z;
  10816. this._cachedTextureMatrix.m[8] = this._t0.x;
  10817. this._cachedTextureMatrix.m[9] = this._t0.y;
  10818. this._cachedTextureMatrix.m[10] = this._t0.z;
  10819. return this._cachedTextureMatrix;
  10820. };
  10821. Texture.prototype.getReflectionTextureMatrix = function () {
  10822. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10823. return this._cachedTextureMatrix;
  10824. }
  10825. if (!this._cachedTextureMatrix) {
  10826. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10827. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10828. }
  10829. this._cachedCoordinatesMode = this.coordinatesMode;
  10830. switch (this.coordinatesMode) {
  10831. case BABYLON.Texture.SPHERICAL_MODE:
  10832. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10833. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10834. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10835. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10836. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10837. break;
  10838. case BABYLON.Texture.PLANAR_MODE:
  10839. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10840. this._cachedTextureMatrix[0] = this.uScale;
  10841. this._cachedTextureMatrix[5] = this.vScale;
  10842. this._cachedTextureMatrix[12] = this.uOffset;
  10843. this._cachedTextureMatrix[13] = this.vOffset;
  10844. break;
  10845. case BABYLON.Texture.PROJECTION_MODE:
  10846. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10847. this._projectionModeMatrix.m[0] = 0.5;
  10848. this._projectionModeMatrix.m[5] = -0.5;
  10849. this._projectionModeMatrix.m[10] = 0.0;
  10850. this._projectionModeMatrix.m[12] = 0.5;
  10851. this._projectionModeMatrix.m[13] = 0.5;
  10852. this._projectionModeMatrix.m[14] = 1.0;
  10853. this._projectionModeMatrix.m[15] = 1.0;
  10854. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10855. break;
  10856. default:
  10857. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10858. break;
  10859. }
  10860. return this._cachedTextureMatrix;
  10861. };
  10862. Texture.prototype.clone = function () {
  10863. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10864. // Base texture
  10865. newTexture.hasAlpha = this.hasAlpha;
  10866. newTexture.level = this.level;
  10867. newTexture.wrapU = this.wrapU;
  10868. newTexture.wrapV = this.wrapV;
  10869. newTexture.coordinatesIndex = this.coordinatesIndex;
  10870. newTexture.coordinatesMode = this.coordinatesMode;
  10871. // Texture
  10872. newTexture.uOffset = this.uOffset;
  10873. newTexture.vOffset = this.vOffset;
  10874. newTexture.uScale = this.uScale;
  10875. newTexture.vScale = this.vScale;
  10876. newTexture.uAng = this.uAng;
  10877. newTexture.vAng = this.vAng;
  10878. newTexture.wAng = this.wAng;
  10879. return newTexture;
  10880. };
  10881. // Statics
  10882. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10883. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10884. if (typeof onLoad === "undefined") { onLoad = null; }
  10885. if (typeof onError === "undefined") { onError = null; }
  10886. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10887. };
  10888. Texture.NEAREST_SAMPLINGMODE = 1;
  10889. Texture.BILINEAR_SAMPLINGMODE = 2;
  10890. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10891. Texture.EXPLICIT_MODE = 0;
  10892. Texture.SPHERICAL_MODE = 1;
  10893. Texture.PLANAR_MODE = 2;
  10894. Texture.CUBIC_MODE = 3;
  10895. Texture.PROJECTION_MODE = 4;
  10896. Texture.SKYBOX_MODE = 5;
  10897. Texture.CLAMP_ADDRESSMODE = 0;
  10898. Texture.WRAP_ADDRESSMODE = 1;
  10899. Texture.MIRROR_ADDRESSMODE = 2;
  10900. return Texture;
  10901. })(BABYLON.BaseTexture);
  10902. BABYLON.Texture = Texture;
  10903. })(BABYLON || (BABYLON = {}));
  10904. //# sourceMappingURL=babylon.texture.js.map
  10905. var BABYLON;
  10906. (function (BABYLON) {
  10907. var CubeTexture = (function (_super) {
  10908. __extends(CubeTexture, _super);
  10909. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10910. _super.call(this, scene);
  10911. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10912. this.name = rootUrl;
  10913. this.url = rootUrl;
  10914. this._noMipmap = noMipmap;
  10915. this.hasAlpha = false;
  10916. this._texture = this._getFromCache(rootUrl, noMipmap);
  10917. if (!extensions) {
  10918. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10919. }
  10920. this._extensions = extensions;
  10921. if (!this._texture) {
  10922. if (!scene.useDelayedTextureLoading) {
  10923. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10924. } else {
  10925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10926. }
  10927. }
  10928. this.isCube = true;
  10929. this._textureMatrix = BABYLON.Matrix.Identity();
  10930. }
  10931. CubeTexture.prototype.clone = function () {
  10932. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10933. // Base texture
  10934. newTexture.level = this.level;
  10935. newTexture.wrapU = this.wrapU;
  10936. newTexture.wrapV = this.wrapV;
  10937. newTexture.coordinatesIndex = this.coordinatesIndex;
  10938. newTexture.coordinatesMode = this.coordinatesMode;
  10939. return newTexture;
  10940. };
  10941. // Methods
  10942. CubeTexture.prototype.delayLoad = function () {
  10943. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10944. return;
  10945. }
  10946. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10947. this._texture = this._getFromCache(this.url, this._noMipmap);
  10948. if (!this._texture) {
  10949. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10950. }
  10951. };
  10952. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10953. return this._textureMatrix;
  10954. };
  10955. return CubeTexture;
  10956. })(BABYLON.BaseTexture);
  10957. BABYLON.CubeTexture = CubeTexture;
  10958. })(BABYLON || (BABYLON = {}));
  10959. //# sourceMappingURL=babylon.cubeTexture.js.map
  10960. var BABYLON;
  10961. (function (BABYLON) {
  10962. var RenderTargetTexture = (function (_super) {
  10963. __extends(RenderTargetTexture, _super);
  10964. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10965. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10966. _super.call(this, null, scene, !generateMipMaps);
  10967. this.renderList = new Array();
  10968. this.renderParticles = true;
  10969. this.renderSprites = false;
  10970. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10971. this._currentRefreshId = -1;
  10972. this._refreshRate = 1;
  10973. this.name = name;
  10974. this.isRenderTarget = true;
  10975. this._size = size;
  10976. this._generateMipMaps = generateMipMaps;
  10977. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10978. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10979. // Rendering groups
  10980. this._renderingManager = new BABYLON.RenderingManager(scene);
  10981. }
  10982. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10983. this._currentRefreshId = -1;
  10984. };
  10985. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10986. get: function () {
  10987. return this._refreshRate;
  10988. },
  10989. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10990. set: function (value) {
  10991. this._refreshRate = value;
  10992. this.resetRefreshCounter();
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. RenderTargetTexture.prototype._shouldRender = function () {
  10998. if (this._currentRefreshId === -1) {
  10999. this._currentRefreshId = 1;
  11000. return true;
  11001. }
  11002. if (this.refreshRate == this._currentRefreshId) {
  11003. this._currentRefreshId = 1;
  11004. return true;
  11005. }
  11006. this._currentRefreshId++;
  11007. return false;
  11008. };
  11009. RenderTargetTexture.prototype.isReady = function () {
  11010. if (!this.getScene().renderTargetsEnabled) {
  11011. return false;
  11012. }
  11013. return _super.prototype.isReady.call(this);
  11014. };
  11015. RenderTargetTexture.prototype.getRenderSize = function () {
  11016. return this._size;
  11017. };
  11018. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11019. get: function () {
  11020. return true;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. RenderTargetTexture.prototype.scale = function (ratio) {
  11026. var newSize = this._size * ratio;
  11027. this.resize(newSize, this._generateMipMaps);
  11028. };
  11029. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11030. this.releaseInternalTexture();
  11031. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11032. };
  11033. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11034. var scene = this.getScene();
  11035. var engine = scene.getEngine();
  11036. if (this._waitingRenderList) {
  11037. this.renderList = [];
  11038. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11039. var id = this._waitingRenderList[index];
  11040. this.renderList.push(scene.getMeshByID(id));
  11041. }
  11042. delete this._waitingRenderList;
  11043. }
  11044. if (!this.renderList) {
  11045. return;
  11046. }
  11047. // Bind
  11048. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11049. engine.bindFramebuffer(this._texture);
  11050. }
  11051. // Clear
  11052. engine.clear(scene.clearColor, true, true);
  11053. this._renderingManager.reset();
  11054. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11055. var mesh = this.renderList[meshIndex];
  11056. if (mesh) {
  11057. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11058. // Reset _currentRefreshId
  11059. this.resetRefreshCounter();
  11060. continue;
  11061. }
  11062. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11063. mesh._activate(scene.getRenderId());
  11064. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11065. var subMesh = mesh.subMeshes[subIndex];
  11066. scene._activeVertices += subMesh.indexCount;
  11067. this._renderingManager.dispatch(subMesh);
  11068. }
  11069. }
  11070. }
  11071. }
  11072. if (!this._doNotChangeAspectRatio) {
  11073. scene.updateTransformMatrix(true);
  11074. }
  11075. if (this.onBeforeRender) {
  11076. this.onBeforeRender();
  11077. }
  11078. // Render
  11079. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11080. if (useCameraPostProcess) {
  11081. scene.postProcessManager._finalizeFrame(false, this._texture);
  11082. }
  11083. if (this.onAfterRender) {
  11084. this.onAfterRender();
  11085. }
  11086. // Unbind
  11087. engine.unBindFramebuffer(this._texture);
  11088. if (!this._doNotChangeAspectRatio) {
  11089. scene.updateTransformMatrix(true);
  11090. }
  11091. };
  11092. RenderTargetTexture.prototype.clone = function () {
  11093. var textureSize = this.getSize();
  11094. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11095. // Base texture
  11096. newTexture.hasAlpha = this.hasAlpha;
  11097. newTexture.level = this.level;
  11098. // RenderTarget Texture
  11099. newTexture.coordinatesMode = this.coordinatesMode;
  11100. newTexture.renderList = this.renderList.slice(0);
  11101. return newTexture;
  11102. };
  11103. return RenderTargetTexture;
  11104. })(BABYLON.Texture);
  11105. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11106. })(BABYLON || (BABYLON = {}));
  11107. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11108. var BABYLON;
  11109. (function (BABYLON) {
  11110. var ProceduralTexture = (function (_super) {
  11111. __extends(ProceduralTexture, _super);
  11112. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11113. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11114. _super.call(this, null, scene, !generateMipMaps);
  11115. this._currentRefreshId = -1;
  11116. this._refreshRate = 1;
  11117. this._vertexDeclaration = [2];
  11118. this._vertexStrideSize = 2 * 4;
  11119. this._uniforms = new Array();
  11120. this._samplers = new Array();
  11121. this._textures = new Array();
  11122. this._floats = new Array();
  11123. this._floatsArrays = {};
  11124. this._colors3 = new Array();
  11125. this._colors4 = new Array();
  11126. this._vectors2 = new Array();
  11127. this._vectors3 = new Array();
  11128. this._matrices = new Array();
  11129. this._fallbackTextureUsed = false;
  11130. scene._proceduralTextures.push(this);
  11131. this.name = name;
  11132. this.isRenderTarget = true;
  11133. this._size = size;
  11134. this._generateMipMaps = generateMipMaps;
  11135. this.setFragment(fragment);
  11136. this._fallbackTexture = fallbackTexture;
  11137. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11138. // VBO
  11139. var vertices = [];
  11140. vertices.push(1, 1);
  11141. vertices.push(-1, 1);
  11142. vertices.push(-1, -1);
  11143. vertices.push(1, -1);
  11144. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11145. // Indices
  11146. var indices = [];
  11147. indices.push(0);
  11148. indices.push(1);
  11149. indices.push(2);
  11150. indices.push(0);
  11151. indices.push(2);
  11152. indices.push(3);
  11153. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11154. }
  11155. ProceduralTexture.prototype.reset = function () {
  11156. if (this._effect === undefined) {
  11157. return;
  11158. }
  11159. var engine = this.getScene().getEngine();
  11160. engine._releaseEffect(this._effect);
  11161. };
  11162. ProceduralTexture.prototype.isReady = function () {
  11163. var _this = this;
  11164. var engine = this.getScene().getEngine();
  11165. var shaders;
  11166. if (!this._fragment) {
  11167. return false;
  11168. }
  11169. if (this._fallbackTextureUsed) {
  11170. return true;
  11171. }
  11172. if (this._fragment.fragmentElement !== undefined) {
  11173. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11174. } else {
  11175. shaders = { vertex: "procedural", fragment: this._fragment };
  11176. }
  11177. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11178. _this.releaseInternalTexture();
  11179. if (_this._fallbackTexture) {
  11180. _this._texture = _this._fallbackTexture._texture;
  11181. _this._texture.references++;
  11182. }
  11183. _this._fallbackTextureUsed = true;
  11184. });
  11185. return this._effect.isReady();
  11186. };
  11187. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11188. this._currentRefreshId = -1;
  11189. };
  11190. ProceduralTexture.prototype.setFragment = function (fragment) {
  11191. this._fragment = fragment;
  11192. };
  11193. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11194. get: function () {
  11195. return this._refreshRate;
  11196. },
  11197. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11198. set: function (value) {
  11199. this._refreshRate = value;
  11200. this.resetRefreshCounter();
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. ProceduralTexture.prototype._shouldRender = function () {
  11206. if (!this.isReady() || !this._texture) {
  11207. return false;
  11208. }
  11209. if (this._fallbackTextureUsed) {
  11210. return false;
  11211. }
  11212. if (this._currentRefreshId === -1) {
  11213. this._currentRefreshId = 1;
  11214. return true;
  11215. }
  11216. if (this.refreshRate === this._currentRefreshId) {
  11217. this._currentRefreshId = 1;
  11218. return true;
  11219. }
  11220. this._currentRefreshId++;
  11221. return false;
  11222. };
  11223. ProceduralTexture.prototype.getRenderSize = function () {
  11224. return this._size;
  11225. };
  11226. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11227. if (this._fallbackTextureUsed) {
  11228. return;
  11229. }
  11230. this.releaseInternalTexture();
  11231. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11232. };
  11233. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11234. if (this._uniforms.indexOf(uniformName) === -1) {
  11235. this._uniforms.push(uniformName);
  11236. }
  11237. };
  11238. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11239. if (this._samplers.indexOf(name) === -1) {
  11240. this._samplers.push(name);
  11241. }
  11242. this._textures[name] = texture;
  11243. return this;
  11244. };
  11245. ProceduralTexture.prototype.setFloat = function (name, value) {
  11246. this._checkUniform(name);
  11247. this._floats[name] = value;
  11248. return this;
  11249. };
  11250. ProceduralTexture.prototype.setFloats = function (name, value) {
  11251. this._checkUniform(name);
  11252. this._floatsArrays[name] = value;
  11253. return this;
  11254. };
  11255. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11256. this._checkUniform(name);
  11257. this._colors3[name] = value;
  11258. return this;
  11259. };
  11260. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11261. this._checkUniform(name);
  11262. this._colors4[name] = value;
  11263. return this;
  11264. };
  11265. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11266. this._checkUniform(name);
  11267. this._vectors2[name] = value;
  11268. return this;
  11269. };
  11270. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11271. this._checkUniform(name);
  11272. this._vectors3[name] = value;
  11273. return this;
  11274. };
  11275. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11276. this._checkUniform(name);
  11277. this._matrices[name] = value;
  11278. return this;
  11279. };
  11280. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11281. var scene = this.getScene();
  11282. var engine = scene.getEngine();
  11283. engine.bindFramebuffer(this._texture);
  11284. // Clear
  11285. engine.clear(scene.clearColor, true, true);
  11286. // Render
  11287. engine.enableEffect(this._effect);
  11288. engine.setState(false);
  11289. for (var name in this._textures) {
  11290. this._effect.setTexture(name, this._textures[name]);
  11291. }
  11292. for (name in this._floats) {
  11293. this._effect.setFloat(name, this._floats[name]);
  11294. }
  11295. for (name in this._floatsArrays) {
  11296. this._effect.setArray(name, this._floatsArrays[name]);
  11297. }
  11298. for (name in this._colors3) {
  11299. this._effect.setColor3(name, this._colors3[name]);
  11300. }
  11301. for (name in this._colors4) {
  11302. var color = this._colors4[name];
  11303. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11304. }
  11305. for (name in this._vectors2) {
  11306. this._effect.setVector2(name, this._vectors2[name]);
  11307. }
  11308. for (name in this._vectors3) {
  11309. this._effect.setVector3(name, this._vectors3[name]);
  11310. }
  11311. for (name in this._matrices) {
  11312. this._effect.setMatrix(name, this._matrices[name]);
  11313. }
  11314. // VBOs
  11315. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11316. // Draw order
  11317. engine.draw(true, 0, 6);
  11318. // Unbind
  11319. engine.unBindFramebuffer(this._texture);
  11320. };
  11321. ProceduralTexture.prototype.clone = function () {
  11322. var textureSize = this.getSize();
  11323. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11324. // Base texture
  11325. newTexture.hasAlpha = this.hasAlpha;
  11326. newTexture.level = this.level;
  11327. // RenderTarget Texture
  11328. newTexture.coordinatesMode = this.coordinatesMode;
  11329. return newTexture;
  11330. };
  11331. ProceduralTexture.prototype.dispose = function () {
  11332. var index = this.getScene()._proceduralTextures.indexOf(this);
  11333. if (index >= 0) {
  11334. this.getScene()._proceduralTextures.splice(index, 1);
  11335. }
  11336. _super.prototype.dispose.call(this);
  11337. };
  11338. return ProceduralTexture;
  11339. })(BABYLON.Texture);
  11340. BABYLON.ProceduralTexture = ProceduralTexture;
  11341. })(BABYLON || (BABYLON = {}));
  11342. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11343. var BABYLON;
  11344. (function (BABYLON) {
  11345. var WoodProceduralTexture = (function (_super) {
  11346. __extends(WoodProceduralTexture, _super);
  11347. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11348. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11349. this._ampScale = 100.0;
  11350. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11351. this.updateShaderUniforms();
  11352. this.refreshRate = 0;
  11353. }
  11354. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11355. this.setFloat("ampScale", this._ampScale);
  11356. this.setColor3("woodColor", this._woodColor);
  11357. };
  11358. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11359. get: function () {
  11360. return this._ampScale;
  11361. },
  11362. set: function (value) {
  11363. this._ampScale = value;
  11364. this.updateShaderUniforms();
  11365. },
  11366. enumerable: true,
  11367. configurable: true
  11368. });
  11369. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11370. get: function () {
  11371. return this._woodColor;
  11372. },
  11373. set: function (value) {
  11374. this._woodColor = value;
  11375. this.updateShaderUniforms();
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. return WoodProceduralTexture;
  11381. })(BABYLON.ProceduralTexture);
  11382. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11383. var FireProceduralTexture = (function (_super) {
  11384. __extends(FireProceduralTexture, _super);
  11385. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11386. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11387. this._time = 0.0;
  11388. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11389. this._shift = 1.6;
  11390. this._autoGenerateTime = true;
  11391. this._alphaThreshold = 0.5;
  11392. this._fireColors = FireProceduralTexture.RedFireColors;
  11393. this.updateShaderUniforms();
  11394. this.refreshRate = 1;
  11395. }
  11396. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11397. this.setFloat("time", this._time);
  11398. this.setVector2("speed", this._speed);
  11399. this.setFloat("shift", this._shift);
  11400. this.setColor3("c1", this._fireColors[0]);
  11401. this.setColor3("c2", this._fireColors[1]);
  11402. this.setColor3("c3", this._fireColors[2]);
  11403. this.setColor3("c4", this._fireColors[3]);
  11404. this.setColor3("c5", this._fireColors[4]);
  11405. this.setColor3("c6", this._fireColors[5]);
  11406. this.setFloat("alphaThreshold", this._alphaThreshold);
  11407. };
  11408. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11409. if (this._autoGenerateTime) {
  11410. this._time += this.getScene().getAnimationRatio() * 0.03;
  11411. this.updateShaderUniforms();
  11412. }
  11413. _super.prototype.render.call(this, useCameraPostProcess);
  11414. };
  11415. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11416. get: function () {
  11417. return [
  11418. new BABYLON.Color3(0.5, 0.0, 1.0),
  11419. new BABYLON.Color3(0.9, 0.0, 1.0),
  11420. new BABYLON.Color3(0.2, 0.0, 1.0),
  11421. new BABYLON.Color3(1.0, 0.9, 1.0),
  11422. new BABYLON.Color3(0.1, 0.1, 1.0),
  11423. new BABYLON.Color3(0.9, 0.9, 1.0)
  11424. ];
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11430. get: function () {
  11431. return [
  11432. new BABYLON.Color3(0.5, 1.0, 0.0),
  11433. new BABYLON.Color3(0.5, 1.0, 0.0),
  11434. new BABYLON.Color3(0.3, 0.4, 0.0),
  11435. new BABYLON.Color3(0.5, 1.0, 0.0),
  11436. new BABYLON.Color3(0.2, 0.0, 0.0),
  11437. new BABYLON.Color3(0.5, 1.0, 0.0)
  11438. ];
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11444. get: function () {
  11445. return [
  11446. new BABYLON.Color3(0.5, 0.0, 0.1),
  11447. new BABYLON.Color3(0.9, 0.0, 0.0),
  11448. new BABYLON.Color3(0.2, 0.0, 0.0),
  11449. new BABYLON.Color3(1.0, 0.9, 0.0),
  11450. new BABYLON.Color3(0.1, 0.1, 0.1),
  11451. new BABYLON.Color3(0.9, 0.9, 0.9)
  11452. ];
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11458. get: function () {
  11459. return [
  11460. new BABYLON.Color3(0.1, 0.0, 0.5),
  11461. new BABYLON.Color3(0.0, 0.0, 0.5),
  11462. new BABYLON.Color3(0.1, 0.0, 0.2),
  11463. new BABYLON.Color3(0.0, 0.0, 1.0),
  11464. new BABYLON.Color3(0.1, 0.2, 0.3),
  11465. new BABYLON.Color3(0.0, 0.2, 0.9)
  11466. ];
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11472. get: function () {
  11473. return this._fireColors;
  11474. },
  11475. set: function (value) {
  11476. this._fireColors = value;
  11477. this.updateShaderUniforms();
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11483. get: function () {
  11484. return this._time;
  11485. },
  11486. set: function (value) {
  11487. this._time = value;
  11488. this.updateShaderUniforms();
  11489. },
  11490. enumerable: true,
  11491. configurable: true
  11492. });
  11493. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11494. get: function () {
  11495. return this._speed;
  11496. },
  11497. set: function (value) {
  11498. this._speed = value;
  11499. this.updateShaderUniforms();
  11500. },
  11501. enumerable: true,
  11502. configurable: true
  11503. });
  11504. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11505. get: function () {
  11506. return this._shift;
  11507. },
  11508. set: function (value) {
  11509. this._shift = value;
  11510. this.updateShaderUniforms();
  11511. },
  11512. enumerable: true,
  11513. configurable: true
  11514. });
  11515. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11516. get: function () {
  11517. return this._alphaThreshold;
  11518. },
  11519. set: function (value) {
  11520. this._alphaThreshold = value;
  11521. this.updateShaderUniforms();
  11522. },
  11523. enumerable: true,
  11524. configurable: true
  11525. });
  11526. return FireProceduralTexture;
  11527. })(BABYLON.ProceduralTexture);
  11528. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11529. var CloudProceduralTexture = (function (_super) {
  11530. __extends(CloudProceduralTexture, _super);
  11531. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11532. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11533. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11534. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11535. this.updateShaderUniforms();
  11536. this.refreshRate = 0;
  11537. }
  11538. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11539. this.setColor3("skyColor", this._skyColor);
  11540. this.setColor3("cloudColor", this._cloudColor);
  11541. };
  11542. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11543. get: function () {
  11544. return this._skyColor;
  11545. },
  11546. set: function (value) {
  11547. this._skyColor = value;
  11548. this.updateShaderUniforms();
  11549. },
  11550. enumerable: true,
  11551. configurable: true
  11552. });
  11553. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11554. get: function () {
  11555. return this._cloudColor;
  11556. },
  11557. set: function (value) {
  11558. this._cloudColor = value;
  11559. this.updateShaderUniforms();
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. return CloudProceduralTexture;
  11565. })(BABYLON.ProceduralTexture);
  11566. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11567. var GrassProceduralTexture = (function (_super) {
  11568. __extends(GrassProceduralTexture, _super);
  11569. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11570. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11571. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11572. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11573. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11574. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11575. this._grassColors = [
  11576. new BABYLON.Color3(0.29, 0.38, 0.02),
  11577. new BABYLON.Color3(0.36, 0.49, 0.09),
  11578. new BABYLON.Color3(0.51, 0.6, 0.28)
  11579. ];
  11580. this.updateShaderUniforms();
  11581. this.refreshRate = 0;
  11582. }
  11583. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11584. this.setColor3("herb1Color", this._grassColors[0]);
  11585. this.setColor3("herb2Color", this._grassColors[1]);
  11586. this.setColor3("herb3Color", this._grassColors[2]);
  11587. this.setColor3("groundColor", this._groundColor);
  11588. };
  11589. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11590. get: function () {
  11591. return this._grassColors;
  11592. },
  11593. set: function (value) {
  11594. this._grassColors = value;
  11595. this.updateShaderUniforms();
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11601. get: function () {
  11602. return this._groundColor;
  11603. },
  11604. set: function (value) {
  11605. this.groundColor = value;
  11606. this.updateShaderUniforms();
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. return GrassProceduralTexture;
  11612. })(BABYLON.ProceduralTexture);
  11613. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11614. var RoadProceduralTexture = (function (_super) {
  11615. __extends(RoadProceduralTexture, _super);
  11616. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11617. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11618. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11619. this.updateShaderUniforms();
  11620. this.refreshRate = 0;
  11621. }
  11622. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11623. this.setColor3("roadColor", this._roadColor);
  11624. };
  11625. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11626. get: function () {
  11627. return this._roadColor;
  11628. },
  11629. set: function (value) {
  11630. this._roadColor = value;
  11631. this.updateShaderUniforms();
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. return RoadProceduralTexture;
  11637. })(BABYLON.ProceduralTexture);
  11638. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11639. var BrickProceduralTexture = (function (_super) {
  11640. __extends(BrickProceduralTexture, _super);
  11641. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11642. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11643. this._numberOfBricksHeight = 15;
  11644. this._numberOfBricksWidth = 5;
  11645. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11646. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11647. this.updateShaderUniforms();
  11648. this.refreshRate = 0;
  11649. }
  11650. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11651. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11652. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11653. this.setColor3("brickColor", this._brickColor);
  11654. this.setColor3("jointColor", this._jointColor);
  11655. };
  11656. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11657. get: function () {
  11658. return this._numberOfBricksHeight;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11664. set: function (value) {
  11665. this._numberOfBricksHeight = value;
  11666. this.updateShaderUniforms();
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11672. get: function () {
  11673. return this._numberOfBricksWidth;
  11674. },
  11675. set: function (value) {
  11676. this._numberOfBricksHeight = value;
  11677. this.updateShaderUniforms();
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11683. get: function () {
  11684. return this._jointColor;
  11685. },
  11686. set: function (value) {
  11687. this._jointColor = value;
  11688. this.updateShaderUniforms();
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11694. get: function () {
  11695. return this._brickColor;
  11696. },
  11697. set: function (value) {
  11698. this._brickColor = value;
  11699. this.updateShaderUniforms();
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. return BrickProceduralTexture;
  11705. })(BABYLON.ProceduralTexture);
  11706. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11707. var MarbleProceduralTexture = (function (_super) {
  11708. __extends(MarbleProceduralTexture, _super);
  11709. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11710. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11711. this._numberOfTilesHeight = 3;
  11712. this._numberOfTilesWidth = 3;
  11713. this._amplitude = 9.0;
  11714. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11715. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11716. this.updateShaderUniforms();
  11717. this.refreshRate = 0;
  11718. }
  11719. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11720. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11721. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11722. this.setFloat("amplitude", this._amplitude);
  11723. this.setColor3("marbleColor", this._marbleColor);
  11724. this.setColor3("jointColor", this._jointColor);
  11725. };
  11726. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11727. get: function () {
  11728. return this._numberOfTilesHeight;
  11729. },
  11730. set: function (value) {
  11731. this._numberOfTilesHeight = value;
  11732. this.updateShaderUniforms();
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11738. get: function () {
  11739. return this._numberOfTilesWidth;
  11740. },
  11741. set: function (value) {
  11742. this._numberOfTilesWidth = value;
  11743. this.updateShaderUniforms();
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11749. get: function () {
  11750. return this._jointColor;
  11751. },
  11752. set: function (value) {
  11753. this._jointColor = value;
  11754. this.updateShaderUniforms();
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11760. get: function () {
  11761. return this._marbleColor;
  11762. },
  11763. set: function (value) {
  11764. this._marbleColor = value;
  11765. this.updateShaderUniforms();
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. return MarbleProceduralTexture;
  11771. })(BABYLON.ProceduralTexture);
  11772. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11773. })(BABYLON || (BABYLON = {}));
  11774. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11775. var BABYLON;
  11776. (function (BABYLON) {
  11777. var CustomProceduralTexture = (function (_super) {
  11778. __extends(CustomProceduralTexture, _super);
  11779. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11780. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11781. this._animate = true;
  11782. this._time = 0;
  11783. this._texturePath = texturePath;
  11784. //Try to load json
  11785. this.loadJson(texturePath);
  11786. this.refreshRate = 1;
  11787. }
  11788. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11789. var _this = this;
  11790. var that = this;
  11791. function noConfigFile() {
  11792. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11793. try {
  11794. that.setFragment(that._texturePath);
  11795. } catch (ex) {
  11796. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11797. }
  11798. }
  11799. var configFileUrl = jsonUrl + "/config.json";
  11800. var xhr = new XMLHttpRequest();
  11801. xhr.open("GET", configFileUrl, true);
  11802. xhr.addEventListener("load", function () {
  11803. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11804. try {
  11805. _this._config = JSON.parse(xhr.response);
  11806. _this.updateShaderUniforms();
  11807. _this.updateTextures();
  11808. _this.setFragment(_this._texturePath + "/custom");
  11809. _this._animate = _this._config.animate;
  11810. _this.refreshRate = _this._config.refreshrate;
  11811. } catch (ex) {
  11812. noConfigFile();
  11813. }
  11814. } else {
  11815. noConfigFile();
  11816. }
  11817. }, false);
  11818. xhr.addEventListener("error", function (event) {
  11819. noConfigFile();
  11820. }, false);
  11821. try {
  11822. xhr.send();
  11823. } catch (ex) {
  11824. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11825. }
  11826. };
  11827. CustomProceduralTexture.prototype.isReady = function () {
  11828. if (!_super.prototype.isReady.call(this)) {
  11829. return false;
  11830. }
  11831. for (var name in this._textures) {
  11832. var texture = this._textures[name];
  11833. if (!texture.isReady()) {
  11834. return false;
  11835. }
  11836. }
  11837. return true;
  11838. };
  11839. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11840. if (this._animate) {
  11841. this._time += this.getScene().getAnimationRatio() * 0.03;
  11842. this.updateShaderUniforms();
  11843. }
  11844. _super.prototype.render.call(this, useCameraPostProcess);
  11845. };
  11846. CustomProceduralTexture.prototype.updateTextures = function () {
  11847. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11848. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11849. }
  11850. };
  11851. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11852. if (this._config) {
  11853. for (var j = 0; j < this._config.uniforms.length; j++) {
  11854. var uniform = this._config.uniforms[j];
  11855. switch (uniform.type) {
  11856. case "float":
  11857. this.setFloat(uniform.name, uniform.value);
  11858. break;
  11859. case "color3":
  11860. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11861. break;
  11862. case "color4":
  11863. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11864. break;
  11865. case "vector2":
  11866. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11867. break;
  11868. case "vector3":
  11869. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11870. break;
  11871. }
  11872. }
  11873. }
  11874. this.setFloat("time", this._time);
  11875. };
  11876. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11877. get: function () {
  11878. return this._animate;
  11879. },
  11880. set: function (value) {
  11881. this._animate = value;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. return CustomProceduralTexture;
  11887. })(BABYLON.ProceduralTexture);
  11888. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11889. })(BABYLON || (BABYLON = {}));
  11890. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11891. var BABYLON;
  11892. (function (BABYLON) {
  11893. var MirrorTexture = (function (_super) {
  11894. __extends(MirrorTexture, _super);
  11895. function MirrorTexture(name, size, scene, generateMipMaps) {
  11896. var _this = this;
  11897. _super.call(this, name, size, scene, generateMipMaps, true);
  11898. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11899. this._transformMatrix = BABYLON.Matrix.Zero();
  11900. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11901. this.onBeforeRender = function () {
  11902. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11903. _this._savedViewMatrix = scene.getViewMatrix();
  11904. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11905. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11906. scene.clipPlane = _this.mirrorPlane;
  11907. scene.getEngine().cullBackFaces = false;
  11908. };
  11909. this.onAfterRender = function () {
  11910. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11911. scene.getEngine().cullBackFaces = true;
  11912. delete scene.clipPlane;
  11913. };
  11914. }
  11915. MirrorTexture.prototype.clone = function () {
  11916. var textureSize = this.getSize();
  11917. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11918. // Base texture
  11919. newTexture.hasAlpha = this.hasAlpha;
  11920. newTexture.level = this.level;
  11921. // Mirror Texture
  11922. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11923. newTexture.renderList = this.renderList.slice(0);
  11924. return newTexture;
  11925. };
  11926. return MirrorTexture;
  11927. })(BABYLON.RenderTargetTexture);
  11928. BABYLON.MirrorTexture = MirrorTexture;
  11929. })(BABYLON || (BABYLON = {}));
  11930. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11931. var BABYLON;
  11932. (function (BABYLON) {
  11933. var DynamicTexture = (function (_super) {
  11934. __extends(DynamicTexture, _super);
  11935. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11936. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11937. _super.call(this, null, scene, !generateMipMaps);
  11938. this.name = name;
  11939. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11940. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11941. this._generateMipMaps = generateMipMaps;
  11942. if (options.getContext) {
  11943. this._canvas = options;
  11944. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11945. } else {
  11946. this._canvas = document.createElement("canvas");
  11947. if (options.width) {
  11948. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11949. } else {
  11950. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11951. }
  11952. }
  11953. var textureSize = this.getSize();
  11954. this._canvas.width = textureSize.width;
  11955. this._canvas.height = textureSize.height;
  11956. this._context = this._canvas.getContext("2d");
  11957. }
  11958. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11959. get: function () {
  11960. return true;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. DynamicTexture.prototype.scale = function (ratio) {
  11966. var textureSize = this.getSize();
  11967. textureSize.width *= ratio;
  11968. textureSize.height *= ratio;
  11969. this._canvas.width = textureSize.width;
  11970. this._canvas.height = textureSize.height;
  11971. this.releaseInternalTexture();
  11972. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11973. };
  11974. DynamicTexture.prototype.getContext = function () {
  11975. return this._context;
  11976. };
  11977. DynamicTexture.prototype.update = function (invertY) {
  11978. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11979. };
  11980. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11981. var size = this.getSize();
  11982. if (clearColor) {
  11983. this._context.fillStyle = clearColor;
  11984. this._context.fillRect(0, 0, size.width, size.height);
  11985. }
  11986. this._context.font = font;
  11987. if (x === null) {
  11988. var textSize = this._context.measureText(text);
  11989. x = (size.width - textSize.width) / 2;
  11990. }
  11991. this._context.fillStyle = color;
  11992. this._context.fillText(text, x, y);
  11993. this.update(invertY);
  11994. };
  11995. DynamicTexture.prototype.clone = function () {
  11996. var textureSize = this.getSize();
  11997. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11998. // Base texture
  11999. newTexture.hasAlpha = this.hasAlpha;
  12000. newTexture.level = this.level;
  12001. // Dynamic Texture
  12002. newTexture.wrapU = this.wrapU;
  12003. newTexture.wrapV = this.wrapV;
  12004. return newTexture;
  12005. };
  12006. return DynamicTexture;
  12007. })(BABYLON.Texture);
  12008. BABYLON.DynamicTexture = DynamicTexture;
  12009. })(BABYLON || (BABYLON = {}));
  12010. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12011. var BABYLON;
  12012. (function (BABYLON) {
  12013. var VideoTexture = (function (_super) {
  12014. __extends(VideoTexture, _super);
  12015. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12016. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12017. var _this = this;
  12018. _super.call(this, null, scene, !generateMipMaps, invertY);
  12019. this._autoLaunch = true;
  12020. this.name = name;
  12021. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12022. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12023. var requiredWidth = size.width || size;
  12024. var requiredHeight = size.height || size;
  12025. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12026. var textureSize = this.getSize();
  12027. this.video = document.createElement("video");
  12028. this.video.width = textureSize.width;
  12029. this.video.height = textureSize.height;
  12030. this.video.autoplay = false;
  12031. this.video.loop = true;
  12032. this.video.addEventListener("canplaythrough", function () {
  12033. if (_this._texture) {
  12034. _this._texture.isReady = true;
  12035. }
  12036. });
  12037. urls.forEach(function (url) {
  12038. var source = document.createElement("source");
  12039. source.src = url;
  12040. _this.video.appendChild(source);
  12041. });
  12042. this._lastUpdate = BABYLON.Tools.Now;
  12043. }
  12044. VideoTexture.prototype.update = function () {
  12045. if (this._autoLaunch) {
  12046. this._autoLaunch = false;
  12047. this.video.play();
  12048. }
  12049. var now = BABYLON.Tools.Now;
  12050. if (now - this._lastUpdate < 15) {
  12051. return false;
  12052. }
  12053. this._lastUpdate = now;
  12054. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12055. return true;
  12056. };
  12057. return VideoTexture;
  12058. })(BABYLON.Texture);
  12059. BABYLON.VideoTexture = VideoTexture;
  12060. })(BABYLON || (BABYLON = {}));
  12061. //# sourceMappingURL=babylon.videoTexture.js.map
  12062. var BABYLON;
  12063. (function (BABYLON) {
  12064. var EffectFallbacks = (function () {
  12065. function EffectFallbacks() {
  12066. this._defines = {};
  12067. this._currentRank = 32;
  12068. this._maxRank = -1;
  12069. }
  12070. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12071. if (!this._defines[rank]) {
  12072. if (rank < this._currentRank) {
  12073. this._currentRank = rank;
  12074. }
  12075. if (rank > this._maxRank) {
  12076. this._maxRank = rank;
  12077. }
  12078. this._defines[rank] = new Array();
  12079. }
  12080. this._defines[rank].push(define);
  12081. };
  12082. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12083. get: function () {
  12084. return this._currentRank <= this._maxRank;
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12090. var currentFallbacks = this._defines[this._currentRank];
  12091. for (var index = 0; index < currentFallbacks.length; index++) {
  12092. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12093. }
  12094. this._currentRank++;
  12095. return currentDefines;
  12096. };
  12097. return EffectFallbacks;
  12098. })();
  12099. BABYLON.EffectFallbacks = EffectFallbacks;
  12100. var Effect = (function () {
  12101. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12102. var _this = this;
  12103. this._isReady = false;
  12104. this._compilationError = "";
  12105. this._valueCache = [];
  12106. this._engine = engine;
  12107. this.name = baseName;
  12108. this.defines = defines;
  12109. this._uniformsNames = uniformsNames.concat(samplers);
  12110. this._samplers = samplers;
  12111. this._attributesNames = attributesNames;
  12112. this.onError = onError;
  12113. this.onCompiled = onCompiled;
  12114. var vertexSource;
  12115. var fragmentSource;
  12116. if (baseName.vertexElement) {
  12117. vertexSource = document.getElementById(baseName.vertexElement);
  12118. if (!vertexSource) {
  12119. vertexSource = baseName.vertexElement;
  12120. }
  12121. } else {
  12122. vertexSource = baseName.vertex || baseName;
  12123. }
  12124. if (baseName.fragmentElement) {
  12125. fragmentSource = document.getElementById(baseName.fragmentElement);
  12126. if (!fragmentSource) {
  12127. fragmentSource = baseName.fragmentElement;
  12128. }
  12129. } else {
  12130. fragmentSource = baseName.fragment || baseName;
  12131. }
  12132. this._loadVertexShader(vertexSource, function (vertexCode) {
  12133. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12134. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12135. });
  12136. });
  12137. }
  12138. // Properties
  12139. Effect.prototype.isReady = function () {
  12140. return this._isReady;
  12141. };
  12142. Effect.prototype.getProgram = function () {
  12143. return this._program;
  12144. };
  12145. Effect.prototype.getAttributesNames = function () {
  12146. return this._attributesNames;
  12147. };
  12148. Effect.prototype.getAttributeLocation = function (index) {
  12149. return this._attributes[index];
  12150. };
  12151. Effect.prototype.getAttributeLocationByName = function (name) {
  12152. var index = this._attributesNames.indexOf(name);
  12153. return this._attributes[index];
  12154. };
  12155. Effect.prototype.getAttributesCount = function () {
  12156. return this._attributes.length;
  12157. };
  12158. Effect.prototype.getUniformIndex = function (uniformName) {
  12159. return this._uniformsNames.indexOf(uniformName);
  12160. };
  12161. Effect.prototype.getUniform = function (uniformName) {
  12162. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12163. };
  12164. Effect.prototype.getSamplers = function () {
  12165. return this._samplers;
  12166. };
  12167. Effect.prototype.getCompilationError = function () {
  12168. return this._compilationError;
  12169. };
  12170. // Methods
  12171. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12172. // DOM element ?
  12173. if (vertex instanceof HTMLElement) {
  12174. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12175. callback(vertexCode);
  12176. return;
  12177. }
  12178. // Is in local store ?
  12179. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12180. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12181. return;
  12182. }
  12183. var vertexShaderUrl;
  12184. if (vertex[0] === ".") {
  12185. vertexShaderUrl = vertex;
  12186. } else {
  12187. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12188. }
  12189. // Vertex shader
  12190. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12191. };
  12192. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12193. // DOM element ?
  12194. if (fragment instanceof HTMLElement) {
  12195. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12196. callback(fragmentCode);
  12197. return;
  12198. }
  12199. // Is in local store ?
  12200. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12201. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12202. return;
  12203. }
  12204. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12205. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12206. return;
  12207. }
  12208. var fragmentShaderUrl;
  12209. if (fragment[0] === ".") {
  12210. fragmentShaderUrl = fragment;
  12211. } else {
  12212. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12213. }
  12214. // Fragment shader
  12215. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12216. };
  12217. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12218. try {
  12219. var engine = this._engine;
  12220. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12221. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12222. this._attributes = engine.getAttributes(this._program, attributesNames);
  12223. for (var index = 0; index < this._samplers.length; index++) {
  12224. var sampler = this.getUniform(this._samplers[index]);
  12225. if (sampler == null) {
  12226. this._samplers.splice(index, 1);
  12227. index--;
  12228. }
  12229. }
  12230. engine.bindSamplers(this);
  12231. this._isReady = true;
  12232. if (this.onCompiled) {
  12233. this.onCompiled(this);
  12234. }
  12235. } catch (e) {
  12236. // Is it a problem with precision?
  12237. if (e.message.indexOf("highp") !== -1) {
  12238. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12239. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12240. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12241. return;
  12242. }
  12243. // Let's go through fallbacks then
  12244. if (fallbacks && fallbacks.isMoreFallbacks) {
  12245. defines = fallbacks.reduce(defines);
  12246. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12247. } else {
  12248. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12249. BABYLON.Tools.Error("Defines: " + defines);
  12250. BABYLON.Tools.Error("Error: " + e.message);
  12251. this._compilationError = e.message;
  12252. if (this.onError) {
  12253. this.onError(this, this._compilationError);
  12254. }
  12255. }
  12256. }
  12257. };
  12258. Effect.prototype._bindTexture = function (channel, texture) {
  12259. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12260. };
  12261. Effect.prototype.setTexture = function (channel, texture) {
  12262. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12263. };
  12264. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12265. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12266. };
  12267. //public _cacheMatrix(uniformName, matrix) {
  12268. // if (!this._valueCache[uniformName]) {
  12269. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12270. // }
  12271. // for (var index = 0; index < 16; index++) {
  12272. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12273. // }
  12274. //};
  12275. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12276. if (!this._valueCache[uniformName]) {
  12277. this._valueCache[uniformName] = [x, y];
  12278. return;
  12279. }
  12280. this._valueCache[uniformName][0] = x;
  12281. this._valueCache[uniformName][1] = y;
  12282. };
  12283. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12284. if (!this._valueCache[uniformName]) {
  12285. this._valueCache[uniformName] = [x, y, z];
  12286. return;
  12287. }
  12288. this._valueCache[uniformName][0] = x;
  12289. this._valueCache[uniformName][1] = y;
  12290. this._valueCache[uniformName][2] = z;
  12291. };
  12292. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12293. if (!this._valueCache[uniformName]) {
  12294. this._valueCache[uniformName] = [x, y, z, w];
  12295. return;
  12296. }
  12297. this._valueCache[uniformName][0] = x;
  12298. this._valueCache[uniformName][1] = y;
  12299. this._valueCache[uniformName][2] = z;
  12300. this._valueCache[uniformName][3] = w;
  12301. };
  12302. Effect.prototype.setArray = function (uniformName, array) {
  12303. this._engine.setArray(this.getUniform(uniformName), array);
  12304. return this;
  12305. };
  12306. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12307. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12308. return this;
  12309. };
  12310. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12311. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12312. // return;
  12313. //this._cacheMatrix(uniformName, matrix);
  12314. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12315. return this;
  12316. };
  12317. Effect.prototype.setFloat = function (uniformName, value) {
  12318. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12319. return this;
  12320. this._valueCache[uniformName] = value;
  12321. this._engine.setFloat(this.getUniform(uniformName), value);
  12322. return this;
  12323. };
  12324. Effect.prototype.setBool = function (uniformName, bool) {
  12325. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12326. return this;
  12327. this._valueCache[uniformName] = bool;
  12328. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12329. return this;
  12330. };
  12331. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12332. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12333. return this;
  12334. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12335. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12336. return this;
  12337. };
  12338. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12339. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12340. return this;
  12341. this._cacheFloat2(uniformName, x, y);
  12342. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12343. return this;
  12344. };
  12345. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12346. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12347. return this;
  12348. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12349. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12350. return this;
  12351. };
  12352. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12353. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12354. return this;
  12355. this._cacheFloat3(uniformName, x, y, z);
  12356. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12357. return this;
  12358. };
  12359. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12360. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12361. return this;
  12362. this._cacheFloat4(uniformName, x, y, z, w);
  12363. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12364. return this;
  12365. };
  12366. Effect.prototype.setColor3 = function (uniformName, color3) {
  12367. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12368. return this;
  12369. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12370. this._engine.setColor3(this.getUniform(uniformName), color3);
  12371. return this;
  12372. };
  12373. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12374. 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)
  12375. return this;
  12376. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12377. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12378. return this;
  12379. };
  12380. 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}",
  12381. 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}",
  12382. 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}",
  12383. 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 brickColor;\nuniform vec3 jointColor;\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 = brickColor;\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(jointColor, 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(jointColor, 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}",
  12384. 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}",
  12385. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12386. 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}",
  12387. 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}",
  12388. 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}",
  12389. 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 INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n 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\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\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}",
  12390. 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}",
  12391. 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}",
  12392. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\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 - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * 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}",
  12393. 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}",
  12394. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\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(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  12395. 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}",
  12396. 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}",
  12397. 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}",
  12398. 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}",
  12399. 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}",
  12400. 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}",
  12401. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\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 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\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(jointColor, 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(jointColor, 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}",
  12402. 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}",
  12403. 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}",
  12404. 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}",
  12405. 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}",
  12406. 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}",
  12407. 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}",
  12408. 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}",
  12409. 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}",
  12410. 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}",
  12411. 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}",
  12412. 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}",
  12413. 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}",
  12414. 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}",
  12415. 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}",
  12416. 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}",
  12417. };
  12418. return Effect;
  12419. })();
  12420. BABYLON.Effect = Effect;
  12421. })(BABYLON || (BABYLON = {}));
  12422. //# sourceMappingURL=babylon.effect.js.map
  12423. var BABYLON;
  12424. (function (BABYLON) {
  12425. var Material = (function () {
  12426. function Material(name, scene, doNotAdd) {
  12427. this.name = name;
  12428. this.checkReadyOnEveryCall = true;
  12429. this.checkReadyOnlyOnce = false;
  12430. this.state = "";
  12431. this.alpha = 1.0;
  12432. this.backFaceCulling = true;
  12433. this._wasPreviouslyReady = false;
  12434. this._fillMode = Material.TriangleFillMode;
  12435. this.pointSize = 1.0;
  12436. this.id = name;
  12437. this._scene = scene;
  12438. if (!doNotAdd) {
  12439. scene.materials.push(this);
  12440. }
  12441. }
  12442. Object.defineProperty(Material, "TriangleFillMode", {
  12443. get: function () {
  12444. return Material._TriangleFillMode;
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Object.defineProperty(Material, "WireFrameFillMode", {
  12450. get: function () {
  12451. return Material._WireFrameFillMode;
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. Object.defineProperty(Material, "PointFillMode", {
  12457. get: function () {
  12458. return Material._PointFillMode;
  12459. },
  12460. enumerable: true,
  12461. configurable: true
  12462. });
  12463. Object.defineProperty(Material.prototype, "wireframe", {
  12464. get: function () {
  12465. return this._fillMode === Material.WireFrameFillMode;
  12466. },
  12467. set: function (value) {
  12468. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. Object.defineProperty(Material.prototype, "pointsCloud", {
  12474. get: function () {
  12475. return this._fillMode === Material.PointFillMode;
  12476. },
  12477. set: function (value) {
  12478. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12479. },
  12480. enumerable: true,
  12481. configurable: true
  12482. });
  12483. Object.defineProperty(Material.prototype, "fillMode", {
  12484. get: function () {
  12485. return this._fillMode;
  12486. },
  12487. set: function (value) {
  12488. this._fillMode = value;
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Material.prototype.isReady = function (mesh, useInstances) {
  12494. return true;
  12495. };
  12496. Material.prototype.getEffect = function () {
  12497. return this._effect;
  12498. };
  12499. Material.prototype.getScene = function () {
  12500. return this._scene;
  12501. };
  12502. Material.prototype.needAlphaBlending = function () {
  12503. return (this.alpha < 1.0);
  12504. };
  12505. Material.prototype.needAlphaTesting = function () {
  12506. return false;
  12507. };
  12508. Material.prototype.getAlphaTestTexture = function () {
  12509. return null;
  12510. };
  12511. Material.prototype.trackCreation = function (onCompiled, onError) {
  12512. };
  12513. Material.prototype._preBind = function () {
  12514. var engine = this._scene.getEngine();
  12515. engine.enableEffect(this._effect);
  12516. engine.setState(this.backFaceCulling);
  12517. };
  12518. Material.prototype.bind = function (world, mesh) {
  12519. this._scene._cachedMaterial = this;
  12520. if (this.onBind) {
  12521. this.onBind(this);
  12522. }
  12523. };
  12524. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12525. };
  12526. Material.prototype.unbind = function () {
  12527. };
  12528. Material.prototype.dispose = function (forceDisposeEffect) {
  12529. // Remove from scene
  12530. var index = this._scene.materials.indexOf(this);
  12531. this._scene.materials.splice(index, 1);
  12532. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12533. if (forceDisposeEffect && this._effect) {
  12534. this._scene.getEngine()._releaseEffect(this._effect);
  12535. this._effect = null;
  12536. }
  12537. // Callback
  12538. if (this.onDispose) {
  12539. this.onDispose();
  12540. }
  12541. };
  12542. Material._TriangleFillMode = 0;
  12543. Material._WireFrameFillMode = 1;
  12544. Material._PointFillMode = 2;
  12545. return Material;
  12546. })();
  12547. BABYLON.Material = Material;
  12548. })(BABYLON || (BABYLON = {}));
  12549. //# sourceMappingURL=babylon.material.js.map
  12550. var BABYLON;
  12551. (function (BABYLON) {
  12552. var maxSimultaneousLights = 4;
  12553. var FresnelParameters = (function () {
  12554. function FresnelParameters() {
  12555. this.isEnabled = true;
  12556. this.leftColor = BABYLON.Color3.White();
  12557. this.rightColor = BABYLON.Color3.Black();
  12558. this.bias = 0;
  12559. this.power = 1;
  12560. }
  12561. return FresnelParameters;
  12562. })();
  12563. BABYLON.FresnelParameters = FresnelParameters;
  12564. var StandardMaterial = (function (_super) {
  12565. __extends(StandardMaterial, _super);
  12566. function StandardMaterial(name, scene) {
  12567. var _this = this;
  12568. _super.call(this, name, scene);
  12569. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12570. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12571. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12572. this.specularPower = 64;
  12573. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12574. this.useAlphaFromDiffuseTexture = false;
  12575. this.useSpecularOverAlpha = true;
  12576. this.fogEnabled = true;
  12577. this._cachedDefines = null;
  12578. this._renderTargets = new BABYLON.SmartArray(16);
  12579. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12580. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12581. this._scaledDiffuse = new BABYLON.Color3();
  12582. this._scaledSpecular = new BABYLON.Color3();
  12583. this.getRenderTargetTextures = function () {
  12584. _this._renderTargets.reset();
  12585. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12586. _this._renderTargets.push(_this.reflectionTexture);
  12587. }
  12588. return _this._renderTargets;
  12589. };
  12590. }
  12591. StandardMaterial.prototype.needAlphaBlending = function () {
  12592. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12593. };
  12594. StandardMaterial.prototype.needAlphaTesting = function () {
  12595. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12596. };
  12597. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12598. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12599. };
  12600. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12601. return this.diffuseTexture;
  12602. };
  12603. // Methods
  12604. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12605. if (this.checkReadyOnlyOnce) {
  12606. if (this._wasPreviouslyReady) {
  12607. return true;
  12608. }
  12609. }
  12610. var scene = this.getScene();
  12611. if (!this.checkReadyOnEveryCall) {
  12612. if (this._renderId === scene.getRenderId()) {
  12613. return true;
  12614. }
  12615. }
  12616. var engine = scene.getEngine();
  12617. var defines = [];
  12618. var fallbacks = new BABYLON.EffectFallbacks();
  12619. // Textures
  12620. if (scene.texturesEnabled) {
  12621. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12622. if (!this.diffuseTexture.isReady()) {
  12623. return false;
  12624. } else {
  12625. defines.push("#define DIFFUSE");
  12626. }
  12627. }
  12628. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12629. if (!this.ambientTexture.isReady()) {
  12630. return false;
  12631. } else {
  12632. defines.push("#define AMBIENT");
  12633. }
  12634. }
  12635. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12636. if (!this.opacityTexture.isReady()) {
  12637. return false;
  12638. } else {
  12639. defines.push("#define OPACITY");
  12640. if (this.opacityTexture.getAlphaFromRGB) {
  12641. defines.push("#define OPACITYRGB");
  12642. }
  12643. }
  12644. }
  12645. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12646. if (!this.reflectionTexture.isReady()) {
  12647. return false;
  12648. } else {
  12649. defines.push("#define REFLECTION");
  12650. fallbacks.addFallback(0, "REFLECTION");
  12651. }
  12652. }
  12653. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12654. if (!this.emissiveTexture.isReady()) {
  12655. return false;
  12656. } else {
  12657. defines.push("#define EMISSIVE");
  12658. }
  12659. }
  12660. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12661. if (!this.specularTexture.isReady()) {
  12662. return false;
  12663. } else {
  12664. defines.push("#define SPECULAR");
  12665. fallbacks.addFallback(0, "SPECULAR");
  12666. }
  12667. }
  12668. }
  12669. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12670. if (!this.bumpTexture.isReady()) {
  12671. return false;
  12672. } else {
  12673. defines.push("#define BUMP");
  12674. fallbacks.addFallback(0, "BUMP");
  12675. }
  12676. }
  12677. // Effect
  12678. if (this.useSpecularOverAlpha) {
  12679. defines.push("#define SPECULAROVERALPHA");
  12680. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12681. }
  12682. if (scene.clipPlane) {
  12683. defines.push("#define CLIPPLANE");
  12684. }
  12685. if (engine.getAlphaTesting()) {
  12686. defines.push("#define ALPHATEST");
  12687. }
  12688. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12689. defines.push("#define ALPHAFROMDIFFUSE");
  12690. }
  12691. // Point size
  12692. if (this.pointsCloud || scene.forcePointsCloud) {
  12693. defines.push("#define POINTSIZE");
  12694. }
  12695. // Fog
  12696. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12697. defines.push("#define FOG");
  12698. fallbacks.addFallback(1, "FOG");
  12699. }
  12700. var shadowsActivated = false;
  12701. var lightIndex = 0;
  12702. if (scene.lightsEnabled) {
  12703. for (var index = 0; index < scene.lights.length; index++) {
  12704. var light = scene.lights[index];
  12705. if (!light.isEnabled()) {
  12706. continue;
  12707. }
  12708. // Excluded check
  12709. if (light._excludedMeshesIds.length > 0) {
  12710. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12711. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12712. if (excludedMesh) {
  12713. light.excludedMeshes.push(excludedMesh);
  12714. }
  12715. }
  12716. light._excludedMeshesIds = [];
  12717. }
  12718. // Included check
  12719. if (light._includedOnlyMeshesIds.length > 0) {
  12720. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12721. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12722. if (includedOnlyMesh) {
  12723. light.includedOnlyMeshes.push(includedOnlyMesh);
  12724. }
  12725. }
  12726. light._includedOnlyMeshesIds = [];
  12727. }
  12728. if (!light.canAffectMesh(mesh)) {
  12729. continue;
  12730. }
  12731. defines.push("#define LIGHT" + lightIndex);
  12732. if (lightIndex > 0) {
  12733. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12734. }
  12735. var type;
  12736. if (light instanceof BABYLON.SpotLight) {
  12737. type = "#define SPOTLIGHT" + lightIndex;
  12738. } else if (light instanceof BABYLON.HemisphericLight) {
  12739. type = "#define HEMILIGHT" + lightIndex;
  12740. } else {
  12741. type = "#define POINTDIRLIGHT" + lightIndex;
  12742. }
  12743. defines.push(type);
  12744. if (lightIndex > 0) {
  12745. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12746. }
  12747. // Shadows
  12748. if (scene.shadowsEnabled) {
  12749. var shadowGenerator = light.getShadowGenerator();
  12750. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12751. defines.push("#define SHADOW" + lightIndex);
  12752. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12753. if (!shadowsActivated) {
  12754. defines.push("#define SHADOWS");
  12755. shadowsActivated = true;
  12756. }
  12757. if (shadowGenerator.useVarianceShadowMap) {
  12758. defines.push("#define SHADOWVSM" + lightIndex);
  12759. if (lightIndex > 0) {
  12760. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12761. }
  12762. }
  12763. if (shadowGenerator.usePoissonSampling) {
  12764. defines.push("#define SHADOWPCF" + lightIndex);
  12765. if (lightIndex > 0) {
  12766. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12767. }
  12768. }
  12769. }
  12770. }
  12771. lightIndex++;
  12772. if (lightIndex === maxSimultaneousLights)
  12773. break;
  12774. }
  12775. }
  12776. if (StandardMaterial.FresnelEnabled) {
  12777. // Fresnel
  12778. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12779. var fresnelRank = 1;
  12780. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12781. defines.push("#define DIFFUSEFRESNEL");
  12782. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12783. fresnelRank++;
  12784. }
  12785. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12786. defines.push("#define OPACITYFRESNEL");
  12787. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12788. fresnelRank++;
  12789. }
  12790. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12791. defines.push("#define REFLECTIONFRESNEL");
  12792. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12793. fresnelRank++;
  12794. }
  12795. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12796. defines.push("#define EMISSIVEFRESNEL");
  12797. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12798. fresnelRank++;
  12799. }
  12800. defines.push("#define FRESNEL");
  12801. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12802. }
  12803. }
  12804. // Attribs
  12805. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12806. if (mesh) {
  12807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12808. attribs.push(BABYLON.VertexBuffer.UVKind);
  12809. defines.push("#define UV1");
  12810. }
  12811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12813. defines.push("#define UV2");
  12814. }
  12815. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12816. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12817. defines.push("#define VERTEXCOLOR");
  12818. if (mesh.hasVertexAlpha) {
  12819. defines.push("#define VERTEXALPHA");
  12820. }
  12821. }
  12822. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12823. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12824. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12825. defines.push("#define BONES");
  12826. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12827. defines.push("#define BONES4");
  12828. fallbacks.addFallback(0, "BONES4");
  12829. }
  12830. // Instances
  12831. if (useInstances) {
  12832. defines.push("#define INSTANCES");
  12833. attribs.push("world0");
  12834. attribs.push("world1");
  12835. attribs.push("world2");
  12836. attribs.push("world3");
  12837. }
  12838. }
  12839. // Get correct effect
  12840. var join = defines.join("\n");
  12841. if (this._cachedDefines !== join) {
  12842. this._cachedDefines = join;
  12843. scene.resetCachedMaterial();
  12844. // Legacy browser patch
  12845. var shaderName = "default";
  12846. if (!scene.getEngine().getCaps().standardDerivatives) {
  12847. shaderName = "legacydefault";
  12848. }
  12849. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12850. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12851. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12852. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12853. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12854. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12855. "vFogInfos", "vFogColor", "pointSize",
  12856. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12857. "mBones",
  12858. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12859. "darkness0", "darkness1", "darkness2", "darkness3",
  12860. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12861. ], [
  12862. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12863. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12864. ], join, fallbacks, this.onCompiled, this.onError);
  12865. }
  12866. if (!this._effect.isReady()) {
  12867. return false;
  12868. }
  12869. this._renderId = scene.getRenderId();
  12870. this._wasPreviouslyReady = true;
  12871. return true;
  12872. };
  12873. StandardMaterial.prototype.unbind = function () {
  12874. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12875. this._effect.setTexture("reflection2DSampler", null);
  12876. }
  12877. };
  12878. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12879. this._effect.setMatrix("world", world);
  12880. };
  12881. StandardMaterial.prototype.bind = function (world, mesh) {
  12882. var scene = this.getScene();
  12883. // Matrices
  12884. this.bindOnlyWorldMatrix(world);
  12885. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12886. // Bones
  12887. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12888. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12889. }
  12890. if (scene.getCachedMaterial() !== this) {
  12891. if (StandardMaterial.FresnelEnabled) {
  12892. // Fresnel
  12893. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12894. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12895. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12896. }
  12897. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12898. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12899. }
  12900. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12901. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12902. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12903. }
  12904. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12905. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12906. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12907. }
  12908. }
  12909. // Textures
  12910. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12911. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12912. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12913. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12914. }
  12915. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12916. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12917. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12918. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12919. }
  12920. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12921. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12922. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12923. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12924. }
  12925. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12926. if (this.reflectionTexture.isCube) {
  12927. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12928. } else {
  12929. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12930. }
  12931. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12932. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12933. }
  12934. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12935. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12936. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12937. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12938. }
  12939. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12940. this._effect.setTexture("specularSampler", this.specularTexture);
  12941. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12942. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12943. }
  12944. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12945. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12946. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12947. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12948. }
  12949. // Clip plane
  12950. if (scene.clipPlane) {
  12951. var clipPlane = scene.clipPlane;
  12952. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12953. }
  12954. // Point size
  12955. if (this.pointsCloud) {
  12956. this._effect.setFloat("pointSize", this.pointSize);
  12957. }
  12958. // Colors
  12959. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12960. // Scaling down color according to emissive
  12961. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12962. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12963. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12964. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12965. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12966. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12967. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12968. }
  12969. // Scaling down color according to emissive
  12970. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12971. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12972. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12973. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12974. if (scene.lightsEnabled) {
  12975. var lightIndex = 0;
  12976. for (var index = 0; index < scene.lights.length; index++) {
  12977. var light = scene.lights[index];
  12978. if (!light.isEnabled()) {
  12979. continue;
  12980. }
  12981. if (!light.canAffectMesh(mesh)) {
  12982. continue;
  12983. }
  12984. if (light instanceof BABYLON.PointLight) {
  12985. // Point Light
  12986. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12987. } else if (light instanceof BABYLON.DirectionalLight) {
  12988. // Directional Light
  12989. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12990. } else if (light instanceof BABYLON.SpotLight) {
  12991. // Spot Light
  12992. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12993. } else if (light instanceof BABYLON.HemisphericLight) {
  12994. // Hemispheric Light
  12995. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12996. }
  12997. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12998. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12999. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13000. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13001. // Shadows
  13002. if (scene.shadowsEnabled) {
  13003. var shadowGenerator = light.getShadowGenerator();
  13004. if (mesh.receiveShadows && shadowGenerator) {
  13005. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13006. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13007. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13008. }
  13009. }
  13010. lightIndex++;
  13011. if (lightIndex === maxSimultaneousLights)
  13012. break;
  13013. }
  13014. }
  13015. // View
  13016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13017. this._effect.setMatrix("view", scene.getViewMatrix());
  13018. }
  13019. // Fog
  13020. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13021. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13022. this._effect.setColor3("vFogColor", scene.fogColor);
  13023. }
  13024. _super.prototype.bind.call(this, world, mesh);
  13025. };
  13026. StandardMaterial.prototype.getAnimatables = function () {
  13027. var results = [];
  13028. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13029. results.push(this.diffuseTexture);
  13030. }
  13031. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13032. results.push(this.ambientTexture);
  13033. }
  13034. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13035. results.push(this.opacityTexture);
  13036. }
  13037. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13038. results.push(this.reflectionTexture);
  13039. }
  13040. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13041. results.push(this.emissiveTexture);
  13042. }
  13043. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13044. results.push(this.specularTexture);
  13045. }
  13046. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13047. results.push(this.bumpTexture);
  13048. }
  13049. return results;
  13050. };
  13051. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13052. if (this.diffuseTexture) {
  13053. this.diffuseTexture.dispose();
  13054. }
  13055. if (this.ambientTexture) {
  13056. this.ambientTexture.dispose();
  13057. }
  13058. if (this.opacityTexture) {
  13059. this.opacityTexture.dispose();
  13060. }
  13061. if (this.reflectionTexture) {
  13062. this.reflectionTexture.dispose();
  13063. }
  13064. if (this.emissiveTexture) {
  13065. this.emissiveTexture.dispose();
  13066. }
  13067. if (this.specularTexture) {
  13068. this.specularTexture.dispose();
  13069. }
  13070. if (this.bumpTexture) {
  13071. this.bumpTexture.dispose();
  13072. }
  13073. _super.prototype.dispose.call(this, forceDisposeEffect);
  13074. };
  13075. StandardMaterial.prototype.clone = function (name) {
  13076. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13077. // Base material
  13078. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13079. newStandardMaterial.alpha = this.alpha;
  13080. newStandardMaterial.fillMode = this.fillMode;
  13081. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13082. // Standard material
  13083. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13084. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13085. }
  13086. if (this.ambientTexture && this.ambientTexture.clone) {
  13087. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13088. }
  13089. if (this.opacityTexture && this.opacityTexture.clone) {
  13090. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13091. }
  13092. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13093. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13094. }
  13095. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13096. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13097. }
  13098. if (this.specularTexture && this.specularTexture.clone) {
  13099. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13100. }
  13101. if (this.bumpTexture && this.bumpTexture.clone) {
  13102. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13103. }
  13104. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13105. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13106. newStandardMaterial.specularColor = this.specularColor.clone();
  13107. newStandardMaterial.specularPower = this.specularPower;
  13108. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13109. return newStandardMaterial;
  13110. };
  13111. StandardMaterial.DiffuseTextureEnabled = true;
  13112. StandardMaterial.AmbientTextureEnabled = true;
  13113. StandardMaterial.OpacityTextureEnabled = true;
  13114. StandardMaterial.ReflectionTextureEnabled = true;
  13115. StandardMaterial.EmissiveTextureEnabled = true;
  13116. StandardMaterial.SpecularTextureEnabled = true;
  13117. StandardMaterial.BumpTextureEnabled = true;
  13118. StandardMaterial.FresnelEnabled = true;
  13119. return StandardMaterial;
  13120. })(BABYLON.Material);
  13121. BABYLON.StandardMaterial = StandardMaterial;
  13122. })(BABYLON || (BABYLON = {}));
  13123. //# sourceMappingURL=babylon.standardMaterial.js.map
  13124. var BABYLON;
  13125. (function (BABYLON) {
  13126. var MultiMaterial = (function (_super) {
  13127. __extends(MultiMaterial, _super);
  13128. function MultiMaterial(name, scene) {
  13129. _super.call(this, name, scene, true);
  13130. this.subMaterials = new Array();
  13131. scene.multiMaterials.push(this);
  13132. }
  13133. // Properties
  13134. MultiMaterial.prototype.getSubMaterial = function (index) {
  13135. if (index < 0 || index >= this.subMaterials.length) {
  13136. return this.getScene().defaultMaterial;
  13137. }
  13138. return this.subMaterials[index];
  13139. };
  13140. // Methods
  13141. MultiMaterial.prototype.isReady = function (mesh) {
  13142. for (var index = 0; index < this.subMaterials.length; index++) {
  13143. var subMaterial = this.subMaterials[index];
  13144. if (subMaterial) {
  13145. if (!this.subMaterials[index].isReady(mesh)) {
  13146. return false;
  13147. }
  13148. }
  13149. }
  13150. return true;
  13151. };
  13152. return MultiMaterial;
  13153. })(BABYLON.Material);
  13154. BABYLON.MultiMaterial = MultiMaterial;
  13155. })(BABYLON || (BABYLON = {}));
  13156. //# sourceMappingURL=babylon.multiMaterial.js.map
  13157. var BABYLON;
  13158. (function (BABYLON) {
  13159. var Database = (function () {
  13160. function Database(urlToScene, callbackManifestChecked) {
  13161. // Handling various flavors of prefixed version of IndexedDB
  13162. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13163. this.callbackManifestChecked = callbackManifestChecked;
  13164. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13165. this.db = null;
  13166. this.enableSceneOffline = false;
  13167. this.enableTexturesOffline = false;
  13168. this.manifestVersionFound = 0;
  13169. this.mustUpdateRessources = false;
  13170. this.hasReachedQuota = false;
  13171. this.checkManifestFile();
  13172. }
  13173. Database.prototype.checkManifestFile = function () {
  13174. var _this = this;
  13175. function noManifestFile() {
  13176. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13177. that.enableSceneOffline = false;
  13178. that.enableTexturesOffline = false;
  13179. that.callbackManifestChecked(false);
  13180. }
  13181. var that = this;
  13182. var manifestURL = this.currentSceneUrl + ".manifest";
  13183. var xhr = new XMLHttpRequest();
  13184. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13185. xhr.open("GET", manifestURLTimeStamped, true);
  13186. xhr.addEventListener("load", function () {
  13187. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13188. try {
  13189. var manifestFile = JSON.parse(xhr.response);
  13190. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13191. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13192. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13193. _this.manifestVersionFound = manifestFile.version;
  13194. }
  13195. if (_this.callbackManifestChecked) {
  13196. _this.callbackManifestChecked(true);
  13197. }
  13198. } catch (ex) {
  13199. noManifestFile();
  13200. }
  13201. } else {
  13202. noManifestFile();
  13203. }
  13204. }, false);
  13205. xhr.addEventListener("error", function (event) {
  13206. noManifestFile();
  13207. }, false);
  13208. try {
  13209. xhr.send();
  13210. } catch (ex) {
  13211. BABYLON.Tools.Error("Error on XHR send request.");
  13212. that.callbackManifestChecked(false);
  13213. }
  13214. };
  13215. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13216. var _this = this;
  13217. function handleError() {
  13218. that.isSupported = false;
  13219. if (errorCallback)
  13220. errorCallback();
  13221. }
  13222. var that = this;
  13223. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13224. // Your browser doesn't support IndexedDB
  13225. this.isSupported = false;
  13226. if (errorCallback)
  13227. errorCallback();
  13228. } else {
  13229. // If the DB hasn't been opened or created yet
  13230. if (!this.db) {
  13231. this.hasReachedQuota = false;
  13232. this.isSupported = true;
  13233. var request = this.idbFactory.open("babylonjs", 1);
  13234. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13235. request.onerror = function (event) {
  13236. handleError();
  13237. };
  13238. // executes when a version change transaction cannot complete due to other active transactions
  13239. request.onblocked = function (event) {
  13240. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13241. handleError();
  13242. };
  13243. // DB has been opened successfully
  13244. request.onsuccess = function (event) {
  13245. _this.db = request.result;
  13246. successCallback();
  13247. };
  13248. // Initialization of the DB. Creating Scenes & Textures stores
  13249. request.onupgradeneeded = function (event) {
  13250. _this.db = (event.target).result;
  13251. try {
  13252. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13253. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13254. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13255. } catch (ex) {
  13256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13257. handleError();
  13258. }
  13259. };
  13260. } else {
  13261. if (successCallback)
  13262. successCallback();
  13263. }
  13264. }
  13265. };
  13266. Database.prototype.loadImageFromDB = function (url, image) {
  13267. var _this = this;
  13268. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13269. var saveAndLoadImage = function () {
  13270. if (!_this.hasReachedQuota && _this.db !== null) {
  13271. // the texture is not yet in the DB, let's try to save it
  13272. _this._saveImageIntoDBAsync(completeURL, image);
  13273. } else {
  13274. image.src = url;
  13275. }
  13276. };
  13277. if (!this.mustUpdateRessources) {
  13278. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13279. } else {
  13280. saveAndLoadImage();
  13281. }
  13282. };
  13283. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13284. if (this.isSupported && this.db !== null) {
  13285. var texture;
  13286. var transaction = this.db.transaction(["textures"]);
  13287. transaction.onabort = function (event) {
  13288. image.src = url;
  13289. };
  13290. transaction.oncomplete = function (event) {
  13291. var blobTextureURL;
  13292. if (texture) {
  13293. var URL = window.URL || window.webkitURL;
  13294. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13295. image.onerror = function () {
  13296. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13297. image.src = url;
  13298. };
  13299. image.src = blobTextureURL;
  13300. } else {
  13301. notInDBCallback();
  13302. }
  13303. };
  13304. var getRequest = transaction.objectStore("textures").get(url);
  13305. getRequest.onsuccess = function (event) {
  13306. texture = (event.target).result;
  13307. };
  13308. getRequest.onerror = function (event) {
  13309. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13310. image.src = url;
  13311. };
  13312. } else {
  13313. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13314. image.src = url;
  13315. }
  13316. };
  13317. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13318. var _this = this;
  13319. if (this.isSupported) {
  13320. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13321. var generateBlobUrl = function () {
  13322. var blobTextureURL;
  13323. if (blob) {
  13324. var URL = window.URL || window.webkitURL;
  13325. try {
  13326. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13327. } catch (ex) {
  13328. blobTextureURL = URL.createObjectURL(blob);
  13329. }
  13330. }
  13331. image.src = blobTextureURL;
  13332. };
  13333. if (BABYLON.Database.isUASupportingBlobStorage) {
  13334. var xhr = new XMLHttpRequest(), blob;
  13335. xhr.open("GET", url, true);
  13336. xhr.responseType = "blob";
  13337. xhr.addEventListener("load", function () {
  13338. if (xhr.status === 200) {
  13339. // Blob as response (XHR2)
  13340. blob = xhr.response;
  13341. var transaction = _this.db.transaction(["textures"], "readwrite");
  13342. // the transaction could abort because of a QuotaExceededError error
  13343. transaction.onabort = function (event) {
  13344. try {
  13345. if (event.srcElement.error.name === "QuotaExceededError") {
  13346. this.hasReachedQuota = true;
  13347. }
  13348. } catch (ex) {
  13349. }
  13350. generateBlobUrl();
  13351. };
  13352. transaction.oncomplete = function (event) {
  13353. generateBlobUrl();
  13354. };
  13355. var newTexture = { textureUrl: url, data: blob };
  13356. try {
  13357. // Put the blob into the dabase
  13358. var addRequest = transaction.objectStore("textures").put(newTexture);
  13359. addRequest.onsuccess = function (event) {
  13360. };
  13361. addRequest.onerror = function (event) {
  13362. generateBlobUrl();
  13363. };
  13364. } catch (ex) {
  13365. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13366. if (ex.code === 25) {
  13367. BABYLON.Database.isUASupportingBlobStorage = false;
  13368. }
  13369. image.src = url;
  13370. }
  13371. } else {
  13372. image.src = url;
  13373. }
  13374. }, false);
  13375. xhr.addEventListener("error", function (event) {
  13376. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13377. image.src = url;
  13378. }, false);
  13379. xhr.send();
  13380. } else {
  13381. image.src = url;
  13382. }
  13383. } else {
  13384. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13385. image.src = url;
  13386. }
  13387. };
  13388. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13389. var _this = this;
  13390. var updateVersion = function (event) {
  13391. // the version is not yet in the DB or we need to update it
  13392. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13393. };
  13394. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13395. };
  13396. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13397. var _this = this;
  13398. if (this.isSupported) {
  13399. var version;
  13400. try {
  13401. var transaction = this.db.transaction(["versions"]);
  13402. transaction.oncomplete = function (event) {
  13403. if (version) {
  13404. // If the version in the JSON file is > than the version in DB
  13405. if (_this.manifestVersionFound > version.data) {
  13406. _this.mustUpdateRessources = true;
  13407. updateInDBCallback();
  13408. } else {
  13409. callback(version.data);
  13410. }
  13411. } else {
  13412. _this.mustUpdateRessources = true;
  13413. updateInDBCallback();
  13414. }
  13415. };
  13416. transaction.onabort = function (event) {
  13417. callback(-1);
  13418. };
  13419. var getRequest = transaction.objectStore("versions").get(url);
  13420. getRequest.onsuccess = function (event) {
  13421. version = (event.target).result;
  13422. };
  13423. getRequest.onerror = function (event) {
  13424. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13425. callback(-1);
  13426. };
  13427. } catch (ex) {
  13428. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13429. callback(-1);
  13430. }
  13431. } else {
  13432. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13433. callback(-1);
  13434. }
  13435. };
  13436. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13437. var _this = this;
  13438. if (this.isSupported && !this.hasReachedQuota) {
  13439. try {
  13440. // Open a transaction to the database
  13441. var transaction = this.db.transaction(["versions"], "readwrite");
  13442. // the transaction could abort because of a QuotaExceededError error
  13443. transaction.onabort = function (event) {
  13444. try {
  13445. if (event.srcElement.error.name === "QuotaExceededError") {
  13446. _this.hasReachedQuota = true;
  13447. }
  13448. } catch (ex) {
  13449. }
  13450. callback(-1);
  13451. };
  13452. transaction.oncomplete = function (event) {
  13453. callback(_this.manifestVersionFound);
  13454. };
  13455. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13456. // Put the scene into the database
  13457. var addRequest = transaction.objectStore("versions").put(newVersion);
  13458. addRequest.onsuccess = function (event) {
  13459. };
  13460. addRequest.onerror = function (event) {
  13461. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13462. };
  13463. } catch (ex) {
  13464. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13465. callback(-1);
  13466. }
  13467. } else {
  13468. callback(-1);
  13469. }
  13470. };
  13471. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13472. var _this = this;
  13473. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13474. var saveAndLoadFile = function (event) {
  13475. // the scene is not yet in the DB, let's try to save it
  13476. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13477. };
  13478. this._checkVersionFromDB(completeUrl, function (version) {
  13479. if (version !== -1) {
  13480. if (!_this.mustUpdateRessources) {
  13481. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13482. } else {
  13483. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13484. }
  13485. } else {
  13486. errorCallback();
  13487. }
  13488. });
  13489. };
  13490. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13491. if (this.isSupported) {
  13492. var targetStore;
  13493. if (url.indexOf(".babylon") !== -1) {
  13494. targetStore = "scenes";
  13495. } else {
  13496. targetStore = "textures";
  13497. }
  13498. var file;
  13499. var transaction = this.db.transaction([targetStore]);
  13500. transaction.oncomplete = function (event) {
  13501. if (file) {
  13502. callback(file.data);
  13503. } else {
  13504. notInDBCallback();
  13505. }
  13506. };
  13507. transaction.onabort = function (event) {
  13508. notInDBCallback();
  13509. };
  13510. var getRequest = transaction.objectStore(targetStore).get(url);
  13511. getRequest.onsuccess = function (event) {
  13512. file = (event.target).result;
  13513. };
  13514. getRequest.onerror = function (event) {
  13515. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13516. notInDBCallback();
  13517. };
  13518. } else {
  13519. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13520. callback();
  13521. }
  13522. };
  13523. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13524. var _this = this;
  13525. if (this.isSupported) {
  13526. var targetStore;
  13527. if (url.indexOf(".babylon") !== -1) {
  13528. targetStore = "scenes";
  13529. } else {
  13530. targetStore = "textures";
  13531. }
  13532. // Create XHR
  13533. var xhr = new XMLHttpRequest(), fileData;
  13534. xhr.open("GET", url, true);
  13535. if (useArrayBuffer) {
  13536. xhr.responseType = "arraybuffer";
  13537. }
  13538. xhr.onprogress = progressCallback;
  13539. xhr.addEventListener("load", function () {
  13540. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13541. // Blob as response (XHR2)
  13542. //fileData = xhr.responseText;
  13543. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13544. if (!_this.hasReachedQuota) {
  13545. // Open a transaction to the database
  13546. var transaction = _this.db.transaction([targetStore], "readwrite");
  13547. // the transaction could abort because of a QuotaExceededError error
  13548. transaction.onabort = function (event) {
  13549. try {
  13550. if (event.srcElement.error.name === "QuotaExceededError") {
  13551. this.hasReachedQuota = true;
  13552. }
  13553. } catch (ex) {
  13554. }
  13555. callback(fileData);
  13556. };
  13557. transaction.oncomplete = function (event) {
  13558. callback(fileData);
  13559. };
  13560. var newFile;
  13561. if (targetStore === "scenes") {
  13562. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13563. } else {
  13564. newFile = { textureUrl: url, data: fileData };
  13565. }
  13566. try {
  13567. // Put the scene into the database
  13568. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13569. addRequest.onsuccess = function (event) {
  13570. };
  13571. addRequest.onerror = function (event) {
  13572. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13573. };
  13574. } catch (ex) {
  13575. callback(fileData);
  13576. }
  13577. } else {
  13578. callback(fileData);
  13579. }
  13580. } else {
  13581. callback();
  13582. }
  13583. }, false);
  13584. xhr.addEventListener("error", function (event) {
  13585. BABYLON.Tools.Error("error on XHR request.");
  13586. callback();
  13587. }, false);
  13588. xhr.send();
  13589. } else {
  13590. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13591. callback();
  13592. }
  13593. };
  13594. Database.isUASupportingBlobStorage = true;
  13595. Database.parseURL = function (url) {
  13596. var a = document.createElement('a');
  13597. a.href = url;
  13598. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13599. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13600. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13601. return absLocation;
  13602. };
  13603. Database.ReturnFullUrlLocation = function (url) {
  13604. if (url.indexOf("http:/") === -1) {
  13605. return (BABYLON.Database.parseURL(window.location.href) + url);
  13606. } else {
  13607. return url;
  13608. }
  13609. };
  13610. return Database;
  13611. })();
  13612. BABYLON.Database = Database;
  13613. })(BABYLON || (BABYLON = {}));
  13614. //# sourceMappingURL=babylon.database.js.map
  13615. var BABYLON;
  13616. (function (BABYLON) {
  13617. var SpriteManager = (function () {
  13618. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13619. this.name = name;
  13620. this.cellSize = cellSize;
  13621. this.sprites = new Array();
  13622. this.renderingGroupId = 0;
  13623. this.fogEnabled = true;
  13624. this._vertexDeclaration = [3, 4, 4, 4];
  13625. this._vertexStrideSize = 15 * 4;
  13626. this._capacity = capacity;
  13627. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13628. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13629. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13630. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13631. this._scene = scene;
  13632. this._scene.spriteManagers.push(this);
  13633. // VBO
  13634. this._vertexDeclaration = [3, 4, 4, 4];
  13635. this._vertexStrideSize = 15 * 4;
  13636. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13637. var indices = [];
  13638. var index = 0;
  13639. for (var count = 0; count < capacity; count++) {
  13640. indices.push(index);
  13641. indices.push(index + 1);
  13642. indices.push(index + 2);
  13643. indices.push(index);
  13644. indices.push(index + 2);
  13645. indices.push(index + 3);
  13646. index += 4;
  13647. }
  13648. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13649. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13650. // Effects
  13651. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13652. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13653. }
  13654. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13655. var arrayOffset = index * 15;
  13656. if (offsetX == 0)
  13657. offsetX = this._epsilon;
  13658. else if (offsetX == 1)
  13659. offsetX = 1 - this._epsilon;
  13660. if (offsetY == 0)
  13661. offsetY = this._epsilon;
  13662. else if (offsetY == 1)
  13663. offsetY = 1 - this._epsilon;
  13664. this._vertices[arrayOffset] = sprite.position.x;
  13665. this._vertices[arrayOffset + 1] = sprite.position.y;
  13666. this._vertices[arrayOffset + 2] = sprite.position.z;
  13667. this._vertices[arrayOffset + 3] = sprite.angle;
  13668. this._vertices[arrayOffset + 4] = sprite.size;
  13669. this._vertices[arrayOffset + 5] = offsetX;
  13670. this._vertices[arrayOffset + 6] = offsetY;
  13671. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13672. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13673. var offset = (sprite.cellIndex / rowSize) >> 0;
  13674. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13675. this._vertices[arrayOffset + 10] = offset;
  13676. // Color
  13677. this._vertices[arrayOffset + 11] = sprite.color.r;
  13678. this._vertices[arrayOffset + 12] = sprite.color.g;
  13679. this._vertices[arrayOffset + 13] = sprite.color.b;
  13680. this._vertices[arrayOffset + 14] = sprite.color.a;
  13681. };
  13682. SpriteManager.prototype.render = function () {
  13683. // Check
  13684. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13685. return;
  13686. var engine = this._scene.getEngine();
  13687. var baseSize = this._spriteTexture.getBaseSize();
  13688. // Sprites
  13689. var deltaTime = engine.getDeltaTime();
  13690. var max = Math.min(this._capacity, this.sprites.length);
  13691. var rowSize = baseSize.width / this.cellSize;
  13692. var offset = 0;
  13693. for (var index = 0; index < max; index++) {
  13694. var sprite = this.sprites[index];
  13695. if (!sprite) {
  13696. continue;
  13697. }
  13698. sprite._animate(deltaTime);
  13699. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13700. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13701. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13702. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13703. }
  13704. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13705. // Render
  13706. var effect = this._effectBase;
  13707. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13708. effect = this._effectFog;
  13709. }
  13710. engine.enableEffect(effect);
  13711. var viewMatrix = this._scene.getViewMatrix();
  13712. effect.setTexture("diffuseSampler", this._spriteTexture);
  13713. effect.setMatrix("view", viewMatrix);
  13714. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13715. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13716. // Fog
  13717. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13718. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13719. effect.setColor3("vFogColor", this._scene.fogColor);
  13720. }
  13721. // VBOs
  13722. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13723. // Draw order
  13724. effect.setBool("alphaTest", true);
  13725. engine.setColorWrite(false);
  13726. engine.draw(true, 0, max * 6);
  13727. engine.setColorWrite(true);
  13728. effect.setBool("alphaTest", false);
  13729. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13730. engine.draw(true, 0, max * 6);
  13731. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13732. };
  13733. SpriteManager.prototype.dispose = function () {
  13734. if (this._vertexBuffer) {
  13735. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13736. this._vertexBuffer = null;
  13737. }
  13738. if (this._indexBuffer) {
  13739. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13740. this._indexBuffer = null;
  13741. }
  13742. if (this._spriteTexture) {
  13743. this._spriteTexture.dispose();
  13744. this._spriteTexture = null;
  13745. }
  13746. // Remove from scene
  13747. var index = this._scene.spriteManagers.indexOf(this);
  13748. this._scene.spriteManagers.splice(index, 1);
  13749. // Callback
  13750. if (this.onDispose) {
  13751. this.onDispose();
  13752. }
  13753. };
  13754. return SpriteManager;
  13755. })();
  13756. BABYLON.SpriteManager = SpriteManager;
  13757. })(BABYLON || (BABYLON = {}));
  13758. //# sourceMappingURL=babylon.spriteManager.js.map
  13759. var BABYLON;
  13760. (function (BABYLON) {
  13761. var Sprite = (function () {
  13762. function Sprite(name, manager) {
  13763. this.name = name;
  13764. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13765. this.size = 1.0;
  13766. this.angle = 0;
  13767. this.cellIndex = 0;
  13768. this.invertU = 0;
  13769. this.invertV = 0;
  13770. this.animations = new Array();
  13771. this._animationStarted = false;
  13772. this._loopAnimation = false;
  13773. this._fromIndex = 0;
  13774. this._toIndex = 0;
  13775. this._delay = 0;
  13776. this._direction = 1;
  13777. this._frameCount = 0;
  13778. this._time = 0;
  13779. this._manager = manager;
  13780. this._manager.sprites.push(this);
  13781. this.position = BABYLON.Vector3.Zero();
  13782. }
  13783. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13784. this._fromIndex = from;
  13785. this._toIndex = to;
  13786. this._loopAnimation = loop;
  13787. this._delay = delay;
  13788. this._animationStarted = true;
  13789. this._direction = from < to ? 1 : -1;
  13790. this.cellIndex = from;
  13791. this._time = 0;
  13792. };
  13793. Sprite.prototype.stopAnimation = function () {
  13794. this._animationStarted = false;
  13795. };
  13796. Sprite.prototype._animate = function (deltaTime) {
  13797. if (!this._animationStarted)
  13798. return;
  13799. this._time += deltaTime;
  13800. if (this._time > this._delay) {
  13801. this._time = this._time % this._delay;
  13802. this.cellIndex += this._direction;
  13803. if (this.cellIndex == this._toIndex) {
  13804. if (this._loopAnimation) {
  13805. this.cellIndex = this._fromIndex;
  13806. } else {
  13807. this._animationStarted = false;
  13808. if (this.disposeWhenFinishedAnimating) {
  13809. this.dispose();
  13810. }
  13811. }
  13812. }
  13813. }
  13814. };
  13815. Sprite.prototype.dispose = function () {
  13816. for (var i = 0; i < this._manager.sprites.length; i++) {
  13817. if (this._manager.sprites[i] == this) {
  13818. this._manager.sprites.splice(i, 1);
  13819. }
  13820. }
  13821. };
  13822. return Sprite;
  13823. })();
  13824. BABYLON.Sprite = Sprite;
  13825. })(BABYLON || (BABYLON = {}));
  13826. //# sourceMappingURL=babylon.sprite.js.map
  13827. var BABYLON;
  13828. (function (BABYLON) {
  13829. var Layer = (function () {
  13830. function Layer(name, imgUrl, scene, isBackground, color) {
  13831. this.name = name;
  13832. this._vertexDeclaration = [2];
  13833. this._vertexStrideSize = 2 * 4;
  13834. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13835. this.isBackground = isBackground === undefined ? true : isBackground;
  13836. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13837. this._scene = scene;
  13838. this._scene.layers.push(this);
  13839. // VBO
  13840. var vertices = [];
  13841. vertices.push(1, 1);
  13842. vertices.push(-1, 1);
  13843. vertices.push(-1, -1);
  13844. vertices.push(1, -1);
  13845. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13846. // Indices
  13847. var indices = [];
  13848. indices.push(0);
  13849. indices.push(1);
  13850. indices.push(2);
  13851. indices.push(0);
  13852. indices.push(2);
  13853. indices.push(3);
  13854. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13855. // Effects
  13856. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13857. }
  13858. Layer.prototype.render = function () {
  13859. // Check
  13860. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13861. return;
  13862. var engine = this._scene.getEngine();
  13863. // Render
  13864. engine.enableEffect(this._effect);
  13865. engine.setState(false);
  13866. // Texture
  13867. this._effect.setTexture("textureSampler", this.texture);
  13868. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13869. // Color
  13870. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13871. // VBOs
  13872. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13873. // Draw order
  13874. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13875. engine.draw(true, 0, 6);
  13876. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13877. };
  13878. Layer.prototype.dispose = function () {
  13879. if (this._vertexBuffer) {
  13880. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13881. this._vertexBuffer = null;
  13882. }
  13883. if (this._indexBuffer) {
  13884. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13885. this._indexBuffer = null;
  13886. }
  13887. if (this.texture) {
  13888. this.texture.dispose();
  13889. this.texture = null;
  13890. }
  13891. // Remove from scene
  13892. var index = this._scene.layers.indexOf(this);
  13893. this._scene.layers.splice(index, 1);
  13894. // Callback
  13895. if (this.onDispose) {
  13896. this.onDispose();
  13897. }
  13898. };
  13899. return Layer;
  13900. })();
  13901. BABYLON.Layer = Layer;
  13902. })(BABYLON || (BABYLON = {}));
  13903. //# sourceMappingURL=babylon.layer.js.map
  13904. var BABYLON;
  13905. (function (BABYLON) {
  13906. var Particle = (function () {
  13907. function Particle() {
  13908. this.position = BABYLON.Vector3.Zero();
  13909. this.direction = BABYLON.Vector3.Zero();
  13910. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13911. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13912. this.lifeTime = 1.0;
  13913. this.age = 0;
  13914. this.size = 0;
  13915. this.angle = 0;
  13916. this.angularSpeed = 0;
  13917. }
  13918. return Particle;
  13919. })();
  13920. BABYLON.Particle = Particle;
  13921. })(BABYLON || (BABYLON = {}));
  13922. //# sourceMappingURL=babylon.particle.js.map
  13923. var BABYLON;
  13924. (function (BABYLON) {
  13925. var randomNumber = function (min, max) {
  13926. if (min === max) {
  13927. return (min);
  13928. }
  13929. var random = Math.random();
  13930. return ((random * (max - min)) + min);
  13931. };
  13932. var ParticleSystem = (function () {
  13933. function ParticleSystem(name, capacity, scene, customEffect) {
  13934. var _this = this;
  13935. this.name = name;
  13936. this.renderingGroupId = 0;
  13937. this.emitter = null;
  13938. this.emitRate = 10;
  13939. this.manualEmitCount = -1;
  13940. this.updateSpeed = 0.01;
  13941. this.targetStopDuration = 0;
  13942. this.disposeOnStop = false;
  13943. this.minEmitPower = 1;
  13944. this.maxEmitPower = 1;
  13945. this.minLifeTime = 1;
  13946. this.maxLifeTime = 1;
  13947. this.minSize = 1;
  13948. this.maxSize = 1;
  13949. this.minAngularSpeed = 0;
  13950. this.maxAngularSpeed = 0;
  13951. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13952. this.forceDepthWrite = false;
  13953. this.gravity = BABYLON.Vector3.Zero();
  13954. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13955. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13956. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13957. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13958. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13959. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13960. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13961. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13962. this.particles = new Array();
  13963. this._vertexDeclaration = [3, 4, 4];
  13964. this._vertexStrideSize = 11 * 4;
  13965. this._stockParticles = new Array();
  13966. this._newPartsExcess = 0;
  13967. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13968. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13969. this._scaledDirection = BABYLON.Vector3.Zero();
  13970. this._scaledGravity = BABYLON.Vector3.Zero();
  13971. this._currentRenderId = -1;
  13972. this._started = false;
  13973. this._stopped = false;
  13974. this._actualFrame = 0;
  13975. this.id = name;
  13976. this._capacity = capacity;
  13977. this._scene = scene;
  13978. this._customEffect = customEffect;
  13979. scene.particleSystems.push(this);
  13980. // VBO
  13981. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13982. var indices = [];
  13983. var index = 0;
  13984. for (var count = 0; count < capacity; count++) {
  13985. indices.push(index);
  13986. indices.push(index + 1);
  13987. indices.push(index + 2);
  13988. indices.push(index);
  13989. indices.push(index + 2);
  13990. indices.push(index + 3);
  13991. index += 4;
  13992. }
  13993. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13994. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13995. // Default behaviors
  13996. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13997. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13998. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13999. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14000. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14001. };
  14002. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14003. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14004. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14005. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14007. };
  14008. this.updateFunction = function (particles) {
  14009. for (var index = 0; index < particles.length; index++) {
  14010. var particle = particles[index];
  14011. particle.age += _this._scaledUpdateSpeed;
  14012. if (particle.age >= particle.lifeTime) {
  14013. particles.splice(index, 1);
  14014. _this._stockParticles.push(particle);
  14015. index--;
  14016. continue;
  14017. } else {
  14018. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14019. particle.color.addInPlace(_this._scaledColorStep);
  14020. if (particle.color.a < 0)
  14021. particle.color.a = 0;
  14022. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14023. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14024. particle.position.addInPlace(_this._scaledDirection);
  14025. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14026. particle.direction.addInPlace(_this._scaledGravity);
  14027. }
  14028. }
  14029. };
  14030. }
  14031. ParticleSystem.prototype.getCapacity = function () {
  14032. return this._capacity;
  14033. };
  14034. ParticleSystem.prototype.isAlive = function () {
  14035. return this._alive;
  14036. };
  14037. ParticleSystem.prototype.isStarted = function () {
  14038. return this._started;
  14039. };
  14040. ParticleSystem.prototype.start = function () {
  14041. this._started = true;
  14042. this._stopped = false;
  14043. this._actualFrame = 0;
  14044. };
  14045. ParticleSystem.prototype.stop = function () {
  14046. this._stopped = true;
  14047. };
  14048. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14049. var offset = index * 11;
  14050. this._vertices[offset] = particle.position.x;
  14051. this._vertices[offset + 1] = particle.position.y;
  14052. this._vertices[offset + 2] = particle.position.z;
  14053. this._vertices[offset + 3] = particle.color.r;
  14054. this._vertices[offset + 4] = particle.color.g;
  14055. this._vertices[offset + 5] = particle.color.b;
  14056. this._vertices[offset + 6] = particle.color.a;
  14057. this._vertices[offset + 7] = particle.angle;
  14058. this._vertices[offset + 8] = particle.size;
  14059. this._vertices[offset + 9] = offsetX;
  14060. this._vertices[offset + 10] = offsetY;
  14061. };
  14062. ParticleSystem.prototype._update = function (newParticles) {
  14063. // Update current
  14064. this._alive = this.particles.length > 0;
  14065. this.updateFunction(this.particles);
  14066. // Add new ones
  14067. var worldMatrix;
  14068. if (this.emitter.position) {
  14069. worldMatrix = this.emitter.getWorldMatrix();
  14070. } else {
  14071. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14072. }
  14073. for (var index = 0; index < newParticles; index++) {
  14074. if (this.particles.length === this._capacity) {
  14075. break;
  14076. }
  14077. if (this._stockParticles.length !== 0) {
  14078. var particle = this._stockParticles.pop();
  14079. particle.age = 0;
  14080. } else {
  14081. particle = new BABYLON.Particle();
  14082. }
  14083. this.particles.push(particle);
  14084. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14085. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14086. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14087. particle.size = randomNumber(this.minSize, this.maxSize);
  14088. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14089. this.startPositionFunction(worldMatrix, particle.position);
  14090. var step = randomNumber(0, 1.0);
  14091. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14092. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14093. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14094. }
  14095. };
  14096. ParticleSystem.prototype._getEffect = function () {
  14097. if (this._customEffect) {
  14098. return this._customEffect;
  14099. }
  14100. ;
  14101. var defines = [];
  14102. if (this._scene.clipPlane) {
  14103. defines.push("#define CLIPPLANE");
  14104. }
  14105. // Effect
  14106. var join = defines.join("\n");
  14107. if (this._cachedDefines !== join) {
  14108. this._cachedDefines = join;
  14109. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14110. }
  14111. return this._effect;
  14112. };
  14113. ParticleSystem.prototype.animate = function () {
  14114. if (!this._started)
  14115. return;
  14116. var effect = this._getEffect();
  14117. // Check
  14118. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14119. return;
  14120. if (this._currentRenderId === this._scene.getRenderId()) {
  14121. return;
  14122. }
  14123. this._currentRenderId = this._scene.getRenderId();
  14124. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14125. // determine the number of particles we need to create
  14126. var emitCout;
  14127. if (this.manualEmitCount > -1) {
  14128. emitCout = this.manualEmitCount;
  14129. this.manualEmitCount = 0;
  14130. } else {
  14131. emitCout = this.emitRate;
  14132. }
  14133. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14134. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14135. if (this._newPartsExcess > 1.0) {
  14136. newParticles += this._newPartsExcess >> 0;
  14137. this._newPartsExcess -= this._newPartsExcess >> 0;
  14138. }
  14139. this._alive = false;
  14140. if (!this._stopped) {
  14141. this._actualFrame += this._scaledUpdateSpeed;
  14142. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14143. this.stop();
  14144. } else {
  14145. newParticles = 0;
  14146. }
  14147. this._update(newParticles);
  14148. // Stopped?
  14149. if (this._stopped) {
  14150. if (!this._alive) {
  14151. this._started = false;
  14152. if (this.disposeOnStop) {
  14153. this._scene._toBeDisposed.push(this);
  14154. }
  14155. }
  14156. }
  14157. // Update VBO
  14158. var offset = 0;
  14159. for (var index = 0; index < this.particles.length; index++) {
  14160. var particle = this.particles[index];
  14161. this._appendParticleVertex(offset++, particle, 0, 0);
  14162. this._appendParticleVertex(offset++, particle, 1, 0);
  14163. this._appendParticleVertex(offset++, particle, 1, 1);
  14164. this._appendParticleVertex(offset++, particle, 0, 1);
  14165. }
  14166. var engine = this._scene.getEngine();
  14167. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14168. };
  14169. ParticleSystem.prototype.render = function () {
  14170. var effect = this._getEffect();
  14171. // Check
  14172. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14173. return 0;
  14174. var engine = this._scene.getEngine();
  14175. // Render
  14176. engine.enableEffect(effect);
  14177. engine.setState(false);
  14178. var viewMatrix = this._scene.getViewMatrix();
  14179. effect.setTexture("diffuseSampler", this.particleTexture);
  14180. effect.setMatrix("view", viewMatrix);
  14181. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14182. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14183. if (this._scene.clipPlane) {
  14184. var clipPlane = this._scene.clipPlane;
  14185. var invView = viewMatrix.clone();
  14186. invView.invert();
  14187. effect.setMatrix("invView", invView);
  14188. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14189. }
  14190. // VBOs
  14191. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14192. // Draw order
  14193. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14194. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14195. } else {
  14196. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14197. }
  14198. if (this.forceDepthWrite) {
  14199. engine.setDepthWrite(true);
  14200. }
  14201. engine.draw(true, 0, this.particles.length * 6);
  14202. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14203. return this.particles.length;
  14204. };
  14205. ParticleSystem.prototype.dispose = function () {
  14206. if (this._vertexBuffer) {
  14207. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14208. this._vertexBuffer = null;
  14209. }
  14210. if (this._indexBuffer) {
  14211. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14212. this._indexBuffer = null;
  14213. }
  14214. if (this.particleTexture) {
  14215. this.particleTexture.dispose();
  14216. this.particleTexture = null;
  14217. }
  14218. // Remove from scene
  14219. var index = this._scene.particleSystems.indexOf(this);
  14220. this._scene.particleSystems.splice(index, 1);
  14221. // Callback
  14222. if (this.onDispose) {
  14223. this.onDispose();
  14224. }
  14225. };
  14226. // Clone
  14227. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14228. var result = new ParticleSystem(name, this._capacity, this._scene);
  14229. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14230. if (newEmitter === undefined) {
  14231. newEmitter = this.emitter;
  14232. }
  14233. result.emitter = newEmitter;
  14234. if (this.particleTexture) {
  14235. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14236. }
  14237. result.start();
  14238. return result;
  14239. };
  14240. ParticleSystem.BLENDMODE_ONEONE = 0;
  14241. ParticleSystem.BLENDMODE_STANDARD = 1;
  14242. return ParticleSystem;
  14243. })();
  14244. BABYLON.ParticleSystem = ParticleSystem;
  14245. })(BABYLON || (BABYLON = {}));
  14246. //# sourceMappingURL=babylon.particleSystem.js.map
  14247. var BABYLON;
  14248. (function (BABYLON) {
  14249. var Animation = (function () {
  14250. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14251. this.name = name;
  14252. this.targetProperty = targetProperty;
  14253. this.framePerSecond = framePerSecond;
  14254. this.dataType = dataType;
  14255. this.loopMode = loopMode;
  14256. this._offsetsCache = {};
  14257. this._highLimitsCache = {};
  14258. this._stopped = false;
  14259. this.targetPropertyPath = targetProperty.split(".");
  14260. this.dataType = dataType;
  14261. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14262. }
  14263. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14264. var dataType = undefined;
  14265. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14266. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14267. } else if (from instanceof BABYLON.Quaternion) {
  14268. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14269. } else if (from instanceof BABYLON.Vector3) {
  14270. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14271. } else if (from instanceof BABYLON.Vector2) {
  14272. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14273. } else if (from instanceof BABYLON.Color3) {
  14274. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14275. }
  14276. if (dataType == undefined) {
  14277. return;
  14278. }
  14279. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14280. var keys = [];
  14281. keys.push({ frame: 0, value: from });
  14282. keys.push({ frame: totalFrame, value: to });
  14283. animation.setKeys(keys);
  14284. mesh.animations.push(animation);
  14285. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14286. };
  14287. // Methods
  14288. Animation.prototype.isStopped = function () {
  14289. return this._stopped;
  14290. };
  14291. Animation.prototype.getKeys = function () {
  14292. return this._keys;
  14293. };
  14294. Animation.prototype.getEasingFunction = function () {
  14295. return this._easingFunction;
  14296. };
  14297. Animation.prototype.setEasingFunction = function (easingFunction) {
  14298. this._easingFunction = easingFunction;
  14299. };
  14300. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14301. return startValue + (endValue - startValue) * gradient;
  14302. };
  14303. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14304. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14305. };
  14306. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14307. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14308. };
  14309. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14310. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14311. };
  14312. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14313. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14314. };
  14315. Animation.prototype.clone = function () {
  14316. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14317. clone.setKeys(this._keys);
  14318. return clone;
  14319. };
  14320. Animation.prototype.setKeys = function (values) {
  14321. this._keys = values.slice(0);
  14322. this._offsetsCache = {};
  14323. this._highLimitsCache = {};
  14324. };
  14325. Animation.prototype._getKeyValue = function (value) {
  14326. if (typeof value === "function") {
  14327. return value();
  14328. }
  14329. return value;
  14330. };
  14331. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14332. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14333. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14334. }
  14335. this.currentFrame = currentFrame;
  14336. for (var key = 0; key < this._keys.length; key++) {
  14337. // for each frame, we need the key just before the frame superior
  14338. if (this._keys[key + 1].frame >= currentFrame) {
  14339. var startValue = this._getKeyValue(this._keys[key].value);
  14340. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14341. // gradient : percent of currentFrame between the frame inf and the frame sup
  14342. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14343. // check for easingFunction and correction of gradient
  14344. if (this._easingFunction != null) {
  14345. gradient = this._easingFunction.ease(gradient);
  14346. }
  14347. switch (this.dataType) {
  14348. case Animation.ANIMATIONTYPE_FLOAT:
  14349. switch (loopMode) {
  14350. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14351. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14352. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14353. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14354. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14355. }
  14356. break;
  14357. case Animation.ANIMATIONTYPE_QUATERNION:
  14358. var quaternion = null;
  14359. switch (loopMode) {
  14360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14362. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14363. break;
  14364. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14365. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14366. break;
  14367. }
  14368. return quaternion;
  14369. case Animation.ANIMATIONTYPE_VECTOR3:
  14370. switch (loopMode) {
  14371. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14372. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14373. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14374. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14375. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14376. }
  14377. case Animation.ANIMATIONTYPE_VECTOR2:
  14378. switch (loopMode) {
  14379. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14380. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14381. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14382. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14383. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14384. }
  14385. case Animation.ANIMATIONTYPE_COLOR3:
  14386. switch (loopMode) {
  14387. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14388. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14389. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14390. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14391. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14392. }
  14393. case Animation.ANIMATIONTYPE_MATRIX:
  14394. switch (loopMode) {
  14395. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14396. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14397. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14398. return startValue;
  14399. }
  14400. default:
  14401. break;
  14402. }
  14403. break;
  14404. }
  14405. }
  14406. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14407. };
  14408. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14409. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14410. this._stopped = true;
  14411. return false;
  14412. }
  14413. var returnValue = true;
  14414. // Adding a start key at frame 0 if missing
  14415. if (this._keys[0].frame !== 0) {
  14416. var newKey = { frame: 0, value: this._keys[0].value };
  14417. this._keys.splice(0, 0, newKey);
  14418. }
  14419. // Check limits
  14420. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14421. from = this._keys[0].frame;
  14422. }
  14423. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14424. to = this._keys[this._keys.length - 1].frame;
  14425. }
  14426. // Compute ratio
  14427. var range = to - from;
  14428. var offsetValue;
  14429. // ratio represents the frame delta between from and to
  14430. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14431. var highLimitValue = 0;
  14432. if (ratio > range && !loop) {
  14433. returnValue = false;
  14434. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14435. } else {
  14436. // Get max value if required
  14437. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14438. var keyOffset = to.toString() + from.toString();
  14439. if (!this._offsetsCache[keyOffset]) {
  14440. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14441. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14442. switch (this.dataType) {
  14443. case Animation.ANIMATIONTYPE_FLOAT:
  14444. this._offsetsCache[keyOffset] = toValue - fromValue;
  14445. break;
  14446. case Animation.ANIMATIONTYPE_QUATERNION:
  14447. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14448. break;
  14449. case Animation.ANIMATIONTYPE_VECTOR3:
  14450. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14451. case Animation.ANIMATIONTYPE_VECTOR2:
  14452. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14453. case Animation.ANIMATIONTYPE_COLOR3:
  14454. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14455. default:
  14456. break;
  14457. }
  14458. this._highLimitsCache[keyOffset] = toValue;
  14459. }
  14460. highLimitValue = this._highLimitsCache[keyOffset];
  14461. offsetValue = this._offsetsCache[keyOffset];
  14462. }
  14463. }
  14464. if (offsetValue === undefined) {
  14465. switch (this.dataType) {
  14466. case Animation.ANIMATIONTYPE_FLOAT:
  14467. offsetValue = 0;
  14468. break;
  14469. case Animation.ANIMATIONTYPE_QUATERNION:
  14470. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14471. break;
  14472. case Animation.ANIMATIONTYPE_VECTOR3:
  14473. offsetValue = BABYLON.Vector3.Zero();
  14474. break;
  14475. case Animation.ANIMATIONTYPE_VECTOR2:
  14476. offsetValue = BABYLON.Vector2.Zero();
  14477. break;
  14478. case Animation.ANIMATIONTYPE_COLOR3:
  14479. offsetValue = BABYLON.Color3.Black();
  14480. }
  14481. }
  14482. // Compute value
  14483. var repeatCount = (ratio / range) >> 0;
  14484. var currentFrame = returnValue ? from + ratio % range : to;
  14485. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14486. // Set value
  14487. if (this.targetPropertyPath.length > 1) {
  14488. var property = this._target[this.targetPropertyPath[0]];
  14489. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14490. property = property[this.targetPropertyPath[index]];
  14491. }
  14492. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14493. } else {
  14494. this._target[this.targetPropertyPath[0]] = currentValue;
  14495. }
  14496. if (this._target.markAsDirty) {
  14497. this._target.markAsDirty(this.targetProperty);
  14498. }
  14499. if (!returnValue) {
  14500. this._stopped = true;
  14501. }
  14502. return returnValue;
  14503. };
  14504. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14505. get: function () {
  14506. return Animation._ANIMATIONTYPE_FLOAT;
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14512. get: function () {
  14513. return Animation._ANIMATIONTYPE_VECTOR3;
  14514. },
  14515. enumerable: true,
  14516. configurable: true
  14517. });
  14518. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14519. get: function () {
  14520. return Animation._ANIMATIONTYPE_VECTOR2;
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14526. get: function () {
  14527. return Animation._ANIMATIONTYPE_QUATERNION;
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14533. get: function () {
  14534. return Animation._ANIMATIONTYPE_MATRIX;
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14540. get: function () {
  14541. return Animation._ANIMATIONTYPE_COLOR3;
  14542. },
  14543. enumerable: true,
  14544. configurable: true
  14545. });
  14546. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14547. get: function () {
  14548. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14549. },
  14550. enumerable: true,
  14551. configurable: true
  14552. });
  14553. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14554. get: function () {
  14555. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14556. },
  14557. enumerable: true,
  14558. configurable: true
  14559. });
  14560. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14561. get: function () {
  14562. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Animation._ANIMATIONTYPE_FLOAT = 0;
  14568. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14569. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14570. Animation._ANIMATIONTYPE_MATRIX = 3;
  14571. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14572. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14573. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14574. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14575. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14576. return Animation;
  14577. })();
  14578. BABYLON.Animation = Animation;
  14579. })(BABYLON || (BABYLON = {}));
  14580. //# sourceMappingURL=babylon.animation.js.map
  14581. var BABYLON;
  14582. (function (BABYLON) {
  14583. var Animatable = (function () {
  14584. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14585. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14586. if (typeof toFrame === "undefined") { toFrame = 100; }
  14587. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14588. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14589. this.target = target;
  14590. this.fromFrame = fromFrame;
  14591. this.toFrame = toFrame;
  14592. this.loopAnimation = loopAnimation;
  14593. this.speedRatio = speedRatio;
  14594. this.onAnimationEnd = onAnimationEnd;
  14595. this._animations = new Array();
  14596. this._paused = false;
  14597. this.animationStarted = false;
  14598. if (animations) {
  14599. this.appendAnimations(target, animations);
  14600. }
  14601. this._scene = scene;
  14602. scene._activeAnimatables.push(this);
  14603. }
  14604. // Methods
  14605. Animatable.prototype.appendAnimations = function (target, animations) {
  14606. for (var index = 0; index < animations.length; index++) {
  14607. var animation = animations[index];
  14608. animation._target = target;
  14609. this._animations.push(animation);
  14610. }
  14611. };
  14612. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14613. var animations = this._animations;
  14614. for (var index = 0; index < animations.length; index++) {
  14615. if (animations[index].targetProperty === property) {
  14616. return animations[index];
  14617. }
  14618. }
  14619. return null;
  14620. };
  14621. Animatable.prototype.pause = function () {
  14622. if (this._paused) {
  14623. return;
  14624. }
  14625. this._paused = true;
  14626. };
  14627. Animatable.prototype.restart = function () {
  14628. this._paused = false;
  14629. };
  14630. Animatable.prototype.stop = function () {
  14631. var index = this._scene._activeAnimatables.indexOf(this);
  14632. if (index > -1) {
  14633. this._scene._activeAnimatables.splice(index, 1);
  14634. }
  14635. if (this.onAnimationEnd) {
  14636. this.onAnimationEnd();
  14637. }
  14638. };
  14639. Animatable.prototype._animate = function (delay) {
  14640. if (this._paused) {
  14641. if (!this._pausedDelay) {
  14642. this._pausedDelay = delay;
  14643. }
  14644. return true;
  14645. }
  14646. if (!this._localDelayOffset) {
  14647. this._localDelayOffset = delay;
  14648. } else if (this._pausedDelay) {
  14649. this._localDelayOffset += delay - this._pausedDelay;
  14650. this._pausedDelay = null;
  14651. }
  14652. // Animating
  14653. var running = false;
  14654. var animations = this._animations;
  14655. for (var index = 0; index < animations.length; index++) {
  14656. var animation = animations[index];
  14657. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14658. running = running || isRunning;
  14659. }
  14660. if (!running && this.onAnimationEnd) {
  14661. this.onAnimationEnd();
  14662. }
  14663. return running;
  14664. };
  14665. return Animatable;
  14666. })();
  14667. BABYLON.Animatable = Animatable;
  14668. })(BABYLON || (BABYLON = {}));
  14669. //# sourceMappingURL=babylon.animatable.js.map
  14670. var BABYLON;
  14671. (function (BABYLON) {
  14672. var EasingFunction = (function () {
  14673. function EasingFunction() {
  14674. // Properties
  14675. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14676. }
  14677. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14678. get: function () {
  14679. return EasingFunction._EASINGMODE_EASEIN;
  14680. },
  14681. enumerable: true,
  14682. configurable: true
  14683. });
  14684. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14685. get: function () {
  14686. return EasingFunction._EASINGMODE_EASEOUT;
  14687. },
  14688. enumerable: true,
  14689. configurable: true
  14690. });
  14691. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14692. get: function () {
  14693. return EasingFunction._EASINGMODE_EASEINOUT;
  14694. },
  14695. enumerable: true,
  14696. configurable: true
  14697. });
  14698. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14699. var n = Math.min(Math.max(easingMode, 0), 2);
  14700. this._easingMode = n;
  14701. };
  14702. EasingFunction.prototype.getEasingMode = function () {
  14703. return this._easingMode;
  14704. };
  14705. EasingFunction.prototype.easeInCore = function (gradient) {
  14706. throw new Error('You must implement this method');
  14707. };
  14708. EasingFunction.prototype.ease = function (gradient) {
  14709. switch (this._easingMode) {
  14710. case EasingFunction.EASINGMODE_EASEIN:
  14711. return this.easeInCore(gradient);
  14712. case EasingFunction.EASINGMODE_EASEOUT:
  14713. return (1 - this.easeInCore(1 - gradient));
  14714. }
  14715. if (gradient >= 0.5) {
  14716. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14717. }
  14718. return (this.easeInCore(gradient * 2) * 0.5);
  14719. };
  14720. EasingFunction._EASINGMODE_EASEIN = 0;
  14721. EasingFunction._EASINGMODE_EASEOUT = 1;
  14722. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14723. return EasingFunction;
  14724. })();
  14725. BABYLON.EasingFunction = EasingFunction;
  14726. var CircleEase = (function (_super) {
  14727. __extends(CircleEase, _super);
  14728. function CircleEase() {
  14729. _super.apply(this, arguments);
  14730. }
  14731. CircleEase.prototype.easeInCore = function (gradient) {
  14732. gradient = Math.max(0, Math.min(1, gradient));
  14733. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14734. };
  14735. return CircleEase;
  14736. })(EasingFunction);
  14737. BABYLON.CircleEase = CircleEase;
  14738. var BackEase = (function (_super) {
  14739. __extends(BackEase, _super);
  14740. function BackEase(amplitude) {
  14741. if (typeof amplitude === "undefined") { amplitude = 1; }
  14742. _super.call(this);
  14743. this.amplitude = amplitude;
  14744. }
  14745. BackEase.prototype.easeInCore = function (gradient) {
  14746. var num = Math.max(0, this.amplitude);
  14747. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14748. };
  14749. return BackEase;
  14750. })(EasingFunction);
  14751. BABYLON.BackEase = BackEase;
  14752. var BounceEase = (function (_super) {
  14753. __extends(BounceEase, _super);
  14754. function BounceEase(bounces, bounciness) {
  14755. if (typeof bounces === "undefined") { bounces = 3; }
  14756. if (typeof bounciness === "undefined") { bounciness = 2; }
  14757. _super.call(this);
  14758. this.bounces = bounces;
  14759. this.bounciness = bounciness;
  14760. }
  14761. BounceEase.prototype.easeInCore = function (gradient) {
  14762. var y = Math.max(0.0, this.bounces);
  14763. var bounciness = this.bounciness;
  14764. if (bounciness <= 1.0) {
  14765. bounciness = 1.001;
  14766. }
  14767. var num9 = Math.pow(bounciness, y);
  14768. var num5 = 1.0 - bounciness;
  14769. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14770. var num15 = gradient * num4;
  14771. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14772. var num3 = Math.floor(num65);
  14773. var num13 = num3 + 1.0;
  14774. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14775. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14776. var num7 = (num8 + num12) * 0.5;
  14777. var num6 = gradient - num7;
  14778. var num2 = num7 - num8;
  14779. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14780. };
  14781. return BounceEase;
  14782. })(EasingFunction);
  14783. BABYLON.BounceEase = BounceEase;
  14784. var CubicEase = (function (_super) {
  14785. __extends(CubicEase, _super);
  14786. function CubicEase() {
  14787. _super.apply(this, arguments);
  14788. }
  14789. CubicEase.prototype.easeInCore = function (gradient) {
  14790. return (gradient * gradient * gradient);
  14791. };
  14792. return CubicEase;
  14793. })(EasingFunction);
  14794. BABYLON.CubicEase = CubicEase;
  14795. var ElasticEase = (function (_super) {
  14796. __extends(ElasticEase, _super);
  14797. function ElasticEase(oscillations, springiness) {
  14798. if (typeof oscillations === "undefined") { oscillations = 3; }
  14799. if (typeof springiness === "undefined") { springiness = 3; }
  14800. _super.call(this);
  14801. this.oscillations = oscillations;
  14802. this.springiness = springiness;
  14803. }
  14804. ElasticEase.prototype.easeInCore = function (gradient) {
  14805. var num2;
  14806. var num3 = Math.max(0.0, this.oscillations);
  14807. var num = Math.max(0.0, this.springiness);
  14808. if (num == 0) {
  14809. num2 = gradient;
  14810. } else {
  14811. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14812. }
  14813. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14814. };
  14815. return ElasticEase;
  14816. })(EasingFunction);
  14817. BABYLON.ElasticEase = ElasticEase;
  14818. var ExponentialEase = (function (_super) {
  14819. __extends(ExponentialEase, _super);
  14820. function ExponentialEase(exponent) {
  14821. if (typeof exponent === "undefined") { exponent = 2; }
  14822. _super.call(this);
  14823. this.exponent = exponent;
  14824. }
  14825. ExponentialEase.prototype.easeInCore = function (gradient) {
  14826. if (this.exponent <= 0) {
  14827. return gradient;
  14828. }
  14829. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14830. };
  14831. return ExponentialEase;
  14832. })(EasingFunction);
  14833. BABYLON.ExponentialEase = ExponentialEase;
  14834. var PowerEase = (function (_super) {
  14835. __extends(PowerEase, _super);
  14836. function PowerEase(power) {
  14837. if (typeof power === "undefined") { power = 2; }
  14838. _super.call(this);
  14839. this.power = power;
  14840. }
  14841. PowerEase.prototype.easeInCore = function (gradient) {
  14842. var y = Math.max(0.0, this.power);
  14843. return Math.pow(gradient, y);
  14844. };
  14845. return PowerEase;
  14846. })(EasingFunction);
  14847. BABYLON.PowerEase = PowerEase;
  14848. var QuadraticEase = (function (_super) {
  14849. __extends(QuadraticEase, _super);
  14850. function QuadraticEase() {
  14851. _super.apply(this, arguments);
  14852. }
  14853. QuadraticEase.prototype.easeInCore = function (gradient) {
  14854. return (gradient * gradient);
  14855. };
  14856. return QuadraticEase;
  14857. })(EasingFunction);
  14858. BABYLON.QuadraticEase = QuadraticEase;
  14859. var QuarticEase = (function (_super) {
  14860. __extends(QuarticEase, _super);
  14861. function QuarticEase() {
  14862. _super.apply(this, arguments);
  14863. }
  14864. QuarticEase.prototype.easeInCore = function (gradient) {
  14865. return (gradient * gradient * gradient * gradient);
  14866. };
  14867. return QuarticEase;
  14868. })(EasingFunction);
  14869. BABYLON.QuarticEase = QuarticEase;
  14870. var QuinticEase = (function (_super) {
  14871. __extends(QuinticEase, _super);
  14872. function QuinticEase() {
  14873. _super.apply(this, arguments);
  14874. }
  14875. QuinticEase.prototype.easeInCore = function (gradient) {
  14876. return (gradient * gradient * gradient * gradient * gradient);
  14877. };
  14878. return QuinticEase;
  14879. })(EasingFunction);
  14880. BABYLON.QuinticEase = QuinticEase;
  14881. var SineEase = (function (_super) {
  14882. __extends(SineEase, _super);
  14883. function SineEase() {
  14884. _super.apply(this, arguments);
  14885. }
  14886. SineEase.prototype.easeInCore = function (gradient) {
  14887. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14888. };
  14889. return SineEase;
  14890. })(EasingFunction);
  14891. BABYLON.SineEase = SineEase;
  14892. var BezierCurveEase = (function (_super) {
  14893. __extends(BezierCurveEase, _super);
  14894. function BezierCurveEase(x1, y1, x2, y2) {
  14895. if (typeof x1 === "undefined") { x1 = 0; }
  14896. if (typeof y1 === "undefined") { y1 = 0; }
  14897. if (typeof x2 === "undefined") { x2 = 1; }
  14898. if (typeof y2 === "undefined") { y2 = 1; }
  14899. _super.call(this);
  14900. this.x1 = x1;
  14901. this.y1 = y1;
  14902. this.x2 = x2;
  14903. this.y2 = y2;
  14904. }
  14905. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14906. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14907. };
  14908. return BezierCurveEase;
  14909. })(EasingFunction);
  14910. BABYLON.BezierCurveEase = BezierCurveEase;
  14911. })(BABYLON || (BABYLON = {}));
  14912. //# sourceMappingURL=babylon.easing.js.map
  14913. var BABYLON;
  14914. (function (BABYLON) {
  14915. var Octree = (function () {
  14916. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14917. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14918. this.maxDepth = maxDepth;
  14919. this.dynamicContent = new Array();
  14920. this._maxBlockCapacity = maxBlockCapacity || 64;
  14921. this._selectionContent = new BABYLON.SmartArray(1024);
  14922. this._creationFunc = creationFunc;
  14923. }
  14924. // Methods
  14925. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14926. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14927. };
  14928. Octree.prototype.addMesh = function (entry) {
  14929. for (var index = 0; index < this.blocks.length; index++) {
  14930. var block = this.blocks[index];
  14931. block.addEntry(entry);
  14932. }
  14933. };
  14934. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14935. this._selectionContent.reset();
  14936. for (var index = 0; index < this.blocks.length; index++) {
  14937. var block = this.blocks[index];
  14938. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14939. }
  14940. if (allowDuplicate) {
  14941. this._selectionContent.concat(this.dynamicContent);
  14942. } else {
  14943. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14944. }
  14945. return this._selectionContent;
  14946. };
  14947. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14948. this._selectionContent.reset();
  14949. for (var index = 0; index < this.blocks.length; index++) {
  14950. var block = this.blocks[index];
  14951. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14952. }
  14953. if (allowDuplicate) {
  14954. this._selectionContent.concat(this.dynamicContent);
  14955. } else {
  14956. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14957. }
  14958. return this._selectionContent;
  14959. };
  14960. Octree.prototype.intersectsRay = function (ray) {
  14961. this._selectionContent.reset();
  14962. for (var index = 0; index < this.blocks.length; index++) {
  14963. var block = this.blocks[index];
  14964. block.intersectsRay(ray, this._selectionContent);
  14965. }
  14966. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14967. return this._selectionContent;
  14968. };
  14969. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14970. target.blocks = new Array();
  14971. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14972. for (var x = 0; x < 2; x++) {
  14973. for (var y = 0; y < 2; y++) {
  14974. for (var z = 0; z < 2; z++) {
  14975. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14976. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14977. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14978. block.addEntries(entries);
  14979. target.blocks.push(block);
  14980. }
  14981. }
  14982. }
  14983. };
  14984. Octree.CreationFuncForMeshes = function (entry, block) {
  14985. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14986. block.entries.push(entry);
  14987. }
  14988. };
  14989. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14990. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14991. block.entries.push(entry);
  14992. }
  14993. };
  14994. return Octree;
  14995. })();
  14996. BABYLON.Octree = Octree;
  14997. })(BABYLON || (BABYLON = {}));
  14998. //# sourceMappingURL=babylon.octree.js.map
  14999. var BABYLON;
  15000. (function (BABYLON) {
  15001. var OctreeBlock = (function () {
  15002. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15003. this.entries = new Array();
  15004. this._boundingVectors = new Array();
  15005. this._capacity = capacity;
  15006. this._depth = depth;
  15007. this._maxDepth = maxDepth;
  15008. this._creationFunc = creationFunc;
  15009. this._minPoint = minPoint;
  15010. this._maxPoint = maxPoint;
  15011. this._boundingVectors.push(minPoint.clone());
  15012. this._boundingVectors.push(maxPoint.clone());
  15013. this._boundingVectors.push(minPoint.clone());
  15014. this._boundingVectors[2].x = maxPoint.x;
  15015. this._boundingVectors.push(minPoint.clone());
  15016. this._boundingVectors[3].y = maxPoint.y;
  15017. this._boundingVectors.push(minPoint.clone());
  15018. this._boundingVectors[4].z = maxPoint.z;
  15019. this._boundingVectors.push(maxPoint.clone());
  15020. this._boundingVectors[5].z = minPoint.z;
  15021. this._boundingVectors.push(maxPoint.clone());
  15022. this._boundingVectors[6].x = minPoint.x;
  15023. this._boundingVectors.push(maxPoint.clone());
  15024. this._boundingVectors[7].y = minPoint.y;
  15025. }
  15026. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15027. // Property
  15028. get: function () {
  15029. return this._capacity;
  15030. },
  15031. enumerable: true,
  15032. configurable: true
  15033. });
  15034. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15035. get: function () {
  15036. return this._minPoint;
  15037. },
  15038. enumerable: true,
  15039. configurable: true
  15040. });
  15041. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15042. get: function () {
  15043. return this._maxPoint;
  15044. },
  15045. enumerable: true,
  15046. configurable: true
  15047. });
  15048. // Methods
  15049. OctreeBlock.prototype.addEntry = function (entry) {
  15050. if (this.blocks) {
  15051. for (var index = 0; index < this.blocks.length; index++) {
  15052. var block = this.blocks[index];
  15053. block.addEntry(entry);
  15054. }
  15055. return;
  15056. }
  15057. this._creationFunc(entry, this);
  15058. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15059. this.createInnerBlocks();
  15060. }
  15061. };
  15062. OctreeBlock.prototype.addEntries = function (entries) {
  15063. for (var index = 0; index < entries.length; index++) {
  15064. var mesh = entries[index];
  15065. this.addEntry(mesh);
  15066. }
  15067. };
  15068. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15069. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15070. if (this.blocks) {
  15071. for (var index = 0; index < this.blocks.length; index++) {
  15072. var block = this.blocks[index];
  15073. block.select(frustumPlanes, selection, allowDuplicate);
  15074. }
  15075. return;
  15076. }
  15077. if (allowDuplicate) {
  15078. selection.concat(this.entries);
  15079. } else {
  15080. selection.concatWithNoDuplicate(this.entries);
  15081. }
  15082. }
  15083. };
  15084. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15085. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15086. if (this.blocks) {
  15087. for (var index = 0; index < this.blocks.length; index++) {
  15088. var block = this.blocks[index];
  15089. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15090. }
  15091. return;
  15092. }
  15093. if (allowDuplicate) {
  15094. selection.concat(this.entries);
  15095. } else {
  15096. selection.concatWithNoDuplicate(this.entries);
  15097. }
  15098. }
  15099. };
  15100. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15101. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15102. if (this.blocks) {
  15103. for (var index = 0; index < this.blocks.length; index++) {
  15104. var block = this.blocks[index];
  15105. block.intersectsRay(ray, selection);
  15106. }
  15107. return;
  15108. }
  15109. selection.concatWithNoDuplicate(this.entries);
  15110. }
  15111. };
  15112. OctreeBlock.prototype.createInnerBlocks = function () {
  15113. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15114. };
  15115. return OctreeBlock;
  15116. })();
  15117. BABYLON.OctreeBlock = OctreeBlock;
  15118. })(BABYLON || (BABYLON = {}));
  15119. //# sourceMappingURL=babylon.octreeBlock.js.map
  15120. var BABYLON;
  15121. (function (BABYLON) {
  15122. var Bone = (function () {
  15123. function Bone(name, skeleton, parentBone, matrix) {
  15124. this.name = name;
  15125. this.children = new Array();
  15126. this.animations = new Array();
  15127. this._worldTransform = new BABYLON.Matrix();
  15128. this._absoluteTransform = new BABYLON.Matrix();
  15129. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15130. this._skeleton = skeleton;
  15131. this._matrix = matrix;
  15132. this._baseMatrix = matrix;
  15133. skeleton.bones.push(this);
  15134. if (parentBone) {
  15135. this._parent = parentBone;
  15136. parentBone.children.push(this);
  15137. } else {
  15138. this._parent = null;
  15139. }
  15140. this._updateDifferenceMatrix();
  15141. }
  15142. // Members
  15143. Bone.prototype.getParent = function () {
  15144. return this._parent;
  15145. };
  15146. Bone.prototype.getLocalMatrix = function () {
  15147. return this._matrix;
  15148. };
  15149. Bone.prototype.getBaseMatrix = function () {
  15150. return this._baseMatrix;
  15151. };
  15152. Bone.prototype.getWorldMatrix = function () {
  15153. return this._worldTransform;
  15154. };
  15155. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15156. return this._invertedAbsoluteTransform;
  15157. };
  15158. Bone.prototype.getAbsoluteMatrix = function () {
  15159. var matrix = this._matrix.clone();
  15160. var parent = this._parent;
  15161. while (parent) {
  15162. matrix = matrix.multiply(parent.getLocalMatrix());
  15163. parent = parent.getParent();
  15164. }
  15165. return matrix;
  15166. };
  15167. // Methods
  15168. Bone.prototype.updateMatrix = function (matrix) {
  15169. this._matrix = matrix;
  15170. this._skeleton._markAsDirty();
  15171. this._updateDifferenceMatrix();
  15172. };
  15173. Bone.prototype._updateDifferenceMatrix = function () {
  15174. if (this._parent) {
  15175. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15176. } else {
  15177. this._absoluteTransform.copyFrom(this._matrix);
  15178. }
  15179. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15180. for (var index = 0; index < this.children.length; index++) {
  15181. this.children[index]._updateDifferenceMatrix();
  15182. }
  15183. };
  15184. Bone.prototype.markAsDirty = function () {
  15185. this._skeleton._markAsDirty();
  15186. };
  15187. return Bone;
  15188. })();
  15189. BABYLON.Bone = Bone;
  15190. })(BABYLON || (BABYLON = {}));
  15191. //# sourceMappingURL=babylon.bone.js.map
  15192. var BABYLON;
  15193. (function (BABYLON) {
  15194. var Skeleton = (function () {
  15195. function Skeleton(name, id, scene) {
  15196. this.name = name;
  15197. this.id = id;
  15198. this.bones = new Array();
  15199. this._isDirty = true;
  15200. this._identity = BABYLON.Matrix.Identity();
  15201. this.bones = [];
  15202. this._scene = scene;
  15203. scene.skeletons.push(this);
  15204. }
  15205. // Members
  15206. Skeleton.prototype.getTransformMatrices = function () {
  15207. return this._transformMatrices;
  15208. };
  15209. // Methods
  15210. Skeleton.prototype._markAsDirty = function () {
  15211. this._isDirty = true;
  15212. };
  15213. Skeleton.prototype.prepare = function () {
  15214. if (!this._isDirty) {
  15215. return;
  15216. }
  15217. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15218. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15219. }
  15220. for (var index = 0; index < this.bones.length; index++) {
  15221. var bone = this.bones[index];
  15222. var parentBone = bone.getParent();
  15223. if (parentBone) {
  15224. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15225. } else {
  15226. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15227. }
  15228. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15229. }
  15230. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15231. this._isDirty = false;
  15232. };
  15233. Skeleton.prototype.getAnimatables = function () {
  15234. if (!this._animatables || this._animatables.length != this.bones.length) {
  15235. this._animatables = [];
  15236. for (var index = 0; index < this.bones.length; index++) {
  15237. this._animatables.push(this.bones[index]);
  15238. }
  15239. }
  15240. return this._animatables;
  15241. };
  15242. Skeleton.prototype.clone = function (name, id) {
  15243. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15244. for (var index = 0; index < this.bones.length; index++) {
  15245. var source = this.bones[index];
  15246. var parentBone = null;
  15247. if (source.getParent()) {
  15248. var parentIndex = this.bones.indexOf(source.getParent());
  15249. parentBone = result.bones[parentIndex];
  15250. }
  15251. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15252. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15253. }
  15254. return result;
  15255. };
  15256. return Skeleton;
  15257. })();
  15258. BABYLON.Skeleton = Skeleton;
  15259. })(BABYLON || (BABYLON = {}));
  15260. //# sourceMappingURL=babylon.skeleton.js.map
  15261. var BABYLON;
  15262. (function (BABYLON) {
  15263. var PostProcess = (function () {
  15264. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15265. this.name = name;
  15266. this.width = -1;
  15267. this.height = -1;
  15268. this._reusable = false;
  15269. this._textures = new BABYLON.SmartArray(2);
  15270. this._currentRenderTextureInd = 0;
  15271. if (camera != null) {
  15272. this._camera = camera;
  15273. this._scene = camera.getScene();
  15274. camera.attachPostProcess(this);
  15275. this._engine = this._scene.getEngine();
  15276. } else {
  15277. this._engine = engine;
  15278. }
  15279. this._renderRatio = ratio;
  15280. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15281. this._reusable = reusable || false;
  15282. samplers = samplers || [];
  15283. samplers.push("textureSampler");
  15284. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15285. }
  15286. PostProcess.prototype.isReusable = function () {
  15287. return this._reusable;
  15288. };
  15289. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15290. camera = camera || this._camera;
  15291. var scene = camera.getScene();
  15292. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15293. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15294. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15295. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15296. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15297. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15298. if (this._textures.length > 0) {
  15299. for (var i = 0; i < this._textures.length; i++) {
  15300. this._engine._releaseTexture(this._textures.data[i]);
  15301. }
  15302. this._textures.reset();
  15303. }
  15304. this.width = desiredWidth;
  15305. this.height = desiredHeight;
  15306. 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 }));
  15307. if (this._reusable) {
  15308. 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 }));
  15309. }
  15310. if (this.onSizeChanged) {
  15311. this.onSizeChanged();
  15312. }
  15313. }
  15314. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15315. if (this.onActivate) {
  15316. this.onActivate(camera);
  15317. }
  15318. // Clear
  15319. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15320. if (this._reusable) {
  15321. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15322. }
  15323. };
  15324. PostProcess.prototype.apply = function () {
  15325. // Check
  15326. if (!this._effect.isReady())
  15327. return null;
  15328. // States
  15329. this._engine.enableEffect(this._effect);
  15330. this._engine.setState(false);
  15331. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15332. this._engine.setDepthBuffer(false);
  15333. this._engine.setDepthWrite(false);
  15334. // Texture
  15335. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15336. // Parameters
  15337. if (this.onApply) {
  15338. this.onApply(this._effect);
  15339. }
  15340. return this._effect;
  15341. };
  15342. PostProcess.prototype.dispose = function (camera) {
  15343. camera = camera || this._camera;
  15344. if (this._textures.length > 0) {
  15345. for (var i = 0; i < this._textures.length; i++) {
  15346. this._engine._releaseTexture(this._textures.data[i]);
  15347. }
  15348. this._textures.reset();
  15349. }
  15350. camera.detachPostProcess(this);
  15351. var index = camera._postProcesses.indexOf(this);
  15352. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15353. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15354. }
  15355. };
  15356. return PostProcess;
  15357. })();
  15358. BABYLON.PostProcess = PostProcess;
  15359. })(BABYLON || (BABYLON = {}));
  15360. //# sourceMappingURL=babylon.postProcess.js.map
  15361. var BABYLON;
  15362. (function (BABYLON) {
  15363. var PostProcessManager = (function () {
  15364. function PostProcessManager(scene) {
  15365. this._vertexDeclaration = [2];
  15366. this._vertexStrideSize = 2 * 4;
  15367. this._scene = scene;
  15368. // VBO
  15369. var vertices = [];
  15370. vertices.push(1, 1);
  15371. vertices.push(-1, 1);
  15372. vertices.push(-1, -1);
  15373. vertices.push(1, -1);
  15374. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15375. // Indices
  15376. var indices = [];
  15377. indices.push(0);
  15378. indices.push(1);
  15379. indices.push(2);
  15380. indices.push(0);
  15381. indices.push(2);
  15382. indices.push(3);
  15383. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15384. }
  15385. // Methods
  15386. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15387. var postProcesses = this._scene.activeCamera._postProcesses;
  15388. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15389. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15390. return false;
  15391. }
  15392. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15393. return true;
  15394. };
  15395. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15396. var postProcesses = this._scene.activeCamera._postProcesses;
  15397. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15398. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15399. return;
  15400. }
  15401. var engine = this._scene.getEngine();
  15402. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15403. if (index < postProcessesTakenIndices.length - 1) {
  15404. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15405. } else {
  15406. if (targetTexture) {
  15407. engine.bindFramebuffer(targetTexture);
  15408. } else {
  15409. engine.restoreDefaultFramebuffer();
  15410. }
  15411. }
  15412. if (doNotPresent) {
  15413. break;
  15414. }
  15415. var pp = postProcesses[postProcessesTakenIndices[index]];
  15416. var effect = pp.apply();
  15417. if (effect) {
  15418. if (pp.onBeforeRender) {
  15419. pp.onBeforeRender(effect);
  15420. }
  15421. // VBOs
  15422. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15423. // Draw order
  15424. engine.draw(true, 0, 6);
  15425. }
  15426. }
  15427. // Restore depth buffer
  15428. engine.setDepthBuffer(true);
  15429. engine.setDepthWrite(true);
  15430. };
  15431. PostProcessManager.prototype.dispose = function () {
  15432. if (this._vertexBuffer) {
  15433. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15434. this._vertexBuffer = null;
  15435. }
  15436. if (this._indexBuffer) {
  15437. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15438. this._indexBuffer = null;
  15439. }
  15440. };
  15441. return PostProcessManager;
  15442. })();
  15443. BABYLON.PostProcessManager = PostProcessManager;
  15444. })(BABYLON || (BABYLON = {}));
  15445. //# sourceMappingURL=babylon.postProcessManager.js.map
  15446. var BABYLON;
  15447. (function (BABYLON) {
  15448. var PassPostProcess = (function (_super) {
  15449. __extends(PassPostProcess, _super);
  15450. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15451. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15452. }
  15453. return PassPostProcess;
  15454. })(BABYLON.PostProcess);
  15455. BABYLON.PassPostProcess = PassPostProcess;
  15456. })(BABYLON || (BABYLON = {}));
  15457. //# sourceMappingURL=babylon.passPostProcess.js.map
  15458. var BABYLON;
  15459. (function (BABYLON) {
  15460. var BlurPostProcess = (function (_super) {
  15461. __extends(BlurPostProcess, _super);
  15462. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15463. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15464. var _this = this;
  15465. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15466. this.direction = direction;
  15467. this.blurWidth = blurWidth;
  15468. this.onApply = function (effect) {
  15469. effect.setFloat2("screenSize", _this.width, _this.height);
  15470. effect.setVector2("direction", _this.direction);
  15471. effect.setFloat("blurWidth", _this.blurWidth);
  15472. };
  15473. }
  15474. return BlurPostProcess;
  15475. })(BABYLON.PostProcess);
  15476. BABYLON.BlurPostProcess = BlurPostProcess;
  15477. })(BABYLON || (BABYLON = {}));
  15478. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15479. var BABYLON;
  15480. (function (BABYLON) {
  15481. var FilterPostProcess = (function (_super) {
  15482. __extends(FilterPostProcess, _super);
  15483. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15484. var _this = this;
  15485. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15486. this.kernelMatrix = kernelMatrix;
  15487. this.onApply = function (effect) {
  15488. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15489. };
  15490. }
  15491. return FilterPostProcess;
  15492. })(BABYLON.PostProcess);
  15493. BABYLON.FilterPostProcess = FilterPostProcess;
  15494. })(BABYLON || (BABYLON = {}));
  15495. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15496. var BABYLON;
  15497. (function (BABYLON) {
  15498. var RefractionPostProcess = (function (_super) {
  15499. __extends(RefractionPostProcess, _super);
  15500. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15501. var _this = this;
  15502. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15503. this.color = color;
  15504. this.depth = depth;
  15505. this.colorLevel = colorLevel;
  15506. this.onActivate = function (cam) {
  15507. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15508. };
  15509. this.onApply = function (effect) {
  15510. effect.setColor3("baseColor", _this.color);
  15511. effect.setFloat("depth", _this.depth);
  15512. effect.setFloat("colorLevel", _this.colorLevel);
  15513. effect.setTexture("refractionSampler", _this._refRexture);
  15514. };
  15515. }
  15516. // Methods
  15517. RefractionPostProcess.prototype.dispose = function (camera) {
  15518. if (this._refRexture) {
  15519. this._refRexture.dispose();
  15520. }
  15521. _super.prototype.dispose.call(this, camera);
  15522. };
  15523. return RefractionPostProcess;
  15524. })(BABYLON.PostProcess);
  15525. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15526. })(BABYLON || (BABYLON = {}));
  15527. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15528. var BABYLON;
  15529. (function (BABYLON) {
  15530. var BlackAndWhitePostProcess = (function (_super) {
  15531. __extends(BlackAndWhitePostProcess, _super);
  15532. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15533. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15534. }
  15535. return BlackAndWhitePostProcess;
  15536. })(BABYLON.PostProcess);
  15537. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15538. })(BABYLON || (BABYLON = {}));
  15539. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15540. var BABYLON;
  15541. (function (BABYLON) {
  15542. var ConvolutionPostProcess = (function (_super) {
  15543. __extends(ConvolutionPostProcess, _super);
  15544. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15545. var _this = this;
  15546. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15547. this.kernel = kernel;
  15548. this.onApply = function (effect) {
  15549. effect.setFloat2("screenSize", _this.width, _this.height);
  15550. effect.setArray("kernel", _this.kernel);
  15551. };
  15552. }
  15553. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15554. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15555. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15556. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15557. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15558. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15559. return ConvolutionPostProcess;
  15560. })(BABYLON.PostProcess);
  15561. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15562. })(BABYLON || (BABYLON = {}));
  15563. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15564. var BABYLON;
  15565. (function (BABYLON) {
  15566. var FxaaPostProcess = (function (_super) {
  15567. __extends(FxaaPostProcess, _super);
  15568. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15569. var _this = this;
  15570. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15571. this.onSizeChanged = function () {
  15572. _this.texelWidth = 1.0 / _this.width;
  15573. _this.texelHeight = 1.0 / _this.height;
  15574. };
  15575. this.onApply = function (effect) {
  15576. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15577. };
  15578. }
  15579. return FxaaPostProcess;
  15580. })(BABYLON.PostProcess);
  15581. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15582. })(BABYLON || (BABYLON = {}));
  15583. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15584. var BABYLON;
  15585. (function (BABYLON) {
  15586. var LensFlare = (function () {
  15587. function LensFlare(size, position, color, imgUrl, system) {
  15588. this.size = size;
  15589. this.position = position;
  15590. this.dispose = function () {
  15591. if (this.texture) {
  15592. this.texture.dispose();
  15593. }
  15594. // Remove from scene
  15595. var index = this._system.lensFlares.indexOf(this);
  15596. this._system.lensFlares.splice(index, 1);
  15597. };
  15598. this.color = color || new BABYLON.Color3(1, 1, 1);
  15599. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15600. this._system = system;
  15601. system.lensFlares.push(this);
  15602. }
  15603. return LensFlare;
  15604. })();
  15605. BABYLON.LensFlare = LensFlare;
  15606. })(BABYLON || (BABYLON = {}));
  15607. //# sourceMappingURL=babylon.lensFlare.js.map
  15608. var BABYLON;
  15609. (function (BABYLON) {
  15610. var LensFlareSystem = (function () {
  15611. function LensFlareSystem(name, emitter, scene) {
  15612. this.name = name;
  15613. this.lensFlares = new Array();
  15614. this.borderLimit = 300;
  15615. this._vertexDeclaration = [2];
  15616. this._vertexStrideSize = 2 * 4;
  15617. this._isEnabled = true;
  15618. this._scene = scene;
  15619. this._emitter = emitter;
  15620. scene.lensFlareSystems.push(this);
  15621. this.meshesSelectionPredicate = function (m) {
  15622. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15623. };
  15624. // VBO
  15625. var vertices = [];
  15626. vertices.push(1, 1);
  15627. vertices.push(-1, 1);
  15628. vertices.push(-1, -1);
  15629. vertices.push(1, -1);
  15630. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15631. // Indices
  15632. var indices = [];
  15633. indices.push(0);
  15634. indices.push(1);
  15635. indices.push(2);
  15636. indices.push(0);
  15637. indices.push(2);
  15638. indices.push(3);
  15639. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15640. // Effects
  15641. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15642. }
  15643. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15644. get: function () {
  15645. return this._isEnabled;
  15646. },
  15647. set: function (value) {
  15648. this._isEnabled = value;
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. LensFlareSystem.prototype.getScene = function () {
  15654. return this._scene;
  15655. };
  15656. LensFlareSystem.prototype.getEmitter = function () {
  15657. return this._emitter;
  15658. };
  15659. LensFlareSystem.prototype.getEmitterPosition = function () {
  15660. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15661. };
  15662. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15663. var position = this.getEmitterPosition();
  15664. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15665. this._positionX = position.x;
  15666. this._positionY = position.y;
  15667. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15668. if (position.z > 0) {
  15669. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15670. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15671. return true;
  15672. }
  15673. }
  15674. return false;
  15675. };
  15676. LensFlareSystem.prototype._isVisible = function () {
  15677. if (!this._isEnabled) {
  15678. return false;
  15679. }
  15680. var emitterPosition = this.getEmitterPosition();
  15681. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15682. var distance = direction.length();
  15683. direction.normalize();
  15684. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15685. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15686. return !pickInfo.hit || pickInfo.distance > distance;
  15687. };
  15688. LensFlareSystem.prototype.render = function () {
  15689. if (!this._effect.isReady())
  15690. return false;
  15691. var engine = this._scene.getEngine();
  15692. var viewport = this._scene.activeCamera.viewport;
  15693. var globalViewport = viewport.toGlobal(engine);
  15694. // Position
  15695. if (!this.computeEffectivePosition(globalViewport)) {
  15696. return false;
  15697. }
  15698. // Visibility
  15699. if (!this._isVisible()) {
  15700. return false;
  15701. }
  15702. // Intensity
  15703. var awayX;
  15704. var awayY;
  15705. if (this._positionX < this.borderLimit + globalViewport.x) {
  15706. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15707. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15708. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15709. } else {
  15710. awayX = 0;
  15711. }
  15712. if (this._positionY < this.borderLimit + globalViewport.y) {
  15713. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15714. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15715. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15716. } else {
  15717. awayY = 0;
  15718. }
  15719. var away = (awayX > awayY) ? awayX : awayY;
  15720. if (away > this.borderLimit) {
  15721. away = this.borderLimit;
  15722. }
  15723. var intensity = 1.0 - (away / this.borderLimit);
  15724. if (intensity < 0) {
  15725. return false;
  15726. }
  15727. if (intensity > 1.0) {
  15728. intensity = 1.0;
  15729. }
  15730. // Position
  15731. var centerX = globalViewport.x + globalViewport.width / 2;
  15732. var centerY = globalViewport.y + globalViewport.height / 2;
  15733. var distX = centerX - this._positionX;
  15734. var distY = centerY - this._positionY;
  15735. // Effects
  15736. engine.enableEffect(this._effect);
  15737. engine.setState(false);
  15738. engine.setDepthBuffer(false);
  15739. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15740. // VBOs
  15741. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15742. for (var index = 0; index < this.lensFlares.length; index++) {
  15743. var flare = this.lensFlares[index];
  15744. var x = centerX - (distX * flare.position);
  15745. var y = centerY - (distY * flare.position);
  15746. var cw = flare.size;
  15747. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15748. var cx = 2 * (x / globalViewport.width) - 1.0;
  15749. var cy = 1.0 - 2 * (y / globalViewport.height);
  15750. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15751. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15752. // Texture
  15753. this._effect.setTexture("textureSampler", flare.texture);
  15754. // Color
  15755. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15756. // Draw order
  15757. engine.draw(true, 0, 6);
  15758. }
  15759. engine.setDepthBuffer(true);
  15760. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15761. return true;
  15762. };
  15763. LensFlareSystem.prototype.dispose = function () {
  15764. if (this._vertexBuffer) {
  15765. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15766. this._vertexBuffer = null;
  15767. }
  15768. if (this._indexBuffer) {
  15769. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15770. this._indexBuffer = null;
  15771. }
  15772. while (this.lensFlares.length) {
  15773. this.lensFlares[0].dispose();
  15774. }
  15775. // Remove from scene
  15776. var index = this._scene.lensFlareSystems.indexOf(this);
  15777. this._scene.lensFlareSystems.splice(index, 1);
  15778. };
  15779. return LensFlareSystem;
  15780. })();
  15781. BABYLON.LensFlareSystem = LensFlareSystem;
  15782. })(BABYLON || (BABYLON = {}));
  15783. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15784. var BABYLON;
  15785. (function (BABYLON) {
  15786. var IntersectionInfo = (function () {
  15787. function IntersectionInfo(bu, bv, distance) {
  15788. this.bu = bu;
  15789. this.bv = bv;
  15790. this.distance = distance;
  15791. this.faceId = 0;
  15792. }
  15793. return IntersectionInfo;
  15794. })();
  15795. BABYLON.IntersectionInfo = IntersectionInfo;
  15796. var PickingInfo = (function () {
  15797. function PickingInfo() {
  15798. this.hit = false;
  15799. this.distance = 0;
  15800. this.pickedPoint = null;
  15801. this.pickedMesh = null;
  15802. this.bu = 0;
  15803. this.bv = 0;
  15804. this.faceId = -1;
  15805. }
  15806. // Methods
  15807. PickingInfo.prototype.getNormal = function () {
  15808. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15809. return null;
  15810. }
  15811. var indices = this.pickedMesh.getIndices();
  15812. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15813. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15814. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15815. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15816. normal0 = normal0.scale(this.bu);
  15817. normal1 = normal1.scale(this.bv);
  15818. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15819. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15820. };
  15821. PickingInfo.prototype.getTextureCoordinates = function () {
  15822. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15823. return null;
  15824. }
  15825. var indices = this.pickedMesh.getIndices();
  15826. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15827. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15828. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15829. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15830. uv0 = uv0.scale(this.bu);
  15831. uv1 = uv1.scale(this.bv);
  15832. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15833. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15834. };
  15835. return PickingInfo;
  15836. })();
  15837. BABYLON.PickingInfo = PickingInfo;
  15838. })(BABYLON || (BABYLON = {}));
  15839. //# sourceMappingURL=babylon.pickingInfo.js.map
  15840. var BABYLON;
  15841. (function (BABYLON) {
  15842. var FilesInput = (function () {
  15843. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15844. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15845. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15846. this.engine = p_engine;
  15847. this.canvas = p_canvas;
  15848. this.currentScene = p_scene;
  15849. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15850. this.progressCallback = p_progressCallback;
  15851. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15852. this.textureLoadingCallback = p_textureLoadingCallback;
  15853. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15854. }
  15855. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15856. var _this = this;
  15857. if (p_elementToMonitor) {
  15858. this.elementToMonitor = p_elementToMonitor;
  15859. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15860. _this.drag(e);
  15861. }, false);
  15862. this.elementToMonitor.addEventListener("dragover", function (e) {
  15863. _this.drag(e);
  15864. }, false);
  15865. this.elementToMonitor.addEventListener("drop", function (e) {
  15866. _this.drop(e);
  15867. }, false);
  15868. }
  15869. };
  15870. FilesInput.prototype.renderFunction = function () {
  15871. if (this.additionnalRenderLoopLogicCallback) {
  15872. this.additionnalRenderLoopLogicCallback();
  15873. }
  15874. if (this.currentScene) {
  15875. if (this.textureLoadingCallback) {
  15876. var remaining = this.currentScene.getWaitingItemsCount();
  15877. if (remaining > 0) {
  15878. this.textureLoadingCallback(remaining);
  15879. }
  15880. }
  15881. this.currentScene.render();
  15882. }
  15883. };
  15884. FilesInput.prototype.drag = function (e) {
  15885. e.stopPropagation();
  15886. e.preventDefault();
  15887. };
  15888. FilesInput.prototype.drop = function (eventDrop) {
  15889. eventDrop.stopPropagation();
  15890. eventDrop.preventDefault();
  15891. this.loadFiles(eventDrop);
  15892. };
  15893. FilesInput.prototype.loadFiles = function (event) {
  15894. var _this = this;
  15895. var that = this;
  15896. if (this.startingProcessingFilesCallback)
  15897. this.startingProcessingFilesCallback();
  15898. var sceneFileToLoad;
  15899. var filesToLoad;
  15900. // Handling data transfer via drag'n'drop
  15901. if (event && event.dataTransfer && event.dataTransfer.files) {
  15902. filesToLoad = event.dataTransfer.files;
  15903. }
  15904. // Handling files from input files
  15905. if (event && event.target && event.target.files) {
  15906. filesToLoad = event.target.files;
  15907. }
  15908. if (filesToLoad && filesToLoad.length > 0) {
  15909. for (var i = 0; i < filesToLoad.length; i++) {
  15910. switch (filesToLoad[i].type) {
  15911. case "image/jpeg":
  15912. case "image/png":
  15913. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15914. break;
  15915. case "image/targa":
  15916. case "image/vnd.ms-dds":
  15917. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15918. break;
  15919. default:
  15920. 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) {
  15921. sceneFileToLoad = filesToLoad[i];
  15922. }
  15923. break;
  15924. }
  15925. }
  15926. // If a ".babylon" file has been provided
  15927. if (sceneFileToLoad) {
  15928. if (this.currentScene) {
  15929. this.engine.stopRenderLoop();
  15930. this.currentScene.dispose();
  15931. }
  15932. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15933. that.currentScene = newScene;
  15934. // Wait for textures and shaders to be ready
  15935. that.currentScene.executeWhenReady(function () {
  15936. // Attach camera to canvas inputs
  15937. if (that.currentScene.activeCamera) {
  15938. that.currentScene.activeCamera.attachControl(that.canvas);
  15939. }
  15940. if (that.sceneLoadedCallback) {
  15941. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15942. }
  15943. that.engine.runRenderLoop(function () {
  15944. that.renderFunction();
  15945. });
  15946. });
  15947. }, function (progress) {
  15948. if (_this.progressCallback) {
  15949. _this.progressCallback(progress);
  15950. }
  15951. });
  15952. } else {
  15953. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15954. }
  15955. }
  15956. };
  15957. FilesInput.FilesTextures = new Array();
  15958. FilesInput.FilesToLoad = new Array();
  15959. return FilesInput;
  15960. })();
  15961. BABYLON.FilesInput = FilesInput;
  15962. })(BABYLON || (BABYLON = {}));
  15963. //# sourceMappingURL=babylon.filesInput.js.map
  15964. var BABYLON;
  15965. (function (BABYLON) {
  15966. var OimoJSPlugin = (function () {
  15967. function OimoJSPlugin() {
  15968. this._registeredMeshes = [];
  15969. /**
  15970. * Update the body position according to the mesh position
  15971. * @param mesh
  15972. */
  15973. this.updateBodyPosition = function (mesh) {
  15974. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15975. var registeredMesh = this._registeredMeshes[index];
  15976. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15977. var body = registeredMesh.body.body;
  15978. mesh.computeWorldMatrix(true);
  15979. var center = mesh.getBoundingInfo().boundingBox.center;
  15980. body.setPosition(center.x, center.y, center.z);
  15981. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15982. return;
  15983. }
  15984. // Case where the parent has been updated
  15985. if (registeredMesh.mesh.parent === mesh) {
  15986. mesh.computeWorldMatrix(true);
  15987. registeredMesh.mesh.computeWorldMatrix(true);
  15988. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15989. var absoluteRotation = mesh.rotation;
  15990. body = registeredMesh.body.body;
  15991. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15992. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15993. return;
  15994. }
  15995. }
  15996. };
  15997. }
  15998. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15999. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16000. };
  16001. OimoJSPlugin.prototype.initialize = function (iterations) {
  16002. this._world = new OIMO.World();
  16003. this._world.clear();
  16004. };
  16005. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16006. this._world.gravity = gravity;
  16007. };
  16008. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16009. var body = null;
  16010. this.unregisterMesh(mesh);
  16011. mesh.computeWorldMatrix(true);
  16012. switch (impostor) {
  16013. case BABYLON.PhysicsEngine.SphereImpostor:
  16014. var initialRotation = null;
  16015. if (mesh.rotationQuaternion) {
  16016. initialRotation = mesh.rotationQuaternion.clone();
  16017. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16018. mesh.computeWorldMatrix(true);
  16019. }
  16020. var bbox = mesh.getBoundingInfo().boundingBox;
  16021. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16022. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16023. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16024. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16025. // The delta between the mesh position and the mesh bounding box center
  16026. var deltaPosition = mesh.position.subtract(bbox.center);
  16027. // Transform delta position with the rotation
  16028. if (initialRotation) {
  16029. var m = new BABYLON.Matrix();
  16030. initialRotation.toRotationMatrix(m);
  16031. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16032. }
  16033. body = new OIMO.Body({
  16034. type: 'sphere',
  16035. size: [size],
  16036. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16037. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16038. move: options.mass != 0,
  16039. config: [options.mass, options.friction, options.restitution],
  16040. world: this._world
  16041. });
  16042. // Restore rotation
  16043. if (initialRotation) {
  16044. body.setQuaternion(initialRotation);
  16045. }
  16046. this._registeredMeshes.push({
  16047. mesh: mesh,
  16048. body: body,
  16049. delta: deltaPosition
  16050. });
  16051. break;
  16052. case BABYLON.PhysicsEngine.PlaneImpostor:
  16053. case BABYLON.PhysicsEngine.BoxImpostor:
  16054. initialRotation = null;
  16055. if (mesh.rotationQuaternion) {
  16056. initialRotation = mesh.rotationQuaternion.clone();
  16057. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16058. mesh.computeWorldMatrix(true);
  16059. }
  16060. bbox = mesh.getBoundingInfo().boundingBox;
  16061. var min = bbox.minimumWorld;
  16062. var max = bbox.maximumWorld;
  16063. var box = max.subtract(min);
  16064. var sizeX = this._checkWithEpsilon(box.x);
  16065. var sizeY = this._checkWithEpsilon(box.y);
  16066. var sizeZ = this._checkWithEpsilon(box.z);
  16067. // The delta between the mesh position and the mesh boudning box center
  16068. deltaPosition = mesh.position.subtract(bbox.center);
  16069. // Transform delta position with the rotation
  16070. if (initialRotation) {
  16071. m = new BABYLON.Matrix();
  16072. initialRotation.toRotationMatrix(m);
  16073. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16074. }
  16075. body = new OIMO.Body({
  16076. type: 'box',
  16077. size: [sizeX, sizeY, sizeZ],
  16078. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16079. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16080. move: options.mass != 0,
  16081. config: [options.mass, options.friction, options.restitution],
  16082. world: this._world
  16083. });
  16084. if (initialRotation) {
  16085. body.setQuaternion(initialRotation);
  16086. }
  16087. this._registeredMeshes.push({
  16088. mesh: mesh,
  16089. body: body,
  16090. delta: deltaPosition
  16091. });
  16092. break;
  16093. }
  16094. return body;
  16095. };
  16096. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16097. var types = [], sizes = [], positions = [], rotations = [];
  16098. var initialMesh = parts[0].mesh;
  16099. for (var index = 0; index < parts.length; index++) {
  16100. var part = parts[index];
  16101. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16102. types.push(bodyParameters.type);
  16103. sizes.push.apply(sizes, bodyParameters.size);
  16104. positions.push.apply(positions, bodyParameters.pos);
  16105. rotations.push.apply(rotations, bodyParameters.rot);
  16106. }
  16107. var body = new OIMO.Body({
  16108. type: types,
  16109. size: sizes,
  16110. pos: positions,
  16111. rot: rotations,
  16112. move: options.mass != 0,
  16113. config: [options.mass, options.friction, options.restitution],
  16114. world: this._world
  16115. });
  16116. this._registeredMeshes.push({
  16117. mesh: initialMesh,
  16118. body: body
  16119. });
  16120. return body;
  16121. };
  16122. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16123. var bodyParameters = null;
  16124. var mesh = part.mesh;
  16125. switch (part.impostor) {
  16126. case BABYLON.PhysicsEngine.SphereImpostor:
  16127. var bbox = mesh.getBoundingInfo().boundingBox;
  16128. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16129. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16130. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16131. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16132. bodyParameters = {
  16133. type: 'sphere',
  16134. /* bug with oimo : sphere needs 3 sizes in this case */
  16135. size: [size, -1, -1],
  16136. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16137. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16138. };
  16139. break;
  16140. case BABYLON.PhysicsEngine.PlaneImpostor:
  16141. case BABYLON.PhysicsEngine.BoxImpostor:
  16142. bbox = mesh.getBoundingInfo().boundingBox;
  16143. var min = bbox.minimumWorld;
  16144. var max = bbox.maximumWorld;
  16145. var box = max.subtract(min);
  16146. var sizeX = this._checkWithEpsilon(box.x);
  16147. var sizeY = this._checkWithEpsilon(box.y);
  16148. var sizeZ = this._checkWithEpsilon(box.z);
  16149. var relativePosition = mesh.position;
  16150. bodyParameters = {
  16151. type: 'box',
  16152. size: [sizeX, sizeY, sizeZ],
  16153. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16154. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16155. };
  16156. break;
  16157. }
  16158. return bodyParameters;
  16159. };
  16160. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16161. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16162. var registeredMesh = this._registeredMeshes[index];
  16163. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16164. if (registeredMesh.body) {
  16165. this._world.removeRigidBody(registeredMesh.body.body);
  16166. this._unbindBody(registeredMesh.body);
  16167. }
  16168. this._registeredMeshes.splice(index, 1);
  16169. return;
  16170. }
  16171. }
  16172. };
  16173. OimoJSPlugin.prototype._unbindBody = function (body) {
  16174. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16175. var registeredMesh = this._registeredMeshes[index];
  16176. if (registeredMesh.body === body) {
  16177. registeredMesh.body = null;
  16178. }
  16179. }
  16180. };
  16181. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16182. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16183. var registeredMesh = this._registeredMeshes[index];
  16184. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16185. // Get object mass to have a behaviour similar to cannon.js
  16186. var mass = registeredMesh.body.body.massInfo.mass;
  16187. // The force is scaled with the mass of object
  16188. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16189. return;
  16190. }
  16191. }
  16192. };
  16193. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16194. var body1 = null, body2 = null;
  16195. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16196. var registeredMesh = this._registeredMeshes[index];
  16197. if (registeredMesh.mesh === mesh1) {
  16198. body1 = registeredMesh.body.body;
  16199. } else if (registeredMesh.mesh === mesh2) {
  16200. body2 = registeredMesh.body.body;
  16201. }
  16202. }
  16203. if (!body1 || !body2) {
  16204. return false;
  16205. }
  16206. if (!options) {
  16207. options = {};
  16208. }
  16209. new OIMO.Link({
  16210. type: options.type,
  16211. body1: body1,
  16212. body2: body2,
  16213. min: options.min,
  16214. max: options.max,
  16215. axe1: options.axe1,
  16216. axe2: options.axe2,
  16217. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16218. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16219. collision: options.collision,
  16220. spring: options.spring,
  16221. world: this._world
  16222. });
  16223. return true;
  16224. };
  16225. OimoJSPlugin.prototype.dispose = function () {
  16226. this._world.clear();
  16227. while (this._registeredMeshes.length) {
  16228. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16229. }
  16230. };
  16231. OimoJSPlugin.prototype.isSupported = function () {
  16232. return OIMO !== undefined;
  16233. };
  16234. OimoJSPlugin.prototype._getLastShape = function (body) {
  16235. var lastShape = body.shapes;
  16236. while (lastShape.next) {
  16237. lastShape = lastShape.next;
  16238. }
  16239. return lastShape;
  16240. };
  16241. OimoJSPlugin.prototype.runOneStep = function (time) {
  16242. this._world.step();
  16243. // Update the position of all registered meshes
  16244. var i = this._registeredMeshes.length;
  16245. var m;
  16246. while (i--) {
  16247. var body = this._registeredMeshes[i].body.body;
  16248. var mesh = this._registeredMeshes[i].mesh;
  16249. var delta = this._registeredMeshes[i].delta;
  16250. if (!body.sleeping) {
  16251. if (body.shapes.next) {
  16252. var parentShape = this._getLastShape(body);
  16253. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16254. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16255. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16256. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16257. if (!mesh.rotationQuaternion) {
  16258. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16259. }
  16260. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16261. mesh.computeWorldMatrix();
  16262. } else {
  16263. m = body.getMatrix();
  16264. mtx = BABYLON.Matrix.FromArray(m);
  16265. // Body position
  16266. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16267. if (!delta) {
  16268. mesh.position.x = bodyX;
  16269. mesh.position.y = bodyY;
  16270. mesh.position.z = bodyZ;
  16271. } else {
  16272. mesh.position.x = bodyX + delta.x;
  16273. mesh.position.y = bodyY + delta.y;
  16274. mesh.position.z = bodyZ + delta.z;
  16275. }
  16276. if (!mesh.rotationQuaternion) {
  16277. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16278. }
  16279. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16280. mesh.computeWorldMatrix();
  16281. }
  16282. }
  16283. }
  16284. };
  16285. return OimoJSPlugin;
  16286. })();
  16287. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16288. })(BABYLON || (BABYLON = {}));
  16289. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16290. var BABYLON;
  16291. (function (BABYLON) {
  16292. var PhysicsEngine = (function () {
  16293. function PhysicsEngine(plugin) {
  16294. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16295. }
  16296. PhysicsEngine.prototype._initialize = function (gravity) {
  16297. this._currentPlugin.initialize();
  16298. this._setGravity(gravity);
  16299. };
  16300. PhysicsEngine.prototype._runOneStep = function (delta) {
  16301. if (delta > 0.1) {
  16302. delta = 0.1;
  16303. } else if (delta <= 0) {
  16304. delta = 1.0 / 60.0;
  16305. }
  16306. this._currentPlugin.runOneStep(delta);
  16307. };
  16308. PhysicsEngine.prototype._setGravity = function (gravity) {
  16309. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16310. this._currentPlugin.setGravity(this.gravity);
  16311. };
  16312. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16313. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16314. };
  16315. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16316. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16317. };
  16318. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16319. this._currentPlugin.unregisterMesh(mesh);
  16320. };
  16321. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16322. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16323. };
  16324. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16325. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16326. };
  16327. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16328. this._currentPlugin.updateBodyPosition(mesh);
  16329. };
  16330. PhysicsEngine.prototype.dispose = function () {
  16331. this._currentPlugin.dispose();
  16332. };
  16333. PhysicsEngine.prototype.isSupported = function () {
  16334. return this._currentPlugin.isSupported();
  16335. };
  16336. PhysicsEngine.NoImpostor = 0;
  16337. PhysicsEngine.SphereImpostor = 1;
  16338. PhysicsEngine.BoxImpostor = 2;
  16339. PhysicsEngine.PlaneImpostor = 3;
  16340. PhysicsEngine.MeshImpostor = 4;
  16341. PhysicsEngine.CapsuleImpostor = 5;
  16342. PhysicsEngine.ConeImpostor = 6;
  16343. PhysicsEngine.CylinderImpostor = 7;
  16344. PhysicsEngine.ConvexHullImpostor = 8;
  16345. PhysicsEngine.Epsilon = 0.001;
  16346. return PhysicsEngine;
  16347. })();
  16348. BABYLON.PhysicsEngine = PhysicsEngine;
  16349. })(BABYLON || (BABYLON = {}));
  16350. //# sourceMappingURL=babylon.physicsEngine.js.map
  16351. var BABYLON;
  16352. (function (BABYLON) {
  16353. var serializeLight = function (light) {
  16354. var serializationObject = {};
  16355. serializationObject.name = light.name;
  16356. serializationObject.id = light.id;
  16357. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16358. if (light instanceof BABYLON.PointLight) {
  16359. serializationObject.type = 0;
  16360. serializationObject.position = light.position.asArray();
  16361. } else if (light instanceof BABYLON.DirectionalLight) {
  16362. serializationObject.type = 1;
  16363. var directionalLight = light;
  16364. serializationObject.position = directionalLight.position.asArray();
  16365. serializationObject.direction = directionalLight.direction.asArray();
  16366. } else if (light instanceof BABYLON.SpotLight) {
  16367. serializationObject.type = 2;
  16368. var spotLight = light;
  16369. serializationObject.position = spotLight.position.asArray();
  16370. serializationObject.direction = spotLight.position.asArray();
  16371. serializationObject.angle = spotLight.angle;
  16372. serializationObject.exponent = spotLight.exponent;
  16373. } else if (light instanceof BABYLON.HemisphericLight) {
  16374. serializationObject.type = 3;
  16375. var hemisphericLight = light;
  16376. serializationObject.direction = hemisphericLight.direction.asArray();
  16377. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16378. }
  16379. if (light.intensity) {
  16380. serializationObject.intensity = light.intensity;
  16381. }
  16382. serializationObject.range = light.range;
  16383. serializationObject.diffuse = light.diffuse.asArray();
  16384. serializationObject.specular = light.specular.asArray();
  16385. return serializationObject;
  16386. };
  16387. var serializeFresnelParameter = function (fresnelParameter) {
  16388. var serializationObject = {};
  16389. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16390. serializationObject.leftColor = fresnelParameter.leftColor;
  16391. serializationObject.rightColor = fresnelParameter.rightColor;
  16392. serializationObject.bias = fresnelParameter.bias;
  16393. serializationObject.power = fresnelParameter.power;
  16394. return serializationObject;
  16395. };
  16396. var serializeCamera = function (camera) {
  16397. var serializationObject = {};
  16398. serializationObject.name = camera.name;
  16399. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16400. serializationObject.id = camera.id;
  16401. serializationObject.position = camera.position.asArray();
  16402. // Parent
  16403. if (camera.parent) {
  16404. serializationObject.parentId = camera.parent.id;
  16405. }
  16406. // Target
  16407. serializationObject.rotation = camera.rotation.asArray();
  16408. // Locked target
  16409. if (camera.lockedTarget && camera.lockedTarget.id) {
  16410. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16411. }
  16412. serializationObject.fov = camera.fov;
  16413. serializationObject.minZ = camera.minZ;
  16414. serializationObject.maxZ = camera.maxZ;
  16415. serializationObject.speed = camera.speed;
  16416. serializationObject.inertia = camera.inertia;
  16417. serializationObject.checkCollisions = camera.checkCollisions;
  16418. serializationObject.applyGravity = camera.applyGravity;
  16419. if (camera.ellipsoid) {
  16420. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16421. }
  16422. // Animations
  16423. appendAnimations(camera, serializationObject);
  16424. // Layer mask
  16425. serializationObject.layerMask = camera.layerMask;
  16426. return serializationObject;
  16427. };
  16428. var appendAnimations = function (source, destination) {
  16429. if (source.animations) {
  16430. destination.animations = [];
  16431. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16432. var animation = source.animations[animationIndex];
  16433. destination.animations.push(serializeAnimation(animation));
  16434. }
  16435. }
  16436. };
  16437. var serializeAnimation = function (animation) {
  16438. var serializationObject = {};
  16439. serializationObject.name = animation.name;
  16440. serializationObject.property = animation.targetProperty;
  16441. serializationObject.framePerSecond = animation.framePerSecond;
  16442. serializationObject.dataType = animation.dataType;
  16443. serializationObject.loopBehavior = animation.loopMode;
  16444. var dataType = animation.dataType;
  16445. serializationObject.keys = [];
  16446. var keys = animation.getKeys();
  16447. for (var index = 0; index < keys.length; index++) {
  16448. var animationKey = keys[index];
  16449. var key = {};
  16450. key.frame = animationKey.frame;
  16451. switch (dataType) {
  16452. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16453. key.values = [animationKey.value];
  16454. break;
  16455. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16456. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16457. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16458. key.values = animationKey.value.asArray();
  16459. break;
  16460. }
  16461. serializationObject.keys.push(key);
  16462. }
  16463. return serializationObject;
  16464. };
  16465. var serializeMultiMaterial = function (material) {
  16466. var serializationObject = {};
  16467. serializationObject.name = material.name;
  16468. serializationObject.id = material.id;
  16469. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16470. serializationObject.materials = [];
  16471. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16472. var subMat = material.subMaterials[matIndex];
  16473. if (subMat) {
  16474. serializationObject.materials.push(subMat.id);
  16475. } else {
  16476. serializationObject.materials.push(null);
  16477. }
  16478. }
  16479. return serializationObject;
  16480. };
  16481. var serializeMaterial = function (material) {
  16482. var serializationObject = {};
  16483. serializationObject.name = material.name;
  16484. serializationObject.ambient = material.ambientColor.asArray();
  16485. serializationObject.diffuse = material.diffuseColor.asArray();
  16486. serializationObject.specular = material.specularColor.asArray();
  16487. serializationObject.specularPower = material.specularPower;
  16488. serializationObject.emissive = material.emissiveColor.asArray();
  16489. serializationObject.alpha = material.alpha;
  16490. serializationObject.id = material.id;
  16491. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16492. serializationObject.backFaceCulling = material.backFaceCulling;
  16493. if (material.diffuseTexture) {
  16494. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16495. }
  16496. if (material.diffuseFresnelParameters) {
  16497. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16498. }
  16499. if (material.ambientTexture) {
  16500. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16501. }
  16502. if (material.opacityTexture) {
  16503. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16504. }
  16505. if (material.opacityFresnelParameters) {
  16506. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16507. }
  16508. if (material.reflectionTexture) {
  16509. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16510. }
  16511. if (material.reflectionFresnelParameters) {
  16512. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16513. }
  16514. if (material.emissiveTexture) {
  16515. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16516. }
  16517. if (material.emissiveFresnelParameters) {
  16518. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16519. }
  16520. if (material.specularTexture) {
  16521. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16522. }
  16523. if (material.bumpTexture) {
  16524. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16525. }
  16526. return serializationObject;
  16527. };
  16528. var serializeTexture = function (texture) {
  16529. var serializationObject = {};
  16530. if (!texture.name) {
  16531. return null;
  16532. }
  16533. if (texture instanceof BABYLON.CubeTexture) {
  16534. serializationObject.name = texture.name;
  16535. serializationObject.hasAlpha = texture.hasAlpha;
  16536. serializationObject.level = texture.level;
  16537. serializationObject.coordinatesMode = texture.coordinatesMode;
  16538. return serializationObject;
  16539. }
  16540. if (texture instanceof BABYLON.MirrorTexture) {
  16541. var mirrorTexture = texture;
  16542. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16543. serializationObject.renderList = [];
  16544. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16545. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16546. }
  16547. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16548. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16549. var renderTargetTexture = texture;
  16550. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16551. serializationObject.renderList = [];
  16552. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16553. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16554. }
  16555. }
  16556. var regularTexture = texture;
  16557. serializationObject.name = texture.name;
  16558. serializationObject.hasAlpha = texture.hasAlpha;
  16559. serializationObject.level = texture.level;
  16560. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16561. serializationObject.coordinatesMode = texture.coordinatesMode;
  16562. serializationObject.uOffset = regularTexture.uOffset;
  16563. serializationObject.vOffset = regularTexture.vOffset;
  16564. serializationObject.uScale = regularTexture.uScale;
  16565. serializationObject.vScale = regularTexture.vScale;
  16566. serializationObject.uAng = regularTexture.uAng;
  16567. serializationObject.vAng = regularTexture.vAng;
  16568. serializationObject.wAng = regularTexture.wAng;
  16569. serializationObject.wrapU = texture.wrapU;
  16570. serializationObject.wrapV = texture.wrapV;
  16571. // Animations
  16572. appendAnimations(texture, serializationObject);
  16573. return serializationObject;
  16574. };
  16575. var serializeSkeleton = function (skeleton) {
  16576. var serializationObject = {};
  16577. serializationObject.name = skeleton.name;
  16578. serializationObject.id = skeleton.id;
  16579. serializationObject.bones = [];
  16580. for (var index = 0; index < skeleton.bones.length; index++) {
  16581. var bone = skeleton.bones[index];
  16582. var serializedBone = {
  16583. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16584. name: bone.name,
  16585. matrix: bone.getLocalMatrix().toArray()
  16586. };
  16587. serializationObject.bones.push(serializedBone);
  16588. if (bone.animations && bone.animations.length > 0) {
  16589. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16590. }
  16591. }
  16592. return serializationObject;
  16593. };
  16594. var serializeParticleSystem = function (particleSystem) {
  16595. var serializationObject = {};
  16596. serializationObject.emitterId = particleSystem.emitter.id;
  16597. serializationObject.capacity = particleSystem.getCapacity();
  16598. if (particleSystem.particleTexture) {
  16599. serializationObject.textureName = particleSystem.particleTexture.name;
  16600. }
  16601. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16602. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16603. serializationObject.minSize = particleSystem.minSize;
  16604. serializationObject.maxSize = particleSystem.maxSize;
  16605. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16606. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16607. serializationObject.emitRate = particleSystem.emitRate;
  16608. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16609. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16610. serializationObject.gravity = particleSystem.gravity.asArray();
  16611. serializationObject.direction1 = particleSystem.direction1.asArray();
  16612. serializationObject.direction2 = particleSystem.direction2.asArray();
  16613. serializationObject.color1 = particleSystem.color1.asArray();
  16614. serializationObject.color2 = particleSystem.color2.asArray();
  16615. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16616. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16617. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16618. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16619. serializationObject.blendMode = particleSystem.blendMode;
  16620. return serializationObject;
  16621. };
  16622. var serializeLensFlareSystem = function (lensFlareSystem) {
  16623. var serializationObject = {};
  16624. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16625. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16626. serializationObject.flares = [];
  16627. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16628. var flare = lensFlareSystem.lensFlares[index];
  16629. serializationObject.flares.push({
  16630. size: flare.size,
  16631. position: flare.position,
  16632. color: flare.color.asArray(),
  16633. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16634. });
  16635. }
  16636. return serializationObject;
  16637. };
  16638. var serializeShadowGenerator = function (light) {
  16639. var serializationObject = {};
  16640. var shadowGenerator = light.getShadowGenerator();
  16641. serializationObject.lightId = light.id;
  16642. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16643. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16644. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16645. serializationObject.renderList = [];
  16646. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16647. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16648. serializationObject.renderList.push(mesh.id);
  16649. }
  16650. return serializationObject;
  16651. };
  16652. var serializedGeometries = [];
  16653. var serializeGeometry = function (geometry, serializationGeometries) {
  16654. if (serializedGeometries[geometry.id]) {
  16655. return;
  16656. }
  16657. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16658. serializationGeometries.boxes.push(serializeBox(geometry));
  16659. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16660. serializationGeometries.spheres.push(serializeSphere(geometry));
  16661. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16662. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16663. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16664. serializationGeometries.toruses.push(serializeTorus(geometry));
  16665. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16666. serializationGeometries.grounds.push(serializeGround(geometry));
  16667. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16668. serializationGeometries.planes.push(serializePlane(geometry));
  16669. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16670. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16671. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16672. throw new Error("Unknow primitive type");
  16673. } else {
  16674. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16675. }
  16676. serializedGeometries[geometry.id] = true;
  16677. };
  16678. var serializeGeometryBase = function (geometry) {
  16679. var serializationObject = {};
  16680. serializationObject.id = geometry.id;
  16681. if (BABYLON.Tags.HasTags(geometry)) {
  16682. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16683. }
  16684. return serializationObject;
  16685. };
  16686. var serializeVertexData = function (vertexData) {
  16687. var serializationObject = serializeGeometryBase(vertexData);
  16688. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16689. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16690. }
  16691. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16692. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16693. }
  16694. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16695. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16696. }
  16697. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16698. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16699. }
  16700. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16701. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16702. }
  16703. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16704. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16705. serializationObject.matricesIndices._isExpanded = true;
  16706. }
  16707. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16708. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16709. }
  16710. serializationObject.indices = vertexData.getIndices();
  16711. return serializationObject;
  16712. };
  16713. var serializePrimitive = function (primitive) {
  16714. var serializationObject = serializeGeometryBase(primitive);
  16715. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16716. return serializationObject;
  16717. };
  16718. var serializeBox = function (box) {
  16719. var serializationObject = serializePrimitive(box);
  16720. serializationObject.size = box.size;
  16721. return serializationObject;
  16722. };
  16723. var serializeSphere = function (sphere) {
  16724. var serializationObject = serializePrimitive(sphere);
  16725. serializationObject.segments = sphere.segments;
  16726. serializationObject.diameter = sphere.diameter;
  16727. return serializationObject;
  16728. };
  16729. var serializeCylinder = function (cylinder) {
  16730. var serializationObject = serializePrimitive(cylinder);
  16731. serializationObject.height = cylinder.height;
  16732. serializationObject.diameterTop = cylinder.diameterTop;
  16733. serializationObject.diameterBottom = cylinder.diameterBottom;
  16734. serializationObject.tessellation = cylinder.tessellation;
  16735. return serializationObject;
  16736. };
  16737. var serializeTorus = function (torus) {
  16738. var serializationObject = serializePrimitive(torus);
  16739. serializationObject.diameter = torus.diameter;
  16740. serializationObject.thickness = torus.thickness;
  16741. serializationObject.tessellation = torus.tessellation;
  16742. return serializationObject;
  16743. };
  16744. var serializeGround = function (ground) {
  16745. var serializationObject = serializePrimitive(ground);
  16746. serializationObject.width = ground.width;
  16747. serializationObject.height = ground.height;
  16748. serializationObject.subdivisions = ground.subdivisions;
  16749. return serializationObject;
  16750. };
  16751. var serializePlane = function (plane) {
  16752. var serializationObject = serializePrimitive(plane);
  16753. serializationObject.size = plane.size;
  16754. return serializationObject;
  16755. };
  16756. var serializeTorusKnot = function (torusKnot) {
  16757. var serializationObject = serializePrimitive(torusKnot);
  16758. serializationObject.radius = torusKnot.radius;
  16759. serializationObject.tube = torusKnot.tube;
  16760. serializationObject.radialSegments = torusKnot.radialSegments;
  16761. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16762. serializationObject.p = torusKnot.p;
  16763. serializationObject.q = torusKnot.q;
  16764. return serializationObject;
  16765. };
  16766. var serializeMesh = function (mesh, serializationScene) {
  16767. var serializationObject = {};
  16768. serializationObject.name = mesh.name;
  16769. serializationObject.id = mesh.id;
  16770. if (BABYLON.Tags.HasTags(mesh)) {
  16771. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16772. }
  16773. serializationObject.position = mesh.position.asArray();
  16774. if (mesh.rotationQuaternion) {
  16775. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16776. } else if (mesh.rotation) {
  16777. serializationObject.rotation = mesh.rotation.asArray();
  16778. }
  16779. serializationObject.scaling = mesh.scaling.asArray();
  16780. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16781. serializationObject.isEnabled = mesh.isEnabled();
  16782. serializationObject.isVisible = mesh.isVisible;
  16783. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16784. serializationObject.pickable = mesh.isPickable;
  16785. serializationObject.receiveShadows = mesh.receiveShadows;
  16786. serializationObject.billboardMode = mesh.billboardMode;
  16787. serializationObject.visibility = mesh.visibility;
  16788. serializationObject.checkCollisions = mesh.checkCollisions;
  16789. // Parent
  16790. if (mesh.parent) {
  16791. serializationObject.parentId = mesh.parent.id;
  16792. }
  16793. // Geometry
  16794. var geometry = mesh._geometry;
  16795. if (geometry) {
  16796. var geometryId = geometry.id;
  16797. serializationObject.geometryId = geometryId;
  16798. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16799. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  16800. serializeGeometry(geometry, serializationScene.geometries);
  16801. }
  16802. // SubMeshes
  16803. serializationObject.subMeshes = [];
  16804. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16805. var subMesh = mesh.subMeshes[subIndex];
  16806. serializationObject.subMeshes.push({
  16807. materialIndex: subMesh.materialIndex,
  16808. verticesStart: subMesh.verticesStart,
  16809. verticesCount: subMesh.verticesCount,
  16810. indexStart: subMesh.indexStart,
  16811. indexCount: subMesh.indexCount
  16812. });
  16813. }
  16814. }
  16815. // Material
  16816. if (mesh.material) {
  16817. serializationObject.materialId = mesh.material.id;
  16818. } else {
  16819. mesh.material = null;
  16820. }
  16821. // Skeleton
  16822. if (mesh.skeleton) {
  16823. serializationObject.skeletonId = mesh.skeleton.id;
  16824. }
  16825. // Physics
  16826. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16827. serializationObject.physicsMass = mesh.getPhysicsMass();
  16828. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16829. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16830. switch (mesh.getPhysicsImpostor()) {
  16831. case BABYLON.PhysicsEngine.BoxImpostor:
  16832. serializationObject.physicsImpostor = 1;
  16833. break;
  16834. case BABYLON.PhysicsEngine.SphereImpostor:
  16835. serializationObject.physicsImpostor = 2;
  16836. break;
  16837. }
  16838. }
  16839. // Instances
  16840. serializationObject.instances = [];
  16841. for (var index = 0; index < mesh.instances.length; index++) {
  16842. var instance = mesh.instances[index];
  16843. var serializationInstance = {
  16844. name: instance.name,
  16845. position: instance.position,
  16846. rotation: instance.rotation,
  16847. rotationQuaternion: instance.rotationQuaternion,
  16848. scaling: instance.scaling
  16849. };
  16850. serializationObject.instances.push(serializationInstance);
  16851. // Animations
  16852. appendAnimations(instance, serializationInstance);
  16853. }
  16854. // Animations
  16855. appendAnimations(mesh, serializationObject);
  16856. // Layer mask
  16857. serializationObject.layerMask = mesh.layerMask;
  16858. return serializationObject;
  16859. };
  16860. var SceneSerializer = (function () {
  16861. function SceneSerializer() {
  16862. }
  16863. SceneSerializer.Serialize = function (scene) {
  16864. var serializationObject = {};
  16865. // Scene
  16866. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16867. serializationObject.autoClear = scene.autoClear;
  16868. serializationObject.clearColor = scene.clearColor.asArray();
  16869. serializationObject.ambientColor = scene.ambientColor.asArray();
  16870. serializationObject.gravity = scene.gravity.asArray();
  16871. // Fog
  16872. if (scene.fogMode && scene.fogMode !== 0) {
  16873. serializationObject.fogMode = scene.fogMode;
  16874. serializationObject.fogColor = scene.fogColor.asArray();
  16875. serializationObject.fogStart = scene.fogStart;
  16876. serializationObject.fogEnd = scene.fogEnd;
  16877. serializationObject.fogDensity = scene.fogDensity;
  16878. }
  16879. // Lights
  16880. serializationObject.lights = [];
  16881. for (var index = 0; index < scene.lights.length; index++) {
  16882. var light = scene.lights[index];
  16883. serializationObject.lights.push(serializeLight(light));
  16884. }
  16885. // Cameras
  16886. serializationObject.cameras = [];
  16887. for (index = 0; index < scene.cameras.length; index++) {
  16888. var camera = scene.cameras[index];
  16889. if (camera instanceof BABYLON.FreeCamera) {
  16890. serializationObject.cameras.push(serializeCamera(camera));
  16891. }
  16892. }
  16893. if (scene.activeCamera) {
  16894. serializationObject.activeCameraID = scene.activeCamera.id;
  16895. }
  16896. // Materials
  16897. serializationObject.materials = [];
  16898. serializationObject.multiMaterials = [];
  16899. for (index = 0; index < scene.materials.length; index++) {
  16900. var material = scene.materials[index];
  16901. if (material instanceof BABYLON.StandardMaterial) {
  16902. serializationObject.materials.push(serializeMaterial(material));
  16903. } else if (material instanceof BABYLON.MultiMaterial) {
  16904. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16905. }
  16906. }
  16907. // Skeletons
  16908. serializationObject.skeletons = [];
  16909. for (index = 0; index < scene.skeletons.length; index++) {
  16910. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16911. }
  16912. // Geometries
  16913. serializationObject.geometries = {};
  16914. serializationObject.geometries.boxes = [];
  16915. serializationObject.geometries.spheres = [];
  16916. serializationObject.geometries.cylinders = [];
  16917. serializationObject.geometries.toruses = [];
  16918. serializationObject.geometries.grounds = [];
  16919. serializationObject.geometries.planes = [];
  16920. serializationObject.geometries.torusKnots = [];
  16921. serializationObject.geometries.vertexData = [];
  16922. serializedGeometries = [];
  16923. var geometries = scene.getGeometries();
  16924. for (var index = 0; index < geometries.length; index++) {
  16925. var geometry = geometries[index];
  16926. if (geometry.isReady()) {
  16927. serializeGeometry(geometry, serializationObject.geometries);
  16928. }
  16929. }
  16930. // Meshes
  16931. serializationObject.meshes = [];
  16932. for (index = 0; index < scene.meshes.length; index++) {
  16933. var abstractMesh = scene.meshes[index];
  16934. if (abstractMesh instanceof BABYLON.Mesh) {
  16935. var mesh = abstractMesh;
  16936. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16937. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16938. }
  16939. }
  16940. }
  16941. // Particles Systems
  16942. serializationObject.particleSystems = [];
  16943. for (index = 0; index < scene.particleSystems.length; index++) {
  16944. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16945. }
  16946. // Lens flares
  16947. serializationObject.lensFlareSystems = [];
  16948. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16949. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16950. }
  16951. // Shadows
  16952. serializationObject.shadowGenerators = [];
  16953. for (index = 0; index < scene.lights.length; index++) {
  16954. light = scene.lights[index];
  16955. if (light.getShadowGenerator()) {
  16956. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16957. }
  16958. }
  16959. return serializationObject;
  16960. };
  16961. return SceneSerializer;
  16962. })();
  16963. BABYLON.SceneSerializer = SceneSerializer;
  16964. })(BABYLON || (BABYLON = {}));
  16965. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16966. var BABYLON;
  16967. (function (BABYLON) {
  16968. var SceneLoader = (function () {
  16969. function SceneLoader() {
  16970. }
  16971. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16972. get: function () {
  16973. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16974. },
  16975. set: function (value) {
  16976. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16977. },
  16978. enumerable: true,
  16979. configurable: true
  16980. });
  16981. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16982. get: function () {
  16983. return SceneLoader._ShowLoadingScreen;
  16984. },
  16985. set: function (value) {
  16986. SceneLoader._ShowLoadingScreen = value;
  16987. },
  16988. enumerable: true,
  16989. configurable: true
  16990. });
  16991. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16992. var dotPosition = sceneFilename.lastIndexOf(".");
  16993. var queryStringPosition = sceneFilename.indexOf("?");
  16994. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16995. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16996. var plugin = this._registeredPlugins[index];
  16997. if (plugin.extensions.indexOf(extension) !== -1) {
  16998. return plugin;
  16999. }
  17000. }
  17001. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17002. };
  17003. // Public functions
  17004. SceneLoader.RegisterPlugin = function (plugin) {
  17005. plugin.extensions = plugin.extensions.toLowerCase();
  17006. SceneLoader._registeredPlugins.push(plugin);
  17007. };
  17008. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17009. var manifestChecked = function (success) {
  17010. scene.database = database;
  17011. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17012. var importMeshFromData = function (data) {
  17013. var meshes = [];
  17014. var particleSystems = [];
  17015. var skeletons = [];
  17016. try {
  17017. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17018. if (onerror) {
  17019. onerror(scene, 'unable to load the scene');
  17020. }
  17021. return;
  17022. }
  17023. } catch (e) {
  17024. if (onerror) {
  17025. onerror(scene, e);
  17026. }
  17027. return;
  17028. }
  17029. if (onsuccess) {
  17030. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17031. onsuccess(meshes, particleSystems, skeletons);
  17032. }
  17033. };
  17034. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17035. // Direct load
  17036. importMeshFromData(sceneFilename.substr(5));
  17037. return;
  17038. }
  17039. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17040. importMeshFromData(data);
  17041. }, progressCallBack, database);
  17042. };
  17043. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17044. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17045. };
  17046. /**
  17047. * Load a scene
  17048. * @param rootUrl a string that defines the root url for scene and resources
  17049. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17050. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17051. */
  17052. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17053. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17054. };
  17055. /**
  17056. * Append a scene
  17057. * @param rootUrl a string that defines the root url for scene and resources
  17058. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17059. * @param scene is the instance of BABYLON.Scene to append to
  17060. */
  17061. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17062. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17063. var database;
  17064. if (SceneLoader.ShowLoadingScreen) {
  17065. scene.getEngine().displayLoadingUI();
  17066. }
  17067. var loadSceneFromData = function (data) {
  17068. scene.database = database;
  17069. if (!plugin.load(scene, data, rootUrl)) {
  17070. if (onerror) {
  17071. onerror(scene);
  17072. }
  17073. scene.getEngine().hideLoadingUI();
  17074. return;
  17075. }
  17076. if (onsuccess) {
  17077. onsuccess(scene);
  17078. }
  17079. if (SceneLoader.ShowLoadingScreen) {
  17080. scene.executeWhenReady(function () {
  17081. scene.getEngine().hideLoadingUI();
  17082. });
  17083. }
  17084. };
  17085. var manifestChecked = function (success) {
  17086. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17087. };
  17088. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17089. // Direct load
  17090. loadSceneFromData(sceneFilename.substr(5));
  17091. return;
  17092. }
  17093. if (rootUrl.indexOf("file:") === -1) {
  17094. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17095. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17096. } else {
  17097. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17098. }
  17099. };
  17100. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17101. SceneLoader._ShowLoadingScreen = true;
  17102. SceneLoader._registeredPlugins = new Array();
  17103. return SceneLoader;
  17104. })();
  17105. BABYLON.SceneLoader = SceneLoader;
  17106. ;
  17107. })(BABYLON || (BABYLON = {}));
  17108. //# sourceMappingURL=babylon.sceneLoader.js.map
  17109. var BABYLON;
  17110. (function (BABYLON) {
  17111. (function (Internals) {
  17112. var checkColors4 = function (colors, count) {
  17113. // Check if color3 was used
  17114. if (colors.length === count * 3) {
  17115. var colors4 = [];
  17116. for (var index = 0; index < colors.length; index += 3) {
  17117. var newIndex = (index / 3) * 4;
  17118. colors4[newIndex] = colors[index];
  17119. colors4[newIndex + 1] = colors[index + 1];
  17120. colors4[newIndex + 2] = colors[index + 2];
  17121. colors4[newIndex + 3] = 1.0;
  17122. }
  17123. return colors4;
  17124. }
  17125. return colors;
  17126. };
  17127. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17128. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17129. texture.name = parsedTexture.name;
  17130. texture.hasAlpha = parsedTexture.hasAlpha;
  17131. texture.level = parsedTexture.level;
  17132. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17133. return texture;
  17134. };
  17135. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17136. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17137. return null;
  17138. }
  17139. if (parsedTexture.isCube) {
  17140. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17141. }
  17142. var texture;
  17143. if (parsedTexture.mirrorPlane) {
  17144. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17145. texture._waitingRenderList = parsedTexture.renderList;
  17146. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17147. } else if (parsedTexture.isRenderTarget) {
  17148. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17149. texture._waitingRenderList = parsedTexture.renderList;
  17150. } else {
  17151. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17152. }
  17153. texture.name = parsedTexture.name;
  17154. texture.hasAlpha = parsedTexture.hasAlpha;
  17155. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17156. texture.level = parsedTexture.level;
  17157. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17158. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17159. texture.uOffset = parsedTexture.uOffset;
  17160. texture.vOffset = parsedTexture.vOffset;
  17161. texture.uScale = parsedTexture.uScale;
  17162. texture.vScale = parsedTexture.vScale;
  17163. texture.uAng = parsedTexture.uAng;
  17164. texture.vAng = parsedTexture.vAng;
  17165. texture.wAng = parsedTexture.wAng;
  17166. texture.wrapU = parsedTexture.wrapU;
  17167. texture.wrapV = parsedTexture.wrapV;
  17168. // Animations
  17169. if (parsedTexture.animations) {
  17170. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17171. var parsedAnimation = parsedTexture.animations[animationIndex];
  17172. texture.animations.push(parseAnimation(parsedAnimation));
  17173. }
  17174. }
  17175. return texture;
  17176. };
  17177. var parseSkeleton = function (parsedSkeleton, scene) {
  17178. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17179. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17180. var parsedBone = parsedSkeleton.bones[index];
  17181. var parentBone = null;
  17182. if (parsedBone.parentBoneIndex > -1) {
  17183. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17184. }
  17185. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17186. if (parsedBone.animation) {
  17187. bone.animations.push(parseAnimation(parsedBone.animation));
  17188. }
  17189. }
  17190. return skeleton;
  17191. };
  17192. var parseFresnelParameters = function (parsedFresnelParameters) {
  17193. var fresnelParameters = new BABYLON.FresnelParameters();
  17194. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17195. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17196. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17197. fresnelParameters.bias = parsedFresnelParameters.bias;
  17198. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17199. return fresnelParameters;
  17200. };
  17201. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17202. var material;
  17203. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17204. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17205. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17206. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17207. material.specularPower = parsedMaterial.specularPower;
  17208. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17209. material.alpha = parsedMaterial.alpha;
  17210. material.id = parsedMaterial.id;
  17211. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17212. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17213. material.wireframe = parsedMaterial.wireframe;
  17214. if (parsedMaterial.diffuseTexture) {
  17215. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17216. }
  17217. if (parsedMaterial.diffuseFresnelParameters) {
  17218. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17219. }
  17220. if (parsedMaterial.ambientTexture) {
  17221. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17222. }
  17223. if (parsedMaterial.opacityTexture) {
  17224. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17225. }
  17226. if (parsedMaterial.opacityFresnelParameters) {
  17227. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17228. }
  17229. if (parsedMaterial.reflectionTexture) {
  17230. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17231. }
  17232. if (parsedMaterial.reflectionFresnelParameters) {
  17233. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17234. }
  17235. if (parsedMaterial.emissiveTexture) {
  17236. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17237. }
  17238. if (parsedMaterial.emissiveFresnelParameters) {
  17239. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17240. }
  17241. if (parsedMaterial.specularTexture) {
  17242. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17243. }
  17244. if (parsedMaterial.bumpTexture) {
  17245. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17246. }
  17247. return material;
  17248. };
  17249. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17250. for (var index = 0; index < parsedData.materials.length; index++) {
  17251. var parsedMaterial = parsedData.materials[index];
  17252. if (parsedMaterial.id === id) {
  17253. return parseMaterial(parsedMaterial, scene, rootUrl);
  17254. }
  17255. }
  17256. return null;
  17257. };
  17258. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17259. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17260. multiMaterial.id = parsedMultiMaterial.id;
  17261. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17262. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17263. var subMatId = parsedMultiMaterial.materials[matIndex];
  17264. if (subMatId) {
  17265. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17266. } else {
  17267. multiMaterial.subMaterials.push(null);
  17268. }
  17269. }
  17270. return multiMaterial;
  17271. };
  17272. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17273. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17274. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17275. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17276. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17277. var parsedFlare = parsedLensFlareSystem.flares[index];
  17278. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17279. }
  17280. return lensFlareSystem;
  17281. };
  17282. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17283. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17284. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17285. if (parsedParticleSystem.textureName) {
  17286. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17287. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17288. }
  17289. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17290. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17291. particleSystem.minSize = parsedParticleSystem.minSize;
  17292. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17293. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17294. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17295. particleSystem.emitter = emitter;
  17296. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17297. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17298. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17299. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17300. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17301. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17302. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17303. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17304. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17305. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17306. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17307. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17308. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17309. particleSystem.start();
  17310. return particleSystem;
  17311. };
  17312. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17313. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17314. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17315. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17316. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17317. shadowGenerator.getShadowMap().renderList.push(mesh);
  17318. }
  17319. if (parsedShadowGenerator.usePoissonSampling) {
  17320. shadowGenerator.usePoissonSampling = true;
  17321. } else {
  17322. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17323. }
  17324. return shadowGenerator;
  17325. };
  17326. var parseAnimation = function (parsedAnimation) {
  17327. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17328. var dataType = parsedAnimation.dataType;
  17329. var keys = [];
  17330. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17331. var key = parsedAnimation.keys[index];
  17332. var data;
  17333. switch (dataType) {
  17334. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17335. data = key.values[0];
  17336. break;
  17337. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17338. data = BABYLON.Quaternion.FromArray(key.values);
  17339. break;
  17340. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17341. data = BABYLON.Matrix.FromArray(key.values);
  17342. break;
  17343. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17344. default:
  17345. data = BABYLON.Vector3.FromArray(key.values);
  17346. break;
  17347. }
  17348. keys.push({
  17349. frame: key.frame,
  17350. value: data
  17351. });
  17352. }
  17353. animation.setKeys(keys);
  17354. return animation;
  17355. };
  17356. var parseLight = function (parsedLight, scene) {
  17357. var light;
  17358. switch (parsedLight.type) {
  17359. case 0:
  17360. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17361. break;
  17362. case 1:
  17363. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17364. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17365. break;
  17366. case 2:
  17367. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17368. break;
  17369. case 3:
  17370. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17371. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17372. break;
  17373. }
  17374. light.id = parsedLight.id;
  17375. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17376. if (parsedLight.intensity !== undefined) {
  17377. light.intensity = parsedLight.intensity;
  17378. }
  17379. if (parsedLight.range) {
  17380. light.range = parsedLight.range;
  17381. }
  17382. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17383. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17384. if (parsedLight.excludedMeshesIds) {
  17385. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17386. }
  17387. // Parent
  17388. if (parsedLight.parentId) {
  17389. light._waitingParentId = parsedLight.parentId;
  17390. }
  17391. if (parsedLight.includedOnlyMeshesIds) {
  17392. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17393. }
  17394. // Animations
  17395. if (parsedLight.animations) {
  17396. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17397. var parsedAnimation = parsedLight.animations[animationIndex];
  17398. light.animations.push(parseAnimation(parsedAnimation));
  17399. }
  17400. }
  17401. if (parsedLight.autoAnimate) {
  17402. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17403. }
  17404. };
  17405. var parseCamera = function (parsedCamera, scene) {
  17406. var camera;
  17407. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17408. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17409. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17410. var alpha = parsedCamera.alpha;
  17411. var beta = parsedCamera.beta;
  17412. var radius = parsedCamera.radius;
  17413. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17414. var eye_space = parsedCamera.eye_space;
  17415. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17416. } else {
  17417. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17418. }
  17419. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17420. var eye_space = parsedCamera.eye_space;
  17421. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17422. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17423. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17424. } else if (parsedCamera.type === "FollowCamera") {
  17425. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17426. camera.heightOffset = parsedCamera.heightOffset;
  17427. camera.radius = parsedCamera.radius;
  17428. camera.rotationOffset = parsedCamera.rotationOffset;
  17429. if (lockedTargetMesh)
  17430. camera.target = lockedTargetMesh;
  17431. } else if (parsedCamera.type === "GamepadCamera") {
  17432. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17433. } else if (parsedCamera.type === "OculusCamera") {
  17434. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17435. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17436. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17437. } else if (parsedCamera.type === "TouchCamera") {
  17438. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17439. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17440. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17441. } else if (parsedCamera.type === "WebVRCamera") {
  17442. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17443. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17444. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17445. } else {
  17446. // Free Camera is the default value
  17447. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17448. }
  17449. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17450. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17451. camera.lockedTarget = lockedTargetMesh;
  17452. }
  17453. camera.id = parsedCamera.id;
  17454. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17455. // Parent
  17456. if (parsedCamera.parentId) {
  17457. camera._waitingParentId = parsedCamera.parentId;
  17458. }
  17459. // Target
  17460. if (parsedCamera.target) {
  17461. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17462. } else {
  17463. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17464. }
  17465. camera.fov = parsedCamera.fov;
  17466. camera.minZ = parsedCamera.minZ;
  17467. camera.maxZ = parsedCamera.maxZ;
  17468. camera.speed = parsedCamera.speed;
  17469. camera.inertia = parsedCamera.inertia;
  17470. camera.checkCollisions = parsedCamera.checkCollisions;
  17471. camera.applyGravity = parsedCamera.applyGravity;
  17472. if (parsedCamera.ellipsoid) {
  17473. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17474. }
  17475. // Animations
  17476. if (parsedCamera.animations) {
  17477. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17478. var parsedAnimation = parsedCamera.animations[animationIndex];
  17479. camera.animations.push(parseAnimation(parsedAnimation));
  17480. }
  17481. }
  17482. if (parsedCamera.autoAnimate) {
  17483. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17484. }
  17485. // Layer Mask
  17486. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17487. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17488. } else {
  17489. camera.layerMask = 0xFFFFFFFF;
  17490. }
  17491. return camera;
  17492. };
  17493. var parseGeometry = function (parsedGeometry, scene) {
  17494. var id = parsedGeometry.id;
  17495. return scene.getGeometryByID(id);
  17496. };
  17497. var parseBox = function (parsedBox, scene) {
  17498. if (parseGeometry(parsedBox, scene)) {
  17499. return null;
  17500. }
  17501. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17502. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17503. scene.pushGeometry(box, true);
  17504. return box;
  17505. };
  17506. var parseSphere = function (parsedSphere, scene) {
  17507. if (parseGeometry(parsedSphere, scene)) {
  17508. return null;
  17509. }
  17510. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17511. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17512. scene.pushGeometry(sphere, true);
  17513. return sphere;
  17514. };
  17515. var parseCylinder = function (parsedCylinder, scene) {
  17516. if (parseGeometry(parsedCylinder, scene)) {
  17517. return null;
  17518. }
  17519. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17520. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17521. scene.pushGeometry(cylinder, true);
  17522. return cylinder;
  17523. };
  17524. var parseTorus = function (parsedTorus, scene) {
  17525. if (parseGeometry(parsedTorus, scene)) {
  17526. return null;
  17527. }
  17528. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17529. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17530. scene.pushGeometry(torus, true);
  17531. return torus;
  17532. };
  17533. var parseGround = function (parsedGround, scene) {
  17534. if (parseGeometry(parsedGround, scene)) {
  17535. return null;
  17536. }
  17537. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17538. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17539. scene.pushGeometry(ground, true);
  17540. return ground;
  17541. };
  17542. var parsePlane = function (parsedPlane, scene) {
  17543. if (parseGeometry(parsedPlane, scene)) {
  17544. return null;
  17545. }
  17546. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17547. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17548. scene.pushGeometry(plane, true);
  17549. return plane;
  17550. };
  17551. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17552. if (parseGeometry(parsedTorusKnot, scene)) {
  17553. return null;
  17554. }
  17555. 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);
  17556. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17557. scene.pushGeometry(torusKnot, true);
  17558. return torusKnot;
  17559. };
  17560. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17561. if (parseGeometry(parsedVertexData, scene)) {
  17562. return null;
  17563. }
  17564. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17565. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17566. if (parsedVertexData.delayLoadingFile) {
  17567. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17568. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17569. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17570. geometry._delayInfo = [];
  17571. if (parsedVertexData.hasUVs) {
  17572. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17573. }
  17574. if (parsedVertexData.hasUVs2) {
  17575. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17576. }
  17577. if (parsedVertexData.hasColors) {
  17578. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17579. }
  17580. if (parsedVertexData.hasMatricesIndices) {
  17581. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17582. }
  17583. if (parsedVertexData.hasMatricesWeights) {
  17584. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17585. }
  17586. geometry._delayLoadingFunction = importVertexData;
  17587. } else {
  17588. importVertexData(parsedVertexData, geometry);
  17589. }
  17590. scene.pushGeometry(geometry, true);
  17591. return geometry;
  17592. };
  17593. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17594. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17595. mesh.id = parsedMesh.id;
  17596. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17597. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17598. if (parsedMesh.rotationQuaternion) {
  17599. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17600. } else if (parsedMesh.rotation) {
  17601. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17602. }
  17603. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17604. if (parsedMesh.localMatrix) {
  17605. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17606. } else if (parsedMesh.pivotMatrix) {
  17607. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17608. }
  17609. mesh.setEnabled(parsedMesh.isEnabled);
  17610. mesh.isVisible = parsedMesh.isVisible;
  17611. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17612. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17613. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17614. if (parsedMesh.applyFog !== undefined) {
  17615. mesh.applyFog = parsedMesh.applyFog;
  17616. }
  17617. if (parsedMesh.pickable !== undefined) {
  17618. mesh.isPickable = parsedMesh.pickable;
  17619. }
  17620. if (parsedMesh.alphaIndex !== undefined) {
  17621. mesh.alphaIndex = parsedMesh.alphaIndex;
  17622. }
  17623. mesh.receiveShadows = parsedMesh.receiveShadows;
  17624. mesh.billboardMode = parsedMesh.billboardMode;
  17625. if (parsedMesh.visibility !== undefined) {
  17626. mesh.visibility = parsedMesh.visibility;
  17627. }
  17628. mesh.checkCollisions = parsedMesh.checkCollisions;
  17629. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17630. // Parent
  17631. if (parsedMesh.parentId) {
  17632. mesh._waitingParentId = parsedMesh.parentId;
  17633. }
  17634. // Geometry
  17635. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17636. if (parsedMesh.delayLoadingFile) {
  17637. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17638. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17639. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17640. if (parsedMesh._binaryInfo) {
  17641. mesh._binaryInfo = parsedMesh._binaryInfo;
  17642. }
  17643. mesh._delayInfo = [];
  17644. if (parsedMesh.hasUVs) {
  17645. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17646. }
  17647. if (parsedMesh.hasUVs2) {
  17648. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17649. }
  17650. if (parsedMesh.hasColors) {
  17651. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17652. }
  17653. if (parsedMesh.hasMatricesIndices) {
  17654. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17655. }
  17656. if (parsedMesh.hasMatricesWeights) {
  17657. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17658. }
  17659. mesh._delayLoadingFunction = importGeometry;
  17660. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17661. mesh._checkDelayState();
  17662. }
  17663. } else {
  17664. importGeometry(parsedMesh, mesh);
  17665. }
  17666. // Material
  17667. if (parsedMesh.materialId) {
  17668. mesh.setMaterialByID(parsedMesh.materialId);
  17669. } else {
  17670. mesh.material = null;
  17671. }
  17672. // Skeleton
  17673. if (parsedMesh.skeletonId > -1) {
  17674. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17675. }
  17676. // Physics
  17677. if (parsedMesh.physicsImpostor) {
  17678. if (!scene.isPhysicsEnabled()) {
  17679. scene.enablePhysics();
  17680. }
  17681. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17682. }
  17683. // Animations
  17684. if (parsedMesh.animations) {
  17685. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17686. var parsedAnimation = parsedMesh.animations[animationIndex];
  17687. mesh.animations.push(parseAnimation(parsedAnimation));
  17688. }
  17689. }
  17690. if (parsedMesh.autoAnimate) {
  17691. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17692. }
  17693. // Layer Mask
  17694. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17695. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17696. } else {
  17697. mesh.layerMask = 0xFFFFFFFF;
  17698. }
  17699. // Instances
  17700. if (parsedMesh.instances) {
  17701. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17702. var parsedInstance = parsedMesh.instances[index];
  17703. var instance = mesh.createInstance(parsedInstance.name);
  17704. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17705. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17706. if (parsedInstance.rotationQuaternion) {
  17707. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17708. } else if (parsedInstance.rotation) {
  17709. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17710. }
  17711. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17712. instance.checkCollisions = mesh.checkCollisions;
  17713. if (parsedMesh.animations) {
  17714. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17715. parsedAnimation = parsedMesh.animations[animationIndex];
  17716. instance.animations.push(parseAnimation(parsedAnimation));
  17717. }
  17718. }
  17719. }
  17720. }
  17721. return mesh;
  17722. };
  17723. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17724. names = (names instanceof Array) ? names : [names];
  17725. for (var i in names) {
  17726. if (mesh.name === names[i]) {
  17727. hierarchyIds.push(mesh.id);
  17728. return true;
  17729. }
  17730. }
  17731. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17732. hierarchyIds.push(mesh.id);
  17733. return true;
  17734. }
  17735. return false;
  17736. };
  17737. var importVertexData = function (parsedVertexData, geometry) {
  17738. var vertexData = new BABYLON.VertexData();
  17739. // positions
  17740. var positions = parsedVertexData.positions;
  17741. if (positions) {
  17742. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17743. }
  17744. // normals
  17745. var normals = parsedVertexData.normals;
  17746. if (normals) {
  17747. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17748. }
  17749. // uvs
  17750. var uvs = parsedVertexData.uvs;
  17751. if (uvs) {
  17752. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17753. }
  17754. // uv2s
  17755. var uv2s = parsedVertexData.uv2s;
  17756. if (uv2s) {
  17757. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17758. }
  17759. // colors
  17760. var colors = parsedVertexData.colors;
  17761. if (colors) {
  17762. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17763. }
  17764. // matricesIndices
  17765. var matricesIndices = parsedVertexData.matricesIndices;
  17766. if (matricesIndices) {
  17767. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17768. }
  17769. // matricesWeights
  17770. var matricesWeights = parsedVertexData.matricesWeights;
  17771. if (matricesWeights) {
  17772. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17773. }
  17774. // indices
  17775. var indices = parsedVertexData.indices;
  17776. if (indices) {
  17777. vertexData.indices = indices;
  17778. }
  17779. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17780. };
  17781. var importGeometry = function (parsedGeometry, mesh) {
  17782. var scene = mesh.getScene();
  17783. // Geometry
  17784. var geometryId = parsedGeometry.geometryId;
  17785. if (geometryId) {
  17786. var geometry = scene.getGeometryByID(geometryId);
  17787. if (geometry) {
  17788. geometry.applyToMesh(mesh);
  17789. }
  17790. } else if (parsedGeometry instanceof ArrayBuffer) {
  17791. var binaryInfo = mesh._binaryInfo;
  17792. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17793. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17794. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17795. }
  17796. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17797. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17798. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17799. }
  17800. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17801. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17802. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17803. }
  17804. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17805. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17806. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17807. }
  17808. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17809. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17810. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17811. }
  17812. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17813. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17815. }
  17816. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17817. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17818. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17819. }
  17820. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17821. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17822. mesh.setIndices(indicesData);
  17823. }
  17824. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17825. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17826. mesh.subMeshes = [];
  17827. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17828. var materialIndex = subMeshesData[(i * 5) + 0];
  17829. var verticesStart = subMeshesData[(i * 5) + 1];
  17830. var verticesCount = subMeshesData[(i * 5) + 2];
  17831. var indexStart = subMeshesData[(i * 5) + 3];
  17832. var indexCount = subMeshesData[(i * 5) + 4];
  17833. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17834. }
  17835. }
  17836. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17837. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17838. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17839. if (parsedGeometry.uvs) {
  17840. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17841. }
  17842. if (parsedGeometry.uvs2) {
  17843. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17844. }
  17845. if (parsedGeometry.colors) {
  17846. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17847. }
  17848. if (parsedGeometry.matricesIndices) {
  17849. if (!parsedGeometry.matricesIndices._isExpanded) {
  17850. var floatIndices = [];
  17851. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17852. var matricesIndex = parsedGeometry.matricesIndices[i];
  17853. floatIndices.push(matricesIndex & 0x000000FF);
  17854. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17855. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17856. floatIndices.push(matricesIndex >> 24);
  17857. }
  17858. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17859. } else {
  17860. delete parsedGeometry.matricesIndices._isExpanded;
  17861. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17862. }
  17863. }
  17864. if (parsedGeometry.matricesWeights) {
  17865. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17866. }
  17867. mesh.setIndices(parsedGeometry.indices);
  17868. // SubMeshes
  17869. if (parsedGeometry.subMeshes) {
  17870. mesh.subMeshes = [];
  17871. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17872. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17873. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17874. }
  17875. }
  17876. }
  17877. // Flat shading
  17878. if (mesh._shouldGenerateFlatShading) {
  17879. mesh.convertToFlatShadedMesh();
  17880. delete mesh._shouldGenerateFlatShading;
  17881. }
  17882. // Update
  17883. mesh.computeWorldMatrix(true);
  17884. // Octree
  17885. if (scene._selectionOctree) {
  17886. scene._selectionOctree.addMesh(mesh);
  17887. }
  17888. };
  17889. BABYLON.SceneLoader.RegisterPlugin({
  17890. extensions: ".babylon",
  17891. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17892. var parsedData = JSON.parse(data);
  17893. var loadedSkeletonsIds = [];
  17894. var loadedMaterialsIds = [];
  17895. var hierarchyIds = [];
  17896. for (var index = 0; index < parsedData.meshes.length; index++) {
  17897. var parsedMesh = parsedData.meshes[index];
  17898. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17899. if (meshesNames instanceof Array) {
  17900. // Remove found mesh name from list.
  17901. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17902. }
  17903. // Material ?
  17904. if (parsedMesh.materialId) {
  17905. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17906. if (!materialFound) {
  17907. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17908. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17909. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17910. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17911. var subMatId = parsedMultiMaterial.materials[matIndex];
  17912. loadedMaterialsIds.push(subMatId);
  17913. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17914. }
  17915. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17916. parseMultiMaterial(parsedMultiMaterial, scene);
  17917. materialFound = true;
  17918. break;
  17919. }
  17920. }
  17921. }
  17922. if (!materialFound) {
  17923. loadedMaterialsIds.push(parsedMesh.materialId);
  17924. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17925. }
  17926. }
  17927. // Skeleton ?
  17928. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17929. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17930. if (!skeletonAlreadyLoaded) {
  17931. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17932. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17933. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17934. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17935. loadedSkeletonsIds.push(parsedSkeleton.id);
  17936. }
  17937. }
  17938. }
  17939. }
  17940. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17941. meshes.push(mesh);
  17942. }
  17943. }
  17944. for (index = 0; index < scene.meshes.length; index++) {
  17945. var currentMesh = scene.meshes[index];
  17946. if (currentMesh._waitingParentId) {
  17947. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17948. currentMesh._waitingParentId = undefined;
  17949. }
  17950. }
  17951. // Particles
  17952. if (parsedData.particleSystems) {
  17953. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17954. var parsedParticleSystem = parsedData.particleSystems[index];
  17955. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17956. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17957. }
  17958. }
  17959. }
  17960. return true;
  17961. },
  17962. load: function (scene, data, rootUrl) {
  17963. var parsedData = JSON.parse(data);
  17964. // Scene
  17965. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17966. scene.autoClear = parsedData.autoClear;
  17967. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17968. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17969. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17970. // Fog
  17971. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17972. scene.fogMode = parsedData.fogMode;
  17973. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17974. scene.fogStart = parsedData.fogStart;
  17975. scene.fogEnd = parsedData.fogEnd;
  17976. scene.fogDensity = parsedData.fogDensity;
  17977. }
  17978. for (var index = 0; index < parsedData.lights.length; index++) {
  17979. var parsedLight = parsedData.lights[index];
  17980. parseLight(parsedLight, scene);
  17981. }
  17982. // Materials
  17983. if (parsedData.materials) {
  17984. for (index = 0; index < parsedData.materials.length; index++) {
  17985. var parsedMaterial = parsedData.materials[index];
  17986. parseMaterial(parsedMaterial, scene, rootUrl);
  17987. }
  17988. }
  17989. if (parsedData.multiMaterials) {
  17990. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17991. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17992. parseMultiMaterial(parsedMultiMaterial, scene);
  17993. }
  17994. }
  17995. // Skeletons
  17996. if (parsedData.skeletons) {
  17997. for (index = 0; index < parsedData.skeletons.length; index++) {
  17998. var parsedSkeleton = parsedData.skeletons[index];
  17999. parseSkeleton(parsedSkeleton, scene);
  18000. }
  18001. }
  18002. // Geometries
  18003. var geometries = parsedData.geometries;
  18004. if (geometries) {
  18005. // Boxes
  18006. var boxes = geometries.boxes;
  18007. if (boxes) {
  18008. for (index = 0; index < boxes.length; index++) {
  18009. var parsedBox = boxes[index];
  18010. parseBox(parsedBox, scene);
  18011. }
  18012. }
  18013. // Spheres
  18014. var spheres = geometries.spheres;
  18015. if (spheres) {
  18016. for (index = 0; index < spheres.length; index++) {
  18017. var parsedSphere = spheres[index];
  18018. parseSphere(parsedSphere, scene);
  18019. }
  18020. }
  18021. // Cylinders
  18022. var cylinders = geometries.cylinders;
  18023. if (cylinders) {
  18024. for (index = 0; index < cylinders.length; index++) {
  18025. var parsedCylinder = cylinders[index];
  18026. parseCylinder(parsedCylinder, scene);
  18027. }
  18028. }
  18029. // Toruses
  18030. var toruses = geometries.toruses;
  18031. if (toruses) {
  18032. for (index = 0; index < toruses.length; index++) {
  18033. var parsedTorus = toruses[index];
  18034. parseTorus(parsedTorus, scene);
  18035. }
  18036. }
  18037. // Grounds
  18038. var grounds = geometries.grounds;
  18039. if (grounds) {
  18040. for (index = 0; index < grounds.length; index++) {
  18041. var parsedGround = grounds[index];
  18042. parseGround(parsedGround, scene);
  18043. }
  18044. }
  18045. // Planes
  18046. var planes = geometries.planes;
  18047. if (planes) {
  18048. for (index = 0; index < planes.length; index++) {
  18049. var parsedPlane = planes[index];
  18050. parsePlane(parsedPlane, scene);
  18051. }
  18052. }
  18053. // TorusKnots
  18054. var torusKnots = geometries.torusKnots;
  18055. if (torusKnots) {
  18056. for (index = 0; index < torusKnots.length; index++) {
  18057. var parsedTorusKnot = torusKnots[index];
  18058. parseTorusKnot(parsedTorusKnot, scene);
  18059. }
  18060. }
  18061. // VertexData
  18062. var vertexData = geometries.vertexData;
  18063. if (vertexData) {
  18064. for (index = 0; index < vertexData.length; index++) {
  18065. var parsedVertexData = vertexData[index];
  18066. parseVertexData(parsedVertexData, scene, rootUrl);
  18067. }
  18068. }
  18069. }
  18070. for (index = 0; index < parsedData.meshes.length; index++) {
  18071. var parsedMesh = parsedData.meshes[index];
  18072. parseMesh(parsedMesh, scene, rootUrl);
  18073. }
  18074. for (index = 0; index < parsedData.cameras.length; index++) {
  18075. var parsedCamera = parsedData.cameras[index];
  18076. parseCamera(parsedCamera, scene);
  18077. }
  18078. if (parsedData.activeCameraID) {
  18079. scene.setActiveCameraByID(parsedData.activeCameraID);
  18080. }
  18081. for (index = 0; index < scene.cameras.length; index++) {
  18082. var camera = scene.cameras[index];
  18083. if (camera._waitingParentId) {
  18084. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18085. camera._waitingParentId = undefined;
  18086. }
  18087. }
  18088. for (index = 0; index < scene.lights.length; index++) {
  18089. var light = scene.lights[index];
  18090. if (light._waitingParentId) {
  18091. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18092. light._waitingParentId = undefined;
  18093. }
  18094. }
  18095. for (index = 0; index < scene.meshes.length; index++) {
  18096. var mesh = scene.meshes[index];
  18097. if (mesh._waitingParentId) {
  18098. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18099. mesh._waitingParentId = undefined;
  18100. }
  18101. }
  18102. // Particles Systems
  18103. if (parsedData.particleSystems) {
  18104. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18105. var parsedParticleSystem = parsedData.particleSystems[index];
  18106. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18107. }
  18108. }
  18109. // Lens flares
  18110. if (parsedData.lensFlareSystems) {
  18111. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18112. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18113. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18114. }
  18115. }
  18116. // Shadows
  18117. if (parsedData.shadowGenerators) {
  18118. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18119. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18120. parseShadowGenerator(parsedShadowGenerator, scene);
  18121. }
  18122. }
  18123. // Finish
  18124. return true;
  18125. }
  18126. });
  18127. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18128. var Internals = BABYLON.Internals;
  18129. })(BABYLON || (BABYLON = {}));
  18130. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18131. var BABYLON;
  18132. (function (BABYLON) {
  18133. // Unique ID when we import meshes from Babylon to CSG
  18134. var currentCSGMeshId = 0;
  18135. // # class Vertex
  18136. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18137. // one to provide additional features like texture coordinates and vertex
  18138. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18139. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18140. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18141. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18142. // is not used anywhere else.
  18143. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18144. var Vertex = (function () {
  18145. function Vertex(pos, normal, uv) {
  18146. this.pos = pos;
  18147. this.normal = normal;
  18148. this.uv = uv;
  18149. }
  18150. Vertex.prototype.clone = function () {
  18151. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18152. };
  18153. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18154. // orientation of a polygon is flipped.
  18155. Vertex.prototype.flip = function () {
  18156. this.normal = this.normal.scale(-1);
  18157. };
  18158. // Create a new vertex between this vertex and `other` by linearly
  18159. // interpolating all properties using a parameter of `t`. Subclasses should
  18160. // override this to interpolate additional properties.
  18161. Vertex.prototype.interpolate = function (other, t) {
  18162. 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));
  18163. };
  18164. return Vertex;
  18165. })();
  18166. // # class Plane
  18167. // Represents a plane in 3D space.
  18168. var Plane = (function () {
  18169. function Plane(normal, w) {
  18170. this.normal = normal;
  18171. this.w = w;
  18172. }
  18173. Plane.FromPoints = function (a, b, c) {
  18174. var v0 = c.subtract(a);
  18175. var v1 = b.subtract(a);
  18176. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18177. return null;
  18178. }
  18179. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18180. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18181. };
  18182. Plane.prototype.clone = function () {
  18183. return new Plane(this.normal.clone(), this.w);
  18184. };
  18185. Plane.prototype.flip = function () {
  18186. this.normal.scaleInPlace(-1);
  18187. this.w = -this.w;
  18188. };
  18189. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18190. // fragments in the appropriate lists. Coplanar polygons go into either
  18191. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18192. // respect to this plane. Polygons in front or in back of this plane go into
  18193. // either `front` or `back`.
  18194. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18195. var COPLANAR = 0;
  18196. var FRONT = 1;
  18197. var BACK = 2;
  18198. var SPANNING = 3;
  18199. // Classify each point as well as the entire polygon into one of the above
  18200. // four classes.
  18201. var polygonType = 0;
  18202. var types = [];
  18203. for (var i = 0; i < polygon.vertices.length; i++) {
  18204. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18205. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18206. polygonType |= type;
  18207. types.push(type);
  18208. }
  18209. switch (polygonType) {
  18210. case COPLANAR:
  18211. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18212. break;
  18213. case FRONT:
  18214. front.push(polygon);
  18215. break;
  18216. case BACK:
  18217. back.push(polygon);
  18218. break;
  18219. case SPANNING:
  18220. var f = [], b = [];
  18221. for (i = 0; i < polygon.vertices.length; i++) {
  18222. var j = (i + 1) % polygon.vertices.length;
  18223. var ti = types[i], tj = types[j];
  18224. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18225. if (ti != BACK)
  18226. f.push(vi);
  18227. if (ti != FRONT)
  18228. b.push(ti != BACK ? vi.clone() : vi);
  18229. if ((ti | tj) == SPANNING) {
  18230. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18231. var v = vi.interpolate(vj, t);
  18232. f.push(v);
  18233. b.push(v.clone());
  18234. }
  18235. }
  18236. if (f.length >= 3) {
  18237. var poly = new Polygon(f, polygon.shared);
  18238. if (poly.plane)
  18239. front.push(poly);
  18240. }
  18241. if (b.length >= 3) {
  18242. poly = new Polygon(b, polygon.shared);
  18243. if (poly.plane)
  18244. back.push(poly);
  18245. }
  18246. break;
  18247. }
  18248. };
  18249. Plane.EPSILON = 1e-5;
  18250. return Plane;
  18251. })();
  18252. // # class Polygon
  18253. // Represents a convex polygon. The vertices used to initialize a polygon must
  18254. // be coplanar and form a convex loop.
  18255. //
  18256. // Each convex polygon has a `shared` property, which is shared between all
  18257. // polygons that are clones of each other or were split from the same polygon.
  18258. // This can be used to define per-polygon properties (such as surface color).
  18259. var Polygon = (function () {
  18260. function Polygon(vertices, shared) {
  18261. this.vertices = vertices;
  18262. this.shared = shared;
  18263. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18264. }
  18265. Polygon.prototype.clone = function () {
  18266. var vertices = this.vertices.map(function (v) {
  18267. return v.clone();
  18268. });
  18269. return new Polygon(vertices, this.shared);
  18270. };
  18271. Polygon.prototype.flip = function () {
  18272. this.vertices.reverse().map(function (v) {
  18273. v.flip();
  18274. });
  18275. this.plane.flip();
  18276. };
  18277. return Polygon;
  18278. })();
  18279. // # class Node
  18280. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18281. // by picking a polygon to split along. That polygon (and all other coplanar
  18282. // polygons) are added directly to that node and the other polygons are added to
  18283. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18284. // no distinction between internal and leaf nodes.
  18285. var Node = (function () {
  18286. function Node(polygons) {
  18287. this.plane = null;
  18288. this.front = null;
  18289. this.back = null;
  18290. this.polygons = [];
  18291. if (polygons) {
  18292. this.build(polygons);
  18293. }
  18294. }
  18295. Node.prototype.clone = function () {
  18296. var node = new Node();
  18297. node.plane = this.plane && this.plane.clone();
  18298. node.front = this.front && this.front.clone();
  18299. node.back = this.back && this.back.clone();
  18300. node.polygons = this.polygons.map(function (p) {
  18301. return p.clone();
  18302. });
  18303. return node;
  18304. };
  18305. // Convert solid space to empty space and empty space to solid space.
  18306. Node.prototype.invert = function () {
  18307. for (var i = 0; i < this.polygons.length; i++) {
  18308. this.polygons[i].flip();
  18309. }
  18310. if (this.plane) {
  18311. this.plane.flip();
  18312. }
  18313. if (this.front) {
  18314. this.front.invert();
  18315. }
  18316. if (this.back) {
  18317. this.back.invert();
  18318. }
  18319. var temp = this.front;
  18320. this.front = this.back;
  18321. this.back = temp;
  18322. };
  18323. // Recursively remove all polygons in `polygons` that are inside this BSP
  18324. // tree.
  18325. Node.prototype.clipPolygons = function (polygons) {
  18326. if (!this.plane)
  18327. return polygons.slice();
  18328. var front = [], back = [];
  18329. for (var i = 0; i < polygons.length; i++) {
  18330. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18331. }
  18332. if (this.front) {
  18333. front = this.front.clipPolygons(front);
  18334. }
  18335. if (this.back) {
  18336. back = this.back.clipPolygons(back);
  18337. } else {
  18338. back = [];
  18339. }
  18340. return front.concat(back);
  18341. };
  18342. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18343. // `bsp`.
  18344. Node.prototype.clipTo = function (bsp) {
  18345. this.polygons = bsp.clipPolygons(this.polygons);
  18346. if (this.front)
  18347. this.front.clipTo(bsp);
  18348. if (this.back)
  18349. this.back.clipTo(bsp);
  18350. };
  18351. // Return a list of all polygons in this BSP tree.
  18352. Node.prototype.allPolygons = function () {
  18353. var polygons = this.polygons.slice();
  18354. if (this.front)
  18355. polygons = polygons.concat(this.front.allPolygons());
  18356. if (this.back)
  18357. polygons = polygons.concat(this.back.allPolygons());
  18358. return polygons;
  18359. };
  18360. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18361. // new polygons are filtered down to the bottom of the tree and become new
  18362. // nodes there. Each set of polygons is partitioned using the first polygon
  18363. // (no heuristic is used to pick a good split).
  18364. Node.prototype.build = function (polygons) {
  18365. if (!polygons.length)
  18366. return;
  18367. if (!this.plane)
  18368. this.plane = polygons[0].plane.clone();
  18369. var front = [], back = [];
  18370. for (var i = 0; i < polygons.length; i++) {
  18371. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18372. }
  18373. if (front.length) {
  18374. if (!this.front)
  18375. this.front = new Node();
  18376. this.front.build(front);
  18377. }
  18378. if (back.length) {
  18379. if (!this.back)
  18380. this.back = new Node();
  18381. this.back.build(back);
  18382. }
  18383. };
  18384. return Node;
  18385. })();
  18386. var CSG = (function () {
  18387. function CSG() {
  18388. this.polygons = new Array();
  18389. }
  18390. // Convert BABYLON.Mesh to BABYLON.CSG
  18391. CSG.FromMesh = function (mesh) {
  18392. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18393. if (mesh instanceof BABYLON.Mesh) {
  18394. mesh.computeWorldMatrix(true);
  18395. var matrix = mesh.getWorldMatrix();
  18396. var meshPosition = mesh.position.clone();
  18397. var meshRotation = mesh.rotation.clone();
  18398. var meshScaling = mesh.scaling.clone();
  18399. } else {
  18400. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18401. }
  18402. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18403. var subMeshes = mesh.subMeshes;
  18404. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18405. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18406. vertices = [];
  18407. for (var j = 0; j < 3; j++) {
  18408. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18409. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18410. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18411. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18412. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18413. vertex = new Vertex(position, normal, uv);
  18414. vertices.push(vertex);
  18415. }
  18416. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18417. // To handle the case of degenerated triangle
  18418. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18419. if (polygon.plane)
  18420. polygons.push(polygon);
  18421. }
  18422. }
  18423. var csg = CSG.FromPolygons(polygons);
  18424. csg.matrix = matrix;
  18425. csg.position = meshPosition;
  18426. csg.rotation = meshRotation;
  18427. csg.scaling = meshScaling;
  18428. currentCSGMeshId++;
  18429. return csg;
  18430. };
  18431. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18432. CSG.FromPolygons = function (polygons) {
  18433. var csg = new BABYLON.CSG();
  18434. csg.polygons = polygons;
  18435. return csg;
  18436. };
  18437. CSG.prototype.clone = function () {
  18438. var csg = new BABYLON.CSG();
  18439. csg.polygons = this.polygons.map(function (p) {
  18440. return p.clone();
  18441. });
  18442. csg.copyTransformAttributes(this);
  18443. return csg;
  18444. };
  18445. CSG.prototype.toPolygons = function () {
  18446. return this.polygons;
  18447. };
  18448. CSG.prototype.union = function (csg) {
  18449. var a = new Node(this.clone().polygons);
  18450. var b = new Node(csg.clone().polygons);
  18451. a.clipTo(b);
  18452. b.clipTo(a);
  18453. b.invert();
  18454. b.clipTo(a);
  18455. b.invert();
  18456. a.build(b.allPolygons());
  18457. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18458. };
  18459. CSG.prototype.unionInPlace = function (csg) {
  18460. var a = new Node(this.polygons);
  18461. var b = new Node(csg.polygons);
  18462. a.clipTo(b);
  18463. b.clipTo(a);
  18464. b.invert();
  18465. b.clipTo(a);
  18466. b.invert();
  18467. a.build(b.allPolygons());
  18468. this.polygons = a.allPolygons();
  18469. };
  18470. CSG.prototype.subtract = function (csg) {
  18471. var a = new Node(this.clone().polygons);
  18472. var b = new Node(csg.clone().polygons);
  18473. a.invert();
  18474. a.clipTo(b);
  18475. b.clipTo(a);
  18476. b.invert();
  18477. b.clipTo(a);
  18478. b.invert();
  18479. a.build(b.allPolygons());
  18480. a.invert();
  18481. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18482. };
  18483. CSG.prototype.subtractInPlace = function (csg) {
  18484. var a = new Node(this.polygons);
  18485. var b = new Node(csg.polygons);
  18486. a.invert();
  18487. a.clipTo(b);
  18488. b.clipTo(a);
  18489. b.invert();
  18490. b.clipTo(a);
  18491. b.invert();
  18492. a.build(b.allPolygons());
  18493. a.invert();
  18494. this.polygons = a.allPolygons();
  18495. };
  18496. CSG.prototype.intersect = function (csg) {
  18497. var a = new Node(this.clone().polygons);
  18498. var b = new Node(csg.clone().polygons);
  18499. a.invert();
  18500. b.clipTo(a);
  18501. b.invert();
  18502. a.clipTo(b);
  18503. b.clipTo(a);
  18504. a.build(b.allPolygons());
  18505. a.invert();
  18506. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18507. };
  18508. CSG.prototype.intersectInPlace = function (csg) {
  18509. var a = new Node(this.polygons);
  18510. var b = new Node(csg.polygons);
  18511. a.invert();
  18512. b.clipTo(a);
  18513. b.invert();
  18514. a.clipTo(b);
  18515. b.clipTo(a);
  18516. a.build(b.allPolygons());
  18517. a.invert();
  18518. this.polygons = a.allPolygons();
  18519. };
  18520. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18521. // not modified.
  18522. CSG.prototype.inverse = function () {
  18523. var csg = this.clone();
  18524. csg.inverseInPlace();
  18525. return csg;
  18526. };
  18527. CSG.prototype.inverseInPlace = function () {
  18528. this.polygons.map(function (p) {
  18529. p.flip();
  18530. });
  18531. };
  18532. // This is used to keep meshes transformations so they can be restored
  18533. // when we build back a Babylon Mesh
  18534. // NB : All CSG operations are performed in world coordinates
  18535. CSG.prototype.copyTransformAttributes = function (csg) {
  18536. this.matrix = csg.matrix;
  18537. this.position = csg.position;
  18538. this.rotation = csg.rotation;
  18539. this.scaling = csg.scaling;
  18540. return this;
  18541. };
  18542. // Build Raw mesh from CSG
  18543. // Coordinates here are in world space
  18544. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18545. var matrix = this.matrix.clone();
  18546. matrix.invert();
  18547. 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;
  18548. if (keepSubMeshes) {
  18549. // Sort Polygons, since subMeshes are indices range
  18550. polygons.sort(function (a, b) {
  18551. if (a.shared.meshId === b.shared.meshId) {
  18552. return a.shared.subMeshId - b.shared.subMeshId;
  18553. } else {
  18554. return a.shared.meshId - b.shared.meshId;
  18555. }
  18556. });
  18557. }
  18558. for (var i = 0, il = polygons.length; i < il; i++) {
  18559. polygon = polygons[i];
  18560. // Building SubMeshes
  18561. if (!subMesh_dict[polygon.shared.meshId]) {
  18562. subMesh_dict[polygon.shared.meshId] = {};
  18563. }
  18564. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18565. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18566. indexStart: +Infinity,
  18567. indexEnd: -Infinity,
  18568. materialIndex: polygon.shared.materialIndex
  18569. };
  18570. }
  18571. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18572. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18573. polygonIndices[0] = 0;
  18574. polygonIndices[1] = j - 1;
  18575. polygonIndices[2] = j;
  18576. for (var k = 0; k < 3; k++) {
  18577. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18578. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18579. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18580. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18581. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18582. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18583. // Check if 2 points can be merged
  18584. 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)) {
  18585. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18586. uvs.push(uv.x, uv.y);
  18587. normals.push(normal.x, normal.y, normal.z);
  18588. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18589. }
  18590. indices.push(vertex_idx);
  18591. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18592. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18593. currentIndex++;
  18594. }
  18595. }
  18596. }
  18597. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18598. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18599. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18600. mesh.setIndices(indices);
  18601. if (keepSubMeshes) {
  18602. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18603. var materialIndexOffset = 0, materialMaxIndex;
  18604. mesh.subMeshes.length = 0;
  18605. for (var m in subMesh_dict) {
  18606. materialMaxIndex = -1;
  18607. for (var sm in subMesh_dict[m]) {
  18608. subMesh_obj = subMesh_dict[m][sm];
  18609. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18610. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18611. }
  18612. materialIndexOffset += ++materialMaxIndex;
  18613. }
  18614. }
  18615. return mesh;
  18616. };
  18617. // Build Mesh from CSG taking material and transforms into account
  18618. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18619. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18620. mesh.material = material;
  18621. mesh.position.copyFrom(this.position);
  18622. mesh.rotation.copyFrom(this.rotation);
  18623. mesh.scaling.copyFrom(this.scaling);
  18624. mesh.computeWorldMatrix(true);
  18625. return mesh;
  18626. };
  18627. return CSG;
  18628. })();
  18629. BABYLON.CSG = CSG;
  18630. })(BABYLON || (BABYLON = {}));
  18631. //# sourceMappingURL=babylon.csg.js.map
  18632. var BABYLON;
  18633. (function (BABYLON) {
  18634. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18635. __extends(OculusDistortionCorrectionPostProcess, _super);
  18636. //ANY
  18637. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18638. var _this = this;
  18639. _super.call(this, name, "oculusDistortionCorrection", [
  18640. 'LensCenter',
  18641. 'Scale',
  18642. 'ScaleIn',
  18643. 'HmdWarpParam'
  18644. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18645. this._isRightEye = isRightEye;
  18646. this._distortionFactors = cameraSettings.DistortionK;
  18647. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18648. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18649. this.onSizeChanged = function () {
  18650. _this.aspectRatio = _this.width * .5 / _this.height;
  18651. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18652. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18653. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18654. };
  18655. this.onApply = function (effect) {
  18656. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18657. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18658. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18659. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18660. };
  18661. }
  18662. return OculusDistortionCorrectionPostProcess;
  18663. })(BABYLON.PostProcess);
  18664. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18665. })(BABYLON || (BABYLON = {}));
  18666. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18667. // Mainly based on these 2 articles :
  18668. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  18669. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18670. var BABYLON;
  18671. (function (BABYLON) {
  18672. (function (JoystickAxis) {
  18673. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18674. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18675. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18676. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18677. var JoystickAxis = BABYLON.JoystickAxis;
  18678. var VirtualJoystick = (function () {
  18679. function VirtualJoystick(leftJoystick) {
  18680. var _this = this;
  18681. if (leftJoystick) {
  18682. this._leftJoystick = true;
  18683. } else {
  18684. this._leftJoystick = false;
  18685. }
  18686. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18687. VirtualJoystick._globalJoystickIndex++;
  18688. // By default left & right arrow keys are moving the X
  18689. // and up & down keys are moving the Y
  18690. this._axisTargetedByLeftAndRight = 0 /* X */;
  18691. this._axisTargetedByUpAndDown = 1 /* Y */;
  18692. this.reverseLeftRight = false;
  18693. this.reverseUpDown = false;
  18694. // collections of pointers
  18695. this._touches = new BABYLON.VirtualJoystick.Collection();
  18696. this.deltaPosition = BABYLON.Vector3.Zero();
  18697. this._joystickSensibility = 25;
  18698. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18699. this._rotationSpeed = 25;
  18700. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18701. this._rotateOnAxisRelativeToMesh = false;
  18702. // injecting a canvas element on top of the canvas 3D game
  18703. if (!VirtualJoystick.vjCanvas) {
  18704. window.addEventListener("resize", function () {
  18705. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18706. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18707. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18708. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18709. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18710. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18711. }, false);
  18712. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18713. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18714. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18715. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18716. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18717. VirtualJoystick.vjCanvas.style.width = "100%";
  18718. VirtualJoystick.vjCanvas.style.height = "100%";
  18719. VirtualJoystick.vjCanvas.style.position = "absolute";
  18720. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18721. VirtualJoystick.vjCanvas.style.top = "0px";
  18722. VirtualJoystick.vjCanvas.style.left = "0px";
  18723. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18724. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18725. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18726. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18727. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18728. document.body.appendChild(VirtualJoystick.vjCanvas);
  18729. }
  18730. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18731. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18732. this.pressed = false;
  18733. // default joystick color
  18734. this._joystickColor = "cyan";
  18735. this._joystickPointerID = -1;
  18736. // current joystick position
  18737. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18738. // origin joystick position
  18739. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18740. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18741. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18742. _this._onPointerDown(evt);
  18743. }, false);
  18744. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18745. _this._onPointerMove(evt);
  18746. }, false);
  18747. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18748. _this._onPointerUp(evt);
  18749. }, false);
  18750. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18751. _this._onPointerUp(evt);
  18752. }, false);
  18753. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18754. evt.preventDefault(); // Disables system menu
  18755. }, false);
  18756. requestAnimationFrame(function () {
  18757. _this._drawVirtualJoystick();
  18758. });
  18759. }
  18760. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18761. this._joystickSensibility = newJoystickSensibility;
  18762. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18763. };
  18764. VirtualJoystick.prototype._onPointerDown = function (e) {
  18765. var positionOnScreenCondition;
  18766. e.preventDefault();
  18767. if (this._leftJoystick === true) {
  18768. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18769. } else {
  18770. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18771. }
  18772. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18773. // First contact will be dedicated to the virtual joystick
  18774. this._joystickPointerID = e.pointerId;
  18775. this._joystickPointerStartPos.x = e.clientX;
  18776. this._joystickPointerStartPos.y = e.clientY;
  18777. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18778. this._deltaJoystickVector.x = 0;
  18779. this._deltaJoystickVector.y = 0;
  18780. this.pressed = true;
  18781. this._touches.add(e.pointerId.toString(), e);
  18782. } else {
  18783. // You can only trigger the action buttons with a joystick declared
  18784. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18785. this._action();
  18786. this._touches.add(e.pointerId.toString(), e);
  18787. }
  18788. }
  18789. };
  18790. VirtualJoystick.prototype._onPointerMove = function (e) {
  18791. // If the current pointer is the one associated to the joystick (first touch contact)
  18792. if (this._joystickPointerID == e.pointerId) {
  18793. this._joystickPointerPos.x = e.clientX;
  18794. this._joystickPointerPos.y = e.clientY;
  18795. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18796. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18797. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18798. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18799. switch (this._axisTargetedByLeftAndRight) {
  18800. case 0 /* X */:
  18801. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18802. break;
  18803. case 1 /* Y */:
  18804. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18805. break;
  18806. case 2 /* Z */:
  18807. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18808. break;
  18809. }
  18810. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18811. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18812. switch (this._axisTargetedByUpAndDown) {
  18813. case 0 /* X */:
  18814. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18815. break;
  18816. case 1 /* Y */:
  18817. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18818. break;
  18819. case 2 /* Z */:
  18820. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18821. break;
  18822. }
  18823. } else {
  18824. if (this._touches.item(e.pointerId.toString())) {
  18825. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18826. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18827. }
  18828. }
  18829. };
  18830. VirtualJoystick.prototype._onPointerUp = function (e) {
  18831. this._clearCanvas();
  18832. if (this._joystickPointerID == e.pointerId) {
  18833. this._joystickPointerID = -1;
  18834. this.pressed = false;
  18835. }
  18836. this._deltaJoystickVector.x = 0;
  18837. this._deltaJoystickVector.y = 0;
  18838. this._touches.remove(e.pointerId.toString());
  18839. };
  18840. /**
  18841. * Change the color of the virtual joystick
  18842. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18843. */
  18844. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18845. this._joystickColor = newColor;
  18846. };
  18847. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18848. this._action = action;
  18849. };
  18850. // Define which axis you'd like to control for left & right
  18851. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18852. switch (axis) {
  18853. case 0 /* X */:
  18854. case 1 /* Y */:
  18855. case 2 /* Z */:
  18856. this._axisTargetedByLeftAndRight = axis;
  18857. break;
  18858. default:
  18859. this._axisTargetedByLeftAndRight = 0 /* X */;
  18860. break;
  18861. }
  18862. };
  18863. // Define which axis you'd like to control for up & down
  18864. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18865. switch (axis) {
  18866. case 0 /* X */:
  18867. case 1 /* Y */:
  18868. case 2 /* Z */:
  18869. this._axisTargetedByUpAndDown = axis;
  18870. break;
  18871. default:
  18872. this._axisTargetedByUpAndDown = 1 /* Y */;
  18873. break;
  18874. }
  18875. };
  18876. VirtualJoystick.prototype._clearCanvas = function () {
  18877. if (this._leftJoystick) {
  18878. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18879. } else {
  18880. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18881. }
  18882. };
  18883. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18884. var _this = this;
  18885. if (this.pressed) {
  18886. this._clearCanvas();
  18887. this._touches.forEach(function (touch) {
  18888. if (touch.pointerId === _this._joystickPointerID) {
  18889. VirtualJoystick.vjCanvasContext.beginPath();
  18890. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18891. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18892. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18893. VirtualJoystick.vjCanvasContext.stroke();
  18894. VirtualJoystick.vjCanvasContext.beginPath();
  18895. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18896. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18897. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18898. VirtualJoystick.vjCanvasContext.stroke();
  18899. VirtualJoystick.vjCanvasContext.beginPath();
  18900. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18901. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18902. VirtualJoystick.vjCanvasContext.stroke();
  18903. } else {
  18904. VirtualJoystick.vjCanvasContext.beginPath();
  18905. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18906. VirtualJoystick.vjCanvasContext.beginPath();
  18907. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18908. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18909. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18910. VirtualJoystick.vjCanvasContext.stroke();
  18911. }
  18912. ;
  18913. });
  18914. }
  18915. requestAnimationFrame(function () {
  18916. _this._drawVirtualJoystick();
  18917. });
  18918. };
  18919. VirtualJoystick.prototype.releaseCanvas = function () {
  18920. if (VirtualJoystick.vjCanvas) {
  18921. document.body.removeChild(VirtualJoystick.vjCanvas);
  18922. VirtualJoystick.vjCanvas = null;
  18923. }
  18924. };
  18925. VirtualJoystick._globalJoystickIndex = 0;
  18926. return VirtualJoystick;
  18927. })();
  18928. BABYLON.VirtualJoystick = VirtualJoystick;
  18929. })(BABYLON || (BABYLON = {}));
  18930. var BABYLON;
  18931. (function (BABYLON) {
  18932. (function (VirtualJoystick) {
  18933. var Collection = (function () {
  18934. function Collection() {
  18935. this._count = 0;
  18936. this._collection = new Array();
  18937. }
  18938. Collection.prototype.Count = function () {
  18939. return this._count;
  18940. };
  18941. Collection.prototype.add = function (key, item) {
  18942. if (this._collection[key] != undefined) {
  18943. return undefined;
  18944. }
  18945. this._collection[key] = item;
  18946. return ++this._count;
  18947. };
  18948. Collection.prototype.remove = function (key) {
  18949. if (this._collection[key] == undefined) {
  18950. return undefined;
  18951. }
  18952. delete this._collection[key];
  18953. return --this._count;
  18954. };
  18955. Collection.prototype.item = function (key) {
  18956. return this._collection[key];
  18957. };
  18958. Collection.prototype.forEach = function (block) {
  18959. var key;
  18960. for (key in this._collection) {
  18961. if (this._collection.hasOwnProperty(key)) {
  18962. block(this._collection[key]);
  18963. }
  18964. }
  18965. };
  18966. return Collection;
  18967. })();
  18968. VirtualJoystick.Collection = Collection;
  18969. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18970. var VirtualJoystick = BABYLON.VirtualJoystick;
  18971. })(BABYLON || (BABYLON = {}));
  18972. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18973. var BABYLON;
  18974. (function (BABYLON) {
  18975. var OculusRiftDevKit2013_Metric = {
  18976. HResolution: 1280,
  18977. VResolution: 800,
  18978. HScreenSize: 0.149759993,
  18979. VScreenSize: 0.0935999975,
  18980. VScreenCenter: 0.0467999987,
  18981. EyeToScreenDistance: 0.0410000011,
  18982. LensSeparationDistance: 0.0635000020,
  18983. InterpupillaryDistance: 0.0640000030,
  18984. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18985. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18986. PostProcessScaleFactor: 1.714605507808412,
  18987. LensCenterOffset: 0.151976421
  18988. };
  18989. var _OculusInnerCamera = (function (_super) {
  18990. __extends(_OculusInnerCamera, _super);
  18991. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18992. _super.call(this, name, position, scene);
  18993. this._workMatrix = new BABYLON.Matrix();
  18994. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18995. // Constants
  18996. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18997. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18998. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18999. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19000. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19001. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19002. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19003. // Postprocess
  19004. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19005. }
  19006. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19007. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19008. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19009. return this._projectionMatrix;
  19010. };
  19011. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19012. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19013. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19014. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19015. // Computing target and final matrix
  19016. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19017. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19018. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19019. return this._viewMatrix;
  19020. };
  19021. return _OculusInnerCamera;
  19022. })(BABYLON.FreeCamera);
  19023. var OculusCamera = (function (_super) {
  19024. __extends(OculusCamera, _super);
  19025. function OculusCamera(name, position, scene) {
  19026. _super.call(this, name, position, scene);
  19027. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19028. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19029. this.subCameras.push(this._leftCamera);
  19030. this.subCameras.push(this._rightCamera);
  19031. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19032. }
  19033. OculusCamera.prototype._update = function () {
  19034. this._leftCamera.position.copyFrom(this.position);
  19035. this._rightCamera.position.copyFrom(this.position);
  19036. this._updateCamera(this._leftCamera);
  19037. this._updateCamera(this._rightCamera);
  19038. _super.prototype._update.call(this);
  19039. };
  19040. OculusCamera.prototype._updateCamera = function (camera) {
  19041. camera.minZ = this.minZ;
  19042. camera.maxZ = this.maxZ;
  19043. camera.rotation.x = this.rotation.x;
  19044. camera.rotation.y = this.rotation.y;
  19045. camera.rotation.z = this.rotation.z;
  19046. };
  19047. // Oculus events
  19048. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19049. var yaw = evt.alpha / 180 * Math.PI;
  19050. var pitch = evt.beta / 180 * Math.PI;
  19051. var roll = evt.gamma / 180 * Math.PI;
  19052. if (!this._offsetOrientation) {
  19053. this._offsetOrientation = {
  19054. yaw: yaw,
  19055. pitch: pitch,
  19056. roll: roll
  19057. };
  19058. return;
  19059. } else {
  19060. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19061. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19062. this.rotation.z += this._offsetOrientation.roll - roll;
  19063. this._offsetOrientation.yaw = yaw;
  19064. this._offsetOrientation.pitch = pitch;
  19065. this._offsetOrientation.roll = roll;
  19066. }
  19067. };
  19068. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19069. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19070. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19071. };
  19072. OculusCamera.prototype.detachControl = function (element) {
  19073. _super.prototype.detachControl.call(this, element);
  19074. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19075. };
  19076. return OculusCamera;
  19077. })(BABYLON.FreeCamera);
  19078. BABYLON.OculusCamera = OculusCamera;
  19079. })(BABYLON || (BABYLON = {}));
  19080. //# sourceMappingURL=babylon.oculusCamera.js.map
  19081. var BABYLON;
  19082. (function (BABYLON) {
  19083. var OculusRiftDevKit2013_Metric = {
  19084. HResolution: 1280,
  19085. VResolution: 800,
  19086. HScreenSize: 0.149759993,
  19087. VScreenSize: 0.0935999975,
  19088. VScreenCenter: 0.0467999987,
  19089. EyeToScreenDistance: 0.0410000011,
  19090. LensSeparationDistance: 0.0635000020,
  19091. InterpupillaryDistance: 0.0640000030,
  19092. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19093. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19094. PostProcessScaleFactor: 1.714605507808412,
  19095. LensCenterOffset: 0.151976421
  19096. };
  19097. var _OculusInnerGamepadCamera = (function (_super) {
  19098. __extends(_OculusInnerGamepadCamera, _super);
  19099. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19100. _super.call(this, name, position, scene);
  19101. this._workMatrix = new BABYLON.Matrix();
  19102. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19103. // Constants
  19104. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19105. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19106. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19107. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19108. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19109. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19110. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19111. // Postprocess
  19112. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19113. }
  19114. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19115. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19116. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19117. return this._projectionMatrix;
  19118. };
  19119. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19120. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19121. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19122. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19123. // Computing target and final matrix
  19124. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19125. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19126. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19127. return this._viewMatrix;
  19128. };
  19129. return _OculusInnerGamepadCamera;
  19130. })(BABYLON.FreeCamera);
  19131. var OculusGamepadCamera = (function (_super) {
  19132. __extends(OculusGamepadCamera, _super);
  19133. function OculusGamepadCamera(name, position, scene) {
  19134. var _this = this;
  19135. _super.call(this, name, position, scene);
  19136. this.angularSensibility = 200;
  19137. this.moveSensibility = 75;
  19138. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19139. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19140. this.subCameras.push(this._leftCamera);
  19141. this.subCameras.push(this._rightCamera);
  19142. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19143. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19144. _this._onNewGameConnected(gamepad);
  19145. });
  19146. }
  19147. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19148. // Only the first gamepad can control the camera
  19149. if (gamepad.index === 0) {
  19150. this._gamepad = gamepad;
  19151. }
  19152. };
  19153. OculusGamepadCamera.prototype._update = function () {
  19154. this._leftCamera.position.copyFrom(this.position);
  19155. this._rightCamera.position.copyFrom(this.position);
  19156. this._updateCamera(this._leftCamera);
  19157. this._updateCamera(this._rightCamera);
  19158. _super.prototype._update.call(this);
  19159. };
  19160. OculusGamepadCamera.prototype._checkInputs = function () {
  19161. if (!this._gamepad) {
  19162. return;
  19163. }
  19164. var LSValues = this._gamepad.leftStick;
  19165. var normalizedLX = LSValues.x / this.moveSensibility;
  19166. var normalizedLY = LSValues.y / this.moveSensibility;
  19167. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19168. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19169. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19170. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19171. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19172. };
  19173. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19174. camera.minZ = this.minZ;
  19175. camera.maxZ = this.maxZ;
  19176. camera.rotation.x = this.rotation.x;
  19177. camera.rotation.y = this.rotation.y;
  19178. camera.rotation.z = this.rotation.z;
  19179. };
  19180. // Oculus events
  19181. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19182. var yaw = evt.alpha / 180 * Math.PI;
  19183. var pitch = evt.beta / 180 * Math.PI;
  19184. var roll = evt.gamma / 180 * Math.PI;
  19185. if (!this._offsetOrientation) {
  19186. this._offsetOrientation = {
  19187. yaw: yaw,
  19188. pitch: pitch,
  19189. roll: roll
  19190. };
  19191. return;
  19192. } else {
  19193. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19194. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19195. this.rotation.z += this._offsetOrientation.roll - roll;
  19196. this._offsetOrientation.yaw = yaw;
  19197. this._offsetOrientation.pitch = pitch;
  19198. this._offsetOrientation.roll = roll;
  19199. }
  19200. };
  19201. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19202. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19203. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19204. };
  19205. OculusGamepadCamera.prototype.detachControl = function (element) {
  19206. _super.prototype.detachControl.call(this, element);
  19207. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19208. };
  19209. OculusGamepadCamera.prototype.dispose = function () {
  19210. this._gamepads.dispose();
  19211. _super.prototype.dispose.call(this);
  19212. };
  19213. return OculusGamepadCamera;
  19214. })(BABYLON.FreeCamera);
  19215. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19216. })(BABYLON || (BABYLON = {}));
  19217. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19218. var BABYLON;
  19219. (function (BABYLON) {
  19220. // We're mainly based on the logic defined into the FreeCamera code
  19221. var VirtualJoysticksCamera = (function (_super) {
  19222. __extends(VirtualJoysticksCamera, _super);
  19223. function VirtualJoysticksCamera(name, position, scene) {
  19224. _super.call(this, name, position, scene);
  19225. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19226. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19227. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19228. this._leftjoystick.setJoystickSensibility(0.15);
  19229. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19230. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19231. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19232. this._rightjoystick.reverseUpDown = true;
  19233. this._rightjoystick.setJoystickSensibility(0.05);
  19234. this._rightjoystick.setJoystickColor("yellow");
  19235. }
  19236. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19237. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19238. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19239. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19240. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19241. if (!this._leftjoystick.pressed) {
  19242. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19243. }
  19244. if (!this._rightjoystick.pressed) {
  19245. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19246. }
  19247. };
  19248. VirtualJoysticksCamera.prototype.dispose = function () {
  19249. this._leftjoystick.releaseCanvas();
  19250. _super.prototype.dispose.call(this);
  19251. };
  19252. return VirtualJoysticksCamera;
  19253. })(BABYLON.FreeCamera);
  19254. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19255. })(BABYLON || (BABYLON = {}));
  19256. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19257. var BABYLON;
  19258. (function (BABYLON) {
  19259. var ShaderMaterial = (function (_super) {
  19260. __extends(ShaderMaterial, _super);
  19261. function ShaderMaterial(name, scene, shaderPath, options) {
  19262. _super.call(this, name, scene);
  19263. this._textures = new Array();
  19264. this._floats = new Array();
  19265. this._floatsArrays = {};
  19266. this._colors3 = new Array();
  19267. this._colors4 = new Array();
  19268. this._vectors2 = new Array();
  19269. this._vectors3 = new Array();
  19270. this._matrices = new Array();
  19271. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19272. this._shaderPath = shaderPath;
  19273. options.needAlphaBlending = options.needAlphaBlending || false;
  19274. options.needAlphaTesting = options.needAlphaTesting || false;
  19275. options.attributes = options.attributes || ["position", "normal", "uv"];
  19276. options.uniforms = options.uniforms || ["worldViewProjection"];
  19277. options.samplers = options.samplers || [];
  19278. this._options = options;
  19279. }
  19280. ShaderMaterial.prototype.needAlphaBlending = function () {
  19281. return this._options.needAlphaBlending;
  19282. };
  19283. ShaderMaterial.prototype.needAlphaTesting = function () {
  19284. return this._options.needAlphaTesting;
  19285. };
  19286. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19287. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19288. this._options.uniforms.push(uniformName);
  19289. }
  19290. };
  19291. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19292. if (this._options.samplers.indexOf(name) === -1) {
  19293. this._options.samplers.push(name);
  19294. }
  19295. this._textures[name] = texture;
  19296. return this;
  19297. };
  19298. ShaderMaterial.prototype.setFloat = function (name, value) {
  19299. this._checkUniform(name);
  19300. this._floats[name] = value;
  19301. return this;
  19302. };
  19303. ShaderMaterial.prototype.setFloats = function (name, value) {
  19304. this._checkUniform(name);
  19305. this._floatsArrays[name] = value;
  19306. return this;
  19307. };
  19308. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19309. this._checkUniform(name);
  19310. this._colors3[name] = value;
  19311. return this;
  19312. };
  19313. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19314. this._checkUniform(name);
  19315. this._colors4[name] = value;
  19316. return this;
  19317. };
  19318. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19319. this._checkUniform(name);
  19320. this._vectors2[name] = value;
  19321. return this;
  19322. };
  19323. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19324. this._checkUniform(name);
  19325. this._vectors3[name] = value;
  19326. return this;
  19327. };
  19328. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19329. this._checkUniform(name);
  19330. this._matrices[name] = value;
  19331. return this;
  19332. };
  19333. ShaderMaterial.prototype.isReady = function () {
  19334. var scene = this.getScene();
  19335. var engine = scene.getEngine();
  19336. if (!this.checkReadyOnEveryCall) {
  19337. if (this._renderId === scene.getRenderId()) {
  19338. return true;
  19339. }
  19340. }
  19341. var previousEffect = this._effect;
  19342. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19343. if (!this._effect.isReady()) {
  19344. return false;
  19345. }
  19346. if (previousEffect !== this._effect) {
  19347. scene.resetCachedMaterial();
  19348. }
  19349. this._renderId = scene.getRenderId();
  19350. return true;
  19351. };
  19352. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19353. var scene = this.getScene();
  19354. if (this._options.uniforms.indexOf("world") !== -1) {
  19355. this._effect.setMatrix("world", world);
  19356. }
  19357. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19358. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19359. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19360. }
  19361. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19362. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19363. }
  19364. };
  19365. ShaderMaterial.prototype.bind = function (world) {
  19366. // Std values
  19367. this.bindOnlyWorldMatrix(world);
  19368. if (this.getScene().getCachedMaterial() !== this) {
  19369. if (this._options.uniforms.indexOf("view") !== -1) {
  19370. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19371. }
  19372. if (this._options.uniforms.indexOf("projection") !== -1) {
  19373. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19374. }
  19375. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19376. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19377. }
  19378. for (var name in this._textures) {
  19379. this._effect.setTexture(name, this._textures[name]);
  19380. }
  19381. for (name in this._floats) {
  19382. this._effect.setFloat(name, this._floats[name]);
  19383. }
  19384. for (name in this._floatsArrays) {
  19385. this._effect.setArray(name, this._floatsArrays[name]);
  19386. }
  19387. for (name in this._colors3) {
  19388. this._effect.setColor3(name, this._colors3[name]);
  19389. }
  19390. for (name in this._colors4) {
  19391. var color = this._colors4[name];
  19392. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19393. }
  19394. for (name in this._vectors2) {
  19395. this._effect.setVector2(name, this._vectors2[name]);
  19396. }
  19397. for (name in this._vectors3) {
  19398. this._effect.setVector3(name, this._vectors3[name]);
  19399. }
  19400. for (name in this._matrices) {
  19401. this._effect.setMatrix(name, this._matrices[name]);
  19402. }
  19403. }
  19404. _super.prototype.bind.call(this, world, null);
  19405. };
  19406. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19407. for (var name in this._textures) {
  19408. this._textures[name].dispose();
  19409. }
  19410. this._textures = [];
  19411. _super.prototype.dispose.call(this, forceDisposeEffect);
  19412. };
  19413. return ShaderMaterial;
  19414. })(BABYLON.Material);
  19415. BABYLON.ShaderMaterial = ShaderMaterial;
  19416. })(BABYLON || (BABYLON = {}));
  19417. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19418. var BABYLON;
  19419. (function (BABYLON) {
  19420. var VertexData = (function () {
  19421. function VertexData() {
  19422. }
  19423. VertexData.prototype.set = function (data, kind) {
  19424. switch (kind) {
  19425. case BABYLON.VertexBuffer.PositionKind:
  19426. this.positions = data;
  19427. break;
  19428. case BABYLON.VertexBuffer.NormalKind:
  19429. this.normals = data;
  19430. break;
  19431. case BABYLON.VertexBuffer.UVKind:
  19432. this.uvs = data;
  19433. break;
  19434. case BABYLON.VertexBuffer.UV2Kind:
  19435. this.uv2s = data;
  19436. break;
  19437. case BABYLON.VertexBuffer.ColorKind:
  19438. this.colors = data;
  19439. break;
  19440. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19441. this.matricesIndices = data;
  19442. break;
  19443. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19444. this.matricesWeights = data;
  19445. break;
  19446. }
  19447. };
  19448. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19449. this._applyTo(mesh, updatable);
  19450. };
  19451. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19452. this._applyTo(geometry, updatable);
  19453. };
  19454. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19455. this._update(mesh);
  19456. };
  19457. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19458. this._update(geometry);
  19459. };
  19460. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19461. if (this.positions) {
  19462. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19463. }
  19464. if (this.normals) {
  19465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19466. }
  19467. if (this.uvs) {
  19468. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19469. }
  19470. if (this.uv2s) {
  19471. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19472. }
  19473. if (this.colors) {
  19474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19475. }
  19476. if (this.matricesIndices) {
  19477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19478. }
  19479. if (this.matricesWeights) {
  19480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19481. }
  19482. if (this.indices) {
  19483. meshOrGeometry.setIndices(this.indices);
  19484. }
  19485. };
  19486. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19487. if (this.positions) {
  19488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19489. }
  19490. if (this.normals) {
  19491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19492. }
  19493. if (this.uvs) {
  19494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19495. }
  19496. if (this.uv2s) {
  19497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19498. }
  19499. if (this.colors) {
  19500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19501. }
  19502. if (this.matricesIndices) {
  19503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19504. }
  19505. if (this.matricesWeights) {
  19506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19507. }
  19508. if (this.indices) {
  19509. meshOrGeometry.setIndices(this.indices);
  19510. }
  19511. };
  19512. VertexData.prototype.transform = function (matrix) {
  19513. var transformed = BABYLON.Vector3.Zero();
  19514. if (this.positions) {
  19515. var position = BABYLON.Vector3.Zero();
  19516. for (var index = 0; index < this.positions.length; index += 3) {
  19517. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19518. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19519. this.positions[index] = transformed.x;
  19520. this.positions[index + 1] = transformed.y;
  19521. this.positions[index + 2] = transformed.z;
  19522. }
  19523. }
  19524. if (this.normals) {
  19525. var normal = BABYLON.Vector3.Zero();
  19526. for (index = 0; index < this.normals.length; index += 3) {
  19527. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19528. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19529. this.normals[index] = transformed.x;
  19530. this.normals[index + 1] = transformed.y;
  19531. this.normals[index + 2] = transformed.z;
  19532. }
  19533. }
  19534. };
  19535. VertexData.prototype.merge = function (other) {
  19536. if (other.indices) {
  19537. if (!this.indices) {
  19538. this.indices = [];
  19539. }
  19540. var offset = this.positions ? this.positions.length / 3 : 0;
  19541. for (var index = 0; index < other.indices.length; index++) {
  19542. this.indices.push(other.indices[index] + offset);
  19543. }
  19544. }
  19545. if (other.positions) {
  19546. if (!this.positions) {
  19547. this.positions = [];
  19548. }
  19549. for (index = 0; index < other.positions.length; index++) {
  19550. this.positions.push(other.positions[index]);
  19551. }
  19552. }
  19553. if (other.normals) {
  19554. if (!this.normals) {
  19555. this.normals = [];
  19556. }
  19557. for (index = 0; index < other.normals.length; index++) {
  19558. this.normals.push(other.normals[index]);
  19559. }
  19560. }
  19561. if (other.uvs) {
  19562. if (!this.uvs) {
  19563. this.uvs = [];
  19564. }
  19565. for (index = 0; index < other.uvs.length; index++) {
  19566. this.uvs.push(other.uvs[index]);
  19567. }
  19568. }
  19569. if (other.uv2s) {
  19570. if (!this.uv2s) {
  19571. this.uv2s = [];
  19572. }
  19573. for (index = 0; index < other.uv2s.length; index++) {
  19574. this.uv2s.push(other.uv2s[index]);
  19575. }
  19576. }
  19577. if (other.matricesIndices) {
  19578. if (!this.matricesIndices) {
  19579. this.matricesIndices = [];
  19580. }
  19581. for (index = 0; index < other.matricesIndices.length; index++) {
  19582. this.matricesIndices.push(other.matricesIndices[index]);
  19583. }
  19584. }
  19585. if (other.matricesWeights) {
  19586. if (!this.matricesWeights) {
  19587. this.matricesWeights = [];
  19588. }
  19589. for (index = 0; index < other.matricesWeights.length; index++) {
  19590. this.matricesWeights.push(other.matricesWeights[index]);
  19591. }
  19592. }
  19593. if (other.colors) {
  19594. if (!this.colors) {
  19595. this.colors = [];
  19596. }
  19597. for (index = 0; index < other.colors.length; index++) {
  19598. this.colors.push(other.colors[index]);
  19599. }
  19600. }
  19601. };
  19602. // Statics
  19603. VertexData.ExtractFromMesh = function (mesh) {
  19604. return VertexData._ExtractFrom(mesh);
  19605. };
  19606. VertexData.ExtractFromGeometry = function (geometry) {
  19607. return VertexData._ExtractFrom(geometry);
  19608. };
  19609. VertexData._ExtractFrom = function (meshOrGeometry) {
  19610. var result = new BABYLON.VertexData();
  19611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19612. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19613. }
  19614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19615. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19616. }
  19617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19618. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19619. }
  19620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19621. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19622. }
  19623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19624. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19625. }
  19626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19627. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19628. }
  19629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19630. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19631. }
  19632. result.indices = meshOrGeometry.getIndices();
  19633. return result;
  19634. };
  19635. VertexData.CreateBox = function (size) {
  19636. var normalsSource = [
  19637. new BABYLON.Vector3(0, 0, 1),
  19638. new BABYLON.Vector3(0, 0, -1),
  19639. new BABYLON.Vector3(1, 0, 0),
  19640. new BABYLON.Vector3(-1, 0, 0),
  19641. new BABYLON.Vector3(0, 1, 0),
  19642. new BABYLON.Vector3(0, -1, 0)
  19643. ];
  19644. var indices = [];
  19645. var positions = [];
  19646. var normals = [];
  19647. var uvs = [];
  19648. size = size || 1;
  19649. for (var index = 0; index < normalsSource.length; index++) {
  19650. var normal = normalsSource[index];
  19651. // Get two vectors perpendicular to the face normal and to each other.
  19652. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19653. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19654. // Six indices (two triangles) per face.
  19655. var verticesLength = positions.length / 3;
  19656. indices.push(verticesLength);
  19657. indices.push(verticesLength + 1);
  19658. indices.push(verticesLength + 2);
  19659. indices.push(verticesLength);
  19660. indices.push(verticesLength + 2);
  19661. indices.push(verticesLength + 3);
  19662. // Four vertices per face.
  19663. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19664. positions.push(vertex.x, vertex.y, vertex.z);
  19665. normals.push(normal.x, normal.y, normal.z);
  19666. uvs.push(1.0, 1.0);
  19667. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19668. positions.push(vertex.x, vertex.y, vertex.z);
  19669. normals.push(normal.x, normal.y, normal.z);
  19670. uvs.push(0.0, 1.0);
  19671. vertex = normal.add(side1).add(side2).scale(size / 2);
  19672. positions.push(vertex.x, vertex.y, vertex.z);
  19673. normals.push(normal.x, normal.y, normal.z);
  19674. uvs.push(0.0, 0.0);
  19675. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19676. positions.push(vertex.x, vertex.y, vertex.z);
  19677. normals.push(normal.x, normal.y, normal.z);
  19678. uvs.push(1.0, 0.0);
  19679. }
  19680. // Result
  19681. var vertexData = new BABYLON.VertexData();
  19682. vertexData.indices = indices;
  19683. vertexData.positions = positions;
  19684. vertexData.normals = normals;
  19685. vertexData.uvs = uvs;
  19686. return vertexData;
  19687. };
  19688. VertexData.CreateSphere = function (segments, diameter) {
  19689. segments = segments || 32;
  19690. diameter = diameter || 1;
  19691. var radius = diameter / 2;
  19692. var totalZRotationSteps = 2 + segments;
  19693. var totalYRotationSteps = 2 * totalZRotationSteps;
  19694. var indices = [];
  19695. var positions = [];
  19696. var normals = [];
  19697. var uvs = [];
  19698. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19699. var normalizedZ = zRotationStep / totalZRotationSteps;
  19700. var angleZ = (normalizedZ * Math.PI);
  19701. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19702. var normalizedY = yRotationStep / totalYRotationSteps;
  19703. var angleY = normalizedY * Math.PI * 2;
  19704. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19705. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19706. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19707. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19708. var vertex = complete.scale(radius);
  19709. var normal = BABYLON.Vector3.Normalize(vertex);
  19710. positions.push(vertex.x, vertex.y, vertex.z);
  19711. normals.push(normal.x, normal.y, normal.z);
  19712. uvs.push(normalizedZ, normalizedY);
  19713. }
  19714. if (zRotationStep > 0) {
  19715. var verticesCount = positions.length / 3;
  19716. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19717. indices.push((firstIndex));
  19718. indices.push((firstIndex + 1));
  19719. indices.push(firstIndex + totalYRotationSteps + 1);
  19720. indices.push((firstIndex + totalYRotationSteps + 1));
  19721. indices.push((firstIndex + 1));
  19722. indices.push((firstIndex + totalYRotationSteps + 2));
  19723. }
  19724. }
  19725. }
  19726. // Result
  19727. var vertexData = new BABYLON.VertexData();
  19728. vertexData.indices = indices;
  19729. vertexData.positions = positions;
  19730. vertexData.normals = normals;
  19731. vertexData.uvs = uvs;
  19732. return vertexData;
  19733. };
  19734. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19735. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19736. var radiusTop = diameterTop / 2;
  19737. var radiusBottom = diameterBottom / 2;
  19738. var indices = [];
  19739. var positions = [];
  19740. var normals = [];
  19741. var uvs = [];
  19742. height = height || 1;
  19743. diameterTop = diameterTop || 0.5;
  19744. diameterBottom = diameterBottom || 1;
  19745. tessellation = tessellation || 16;
  19746. subdivisions = subdivisions || 1;
  19747. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19748. var getCircleVector = function (i) {
  19749. var angle = (i * 2.0 * Math.PI / tessellation);
  19750. var dx = Math.cos(angle);
  19751. var dz = Math.sin(angle);
  19752. return new BABYLON.Vector3(dx, 0, dz);
  19753. };
  19754. var createCylinderCap = function (isTop) {
  19755. var radius = isTop ? radiusTop : radiusBottom;
  19756. if (radius == 0) {
  19757. return;
  19758. }
  19759. var vbase = positions.length / 3;
  19760. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19761. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19762. if (!isTop) {
  19763. offset.scaleInPlace(-1);
  19764. textureScale.x = -textureScale.x;
  19765. }
  19766. for (i = 0; i < tessellation; i++) {
  19767. var circleVector = getCircleVector(i);
  19768. var position = circleVector.scale(radius).add(offset);
  19769. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19770. positions.push(position.x, position.y, position.z);
  19771. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19772. }
  19773. for (var i = 0; i < tessellation - 2; i++) {
  19774. if (!isTop) {
  19775. indices.push(vbase);
  19776. indices.push(vbase + (i + 2) % tessellation);
  19777. indices.push(vbase + (i + 1) % tessellation);
  19778. } else {
  19779. indices.push(vbase);
  19780. indices.push(vbase + (i + 1) % tessellation);
  19781. indices.push(vbase + (i + 2) % tessellation);
  19782. }
  19783. }
  19784. };
  19785. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19786. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19787. var stride = tessellation + 1;
  19788. for (var i = 0; i <= tessellation; i++) {
  19789. var circleVector = getCircleVector(i);
  19790. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19791. var position, radius = radiusBottom;
  19792. for (var s = 0; s <= subdivisions; s++) {
  19793. // Update variables
  19794. position = circleVector.scale(radius);
  19795. position.addInPlace(base.add(offset.scale(s)));
  19796. textureCoordinate.y += 1 / subdivisions;
  19797. radius += (radiusTop - radiusBottom) / subdivisions;
  19798. // Push in arrays
  19799. positions.push(position.x, position.y, position.z);
  19800. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19801. }
  19802. }
  19803. subdivisions += 1;
  19804. for (var s = 0; s < subdivisions - 1; s++) {
  19805. for (var i = 0; i <= tessellation; i++) {
  19806. indices.push(i * subdivisions + s);
  19807. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19808. indices.push(i * subdivisions + (s + 1));
  19809. indices.push(i * subdivisions + (s + 1));
  19810. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19811. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19812. }
  19813. }
  19814. // Create flat triangle fan caps to seal the top and bottom.
  19815. createCylinderCap(true);
  19816. createCylinderCap(false);
  19817. // Normals
  19818. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19819. // Result
  19820. var vertexData = new BABYLON.VertexData();
  19821. vertexData.indices = indices;
  19822. vertexData.positions = positions;
  19823. vertexData.normals = normals;
  19824. vertexData.uvs = uvs;
  19825. return vertexData;
  19826. };
  19827. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19828. var indices = [];
  19829. var positions = [];
  19830. var normals = [];
  19831. var uvs = [];
  19832. diameter = diameter || 1;
  19833. thickness = thickness || 0.5;
  19834. tessellation = tessellation || 16;
  19835. var stride = tessellation + 1;
  19836. for (var i = 0; i <= tessellation; i++) {
  19837. var u = i / tessellation;
  19838. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19839. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19840. for (var j = 0; j <= tessellation; j++) {
  19841. var v = 1 - j / tessellation;
  19842. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19843. var dx = Math.cos(innerAngle);
  19844. var dy = Math.sin(innerAngle);
  19845. // Create a vertex.
  19846. var normal = new BABYLON.Vector3(dx, dy, 0);
  19847. var position = normal.scale(thickness / 2);
  19848. var textureCoordinate = new BABYLON.Vector2(u, v);
  19849. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19850. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19851. positions.push(position.x, position.y, position.z);
  19852. normals.push(normal.x, normal.y, normal.z);
  19853. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19854. // And create indices for two triangles.
  19855. var nextI = (i + 1) % stride;
  19856. var nextJ = (j + 1) % stride;
  19857. indices.push(i * stride + j);
  19858. indices.push(i * stride + nextJ);
  19859. indices.push(nextI * stride + j);
  19860. indices.push(i * stride + nextJ);
  19861. indices.push(nextI * stride + nextJ);
  19862. indices.push(nextI * stride + j);
  19863. }
  19864. }
  19865. // Result
  19866. var vertexData = new BABYLON.VertexData();
  19867. vertexData.indices = indices;
  19868. vertexData.positions = positions;
  19869. vertexData.normals = normals;
  19870. vertexData.uvs = uvs;
  19871. return vertexData;
  19872. };
  19873. VertexData.CreateLines = function (points) {
  19874. var indices = [];
  19875. var positions = [];
  19876. for (var index = 0; index < points.length; index++) {
  19877. positions.push(points[index].x, points[index].y, points[index].z);
  19878. if (index > 0) {
  19879. indices.push(index - 1);
  19880. indices.push(index);
  19881. }
  19882. }
  19883. // Result
  19884. var vertexData = new BABYLON.VertexData();
  19885. vertexData.indices = indices;
  19886. vertexData.positions = positions;
  19887. return vertexData;
  19888. };
  19889. VertexData.CreateGround = function (width, height, subdivisions) {
  19890. var indices = [];
  19891. var positions = [];
  19892. var normals = [];
  19893. var uvs = [];
  19894. var row, col;
  19895. width = width || 1;
  19896. height = height || 1;
  19897. subdivisions = subdivisions || 1;
  19898. for (row = 0; row <= subdivisions; row++) {
  19899. for (col = 0; col <= subdivisions; col++) {
  19900. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19901. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19902. positions.push(position.x, position.y, position.z);
  19903. normals.push(normal.x, normal.y, normal.z);
  19904. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19905. }
  19906. }
  19907. for (row = 0; row < subdivisions; row++) {
  19908. for (col = 0; col < subdivisions; col++) {
  19909. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19910. indices.push(col + 1 + row * (subdivisions + 1));
  19911. indices.push(col + row * (subdivisions + 1));
  19912. indices.push(col + (row + 1) * (subdivisions + 1));
  19913. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19914. indices.push(col + row * (subdivisions + 1));
  19915. }
  19916. }
  19917. // Result
  19918. var vertexData = new BABYLON.VertexData();
  19919. vertexData.indices = indices;
  19920. vertexData.positions = positions;
  19921. vertexData.normals = normals;
  19922. vertexData.uvs = uvs;
  19923. return vertexData;
  19924. };
  19925. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19926. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19927. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19928. var indices = [];
  19929. var positions = [];
  19930. var normals = [];
  19931. var uvs = [];
  19932. var row, col, tileRow, tileCol;
  19933. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19934. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19935. precision.w = (precision.w < 1) ? 1 : precision.w;
  19936. precision.h = (precision.h < 1) ? 1 : precision.h;
  19937. var tileSize = {
  19938. 'w': (xmax - xmin) / subdivisions.w,
  19939. 'h': (zmax - zmin) / subdivisions.h
  19940. };
  19941. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19942. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19943. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19944. }
  19945. }
  19946. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19947. // Indices
  19948. var base = positions.length / 3;
  19949. var rowLength = precision.w + 1;
  19950. for (row = 0; row < precision.h; row++) {
  19951. for (col = 0; col < precision.w; col++) {
  19952. var square = [
  19953. base + col + row * rowLength,
  19954. base + (col + 1) + row * rowLength,
  19955. base + (col + 1) + (row + 1) * rowLength,
  19956. base + col + (row + 1) * rowLength
  19957. ];
  19958. indices.push(square[1]);
  19959. indices.push(square[2]);
  19960. indices.push(square[3]);
  19961. indices.push(square[0]);
  19962. indices.push(square[1]);
  19963. indices.push(square[3]);
  19964. }
  19965. }
  19966. // Position, normals and uvs
  19967. var position = BABYLON.Vector3.Zero();
  19968. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19969. for (row = 0; row <= precision.h; row++) {
  19970. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19971. for (col = 0; col <= precision.w; col++) {
  19972. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19973. position.y = 0;
  19974. positions.push(position.x, position.y, position.z);
  19975. normals.push(normal.x, normal.y, normal.z);
  19976. uvs.push(col / precision.w, row / precision.h);
  19977. }
  19978. }
  19979. }
  19980. // Result
  19981. var vertexData = new BABYLON.VertexData();
  19982. vertexData.indices = indices;
  19983. vertexData.positions = positions;
  19984. vertexData.normals = normals;
  19985. vertexData.uvs = uvs;
  19986. return vertexData;
  19987. };
  19988. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19989. var indices = [];
  19990. var positions = [];
  19991. var normals = [];
  19992. var uvs = [];
  19993. var row, col;
  19994. for (row = 0; row <= subdivisions; row++) {
  19995. for (col = 0; col <= subdivisions; col++) {
  19996. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19997. // Compute height
  19998. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19999. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20000. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20001. var r = buffer[pos] / 255.0;
  20002. var g = buffer[pos + 1] / 255.0;
  20003. var b = buffer[pos + 2] / 255.0;
  20004. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20005. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20006. // Add vertex
  20007. positions.push(position.x, position.y, position.z);
  20008. normals.push(0, 0, 0);
  20009. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20010. }
  20011. }
  20012. for (row = 0; row < subdivisions; row++) {
  20013. for (col = 0; col < subdivisions; col++) {
  20014. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20015. indices.push(col + 1 + row * (subdivisions + 1));
  20016. indices.push(col + row * (subdivisions + 1));
  20017. indices.push(col + (row + 1) * (subdivisions + 1));
  20018. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20019. indices.push(col + row * (subdivisions + 1));
  20020. }
  20021. }
  20022. // Normals
  20023. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20024. // Result
  20025. var vertexData = new BABYLON.VertexData();
  20026. vertexData.indices = indices;
  20027. vertexData.positions = positions;
  20028. vertexData.normals = normals;
  20029. vertexData.uvs = uvs;
  20030. return vertexData;
  20031. };
  20032. VertexData.CreatePlane = function (size) {
  20033. var indices = [];
  20034. var positions = [];
  20035. var normals = [];
  20036. var uvs = [];
  20037. size = size || 1;
  20038. // Vertices
  20039. var halfSize = size / 2.0;
  20040. positions.push(-halfSize, -halfSize, 0);
  20041. normals.push(0, 0, -1.0);
  20042. uvs.push(0.0, 0.0);
  20043. positions.push(halfSize, -halfSize, 0);
  20044. normals.push(0, 0, -1.0);
  20045. uvs.push(1.0, 0.0);
  20046. positions.push(halfSize, halfSize, 0);
  20047. normals.push(0, 0, -1.0);
  20048. uvs.push(1.0, 1.0);
  20049. positions.push(-halfSize, halfSize, 0);
  20050. normals.push(0, 0, -1.0);
  20051. uvs.push(0.0, 1.0);
  20052. // Indices
  20053. indices.push(0);
  20054. indices.push(1);
  20055. indices.push(2);
  20056. indices.push(0);
  20057. indices.push(2);
  20058. indices.push(3);
  20059. // Result
  20060. var vertexData = new BABYLON.VertexData();
  20061. vertexData.indices = indices;
  20062. vertexData.positions = positions;
  20063. vertexData.normals = normals;
  20064. vertexData.uvs = uvs;
  20065. return vertexData;
  20066. };
  20067. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20068. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20069. var indices = [];
  20070. var positions = [];
  20071. var normals = [];
  20072. var uvs = [];
  20073. radius = radius || 2;
  20074. tube = tube || 0.5;
  20075. radialSegments = radialSegments || 32;
  20076. tubularSegments = tubularSegments || 32;
  20077. p = p || 2;
  20078. q = q || 3;
  20079. // Helper
  20080. var getPos = function (angle) {
  20081. var cu = Math.cos(angle);
  20082. var su = Math.sin(angle);
  20083. var quOverP = q / p * angle;
  20084. var cs = Math.cos(quOverP);
  20085. var tx = radius * (2 + cs) * 0.5 * cu;
  20086. var ty = radius * (2 + cs) * su * 0.5;
  20087. var tz = radius * Math.sin(quOverP) * 0.5;
  20088. return new BABYLON.Vector3(tx, ty, tz);
  20089. };
  20090. for (var i = 0; i <= radialSegments; i++) {
  20091. var modI = i % radialSegments;
  20092. var u = modI / radialSegments * 2 * p * Math.PI;
  20093. var p1 = getPos(u);
  20094. var p2 = getPos(u + 0.01);
  20095. var tang = p2.subtract(p1);
  20096. var n = p2.add(p1);
  20097. var bitan = BABYLON.Vector3.Cross(tang, n);
  20098. n = BABYLON.Vector3.Cross(bitan, tang);
  20099. bitan.normalize();
  20100. n.normalize();
  20101. for (var j = 0; j < tubularSegments; j++) {
  20102. var modJ = j % tubularSegments;
  20103. var v = modJ / tubularSegments * 2 * Math.PI;
  20104. var cx = -tube * Math.cos(v);
  20105. var cy = tube * Math.sin(v);
  20106. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20107. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20108. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20109. uvs.push(i / radialSegments);
  20110. uvs.push(j / tubularSegments);
  20111. }
  20112. }
  20113. for (i = 0; i < radialSegments; i++) {
  20114. for (j = 0; j < tubularSegments; j++) {
  20115. var jNext = (j + 1) % tubularSegments;
  20116. var a = i * tubularSegments + j;
  20117. var b = (i + 1) * tubularSegments + j;
  20118. var c = (i + 1) * tubularSegments + jNext;
  20119. var d = i * tubularSegments + jNext;
  20120. indices.push(d);
  20121. indices.push(b);
  20122. indices.push(a);
  20123. indices.push(d);
  20124. indices.push(c);
  20125. indices.push(b);
  20126. }
  20127. }
  20128. // Normals
  20129. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20130. // Result
  20131. var vertexData = new BABYLON.VertexData();
  20132. vertexData.indices = indices;
  20133. vertexData.positions = positions;
  20134. vertexData.normals = normals;
  20135. vertexData.uvs = uvs;
  20136. return vertexData;
  20137. };
  20138. // Tools
  20139. VertexData.ComputeNormals = function (positions, indices, normals) {
  20140. var positionVectors = [];
  20141. var facesOfVertices = [];
  20142. var index;
  20143. for (index = 0; index < positions.length; index += 3) {
  20144. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20145. positionVectors.push(vector3);
  20146. facesOfVertices.push([]);
  20147. }
  20148. // Compute normals
  20149. var facesNormals = [];
  20150. for (index = 0; index < indices.length / 3; index++) {
  20151. var i1 = indices[index * 3];
  20152. var i2 = indices[index * 3 + 1];
  20153. var i3 = indices[index * 3 + 2];
  20154. var p1 = positionVectors[i1];
  20155. var p2 = positionVectors[i2];
  20156. var p3 = positionVectors[i3];
  20157. var p1p2 = p1.subtract(p2);
  20158. var p3p2 = p3.subtract(p2);
  20159. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20160. facesOfVertices[i1].push(index);
  20161. facesOfVertices[i2].push(index);
  20162. facesOfVertices[i3].push(index);
  20163. }
  20164. for (index = 0; index < positionVectors.length; index++) {
  20165. var faces = facesOfVertices[index];
  20166. var normal = BABYLON.Vector3.Zero();
  20167. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20168. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20169. }
  20170. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20171. normals[index * 3] = normal.x;
  20172. normals[index * 3 + 1] = normal.y;
  20173. normals[index * 3 + 2] = normal.z;
  20174. }
  20175. };
  20176. return VertexData;
  20177. })();
  20178. BABYLON.VertexData = VertexData;
  20179. })(BABYLON || (BABYLON = {}));
  20180. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20181. var BABYLON;
  20182. (function (BABYLON) {
  20183. var buildCamera = function (that, name) {
  20184. that._leftCamera.isIntermediate = true;
  20185. that.subCameras.push(that._leftCamera);
  20186. that.subCameras.push(that._rightCamera);
  20187. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20188. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20189. that._anaglyphPostProcess.onApply = function (effect) {
  20190. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20191. };
  20192. that._update();
  20193. };
  20194. var AnaglyphArcRotateCamera = (function (_super) {
  20195. __extends(AnaglyphArcRotateCamera, _super);
  20196. // ANY
  20197. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20198. _super.call(this, name, alpha, beta, radius, target, scene);
  20199. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20200. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20201. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20202. buildCamera(this, name);
  20203. }
  20204. AnaglyphArcRotateCamera.prototype._update = function () {
  20205. this._updateCamera(this._leftCamera);
  20206. this._updateCamera(this._rightCamera);
  20207. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20208. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20209. _super.prototype._update.call(this);
  20210. };
  20211. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20212. camera.beta = this.beta;
  20213. camera.radius = this.radius;
  20214. camera.minZ = this.minZ;
  20215. camera.maxZ = this.maxZ;
  20216. camera.fov = this.fov;
  20217. camera.target = this.target;
  20218. };
  20219. return AnaglyphArcRotateCamera;
  20220. })(BABYLON.ArcRotateCamera);
  20221. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20222. var AnaglyphFreeCamera = (function (_super) {
  20223. __extends(AnaglyphFreeCamera, _super);
  20224. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20225. _super.call(this, name, position, scene);
  20226. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20227. this._transformMatrix = new BABYLON.Matrix();
  20228. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20229. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20230. buildCamera(this, name);
  20231. }
  20232. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20233. var target = this.getTarget();
  20234. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20235. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20236. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20237. };
  20238. AnaglyphFreeCamera.prototype._update = function () {
  20239. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20240. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20241. this._updateCamera(this._leftCamera);
  20242. this._updateCamera(this._rightCamera);
  20243. _super.prototype._update.call(this);
  20244. };
  20245. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20246. camera.minZ = this.minZ;
  20247. camera.maxZ = this.maxZ;
  20248. camera.fov = this.fov;
  20249. camera.viewport = this.viewport;
  20250. camera.setTarget(this.getTarget());
  20251. };
  20252. return AnaglyphFreeCamera;
  20253. })(BABYLON.FreeCamera);
  20254. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20255. })(BABYLON || (BABYLON = {}));
  20256. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20257. var BABYLON;
  20258. (function (BABYLON) {
  20259. var AnaglyphPostProcess = (function (_super) {
  20260. __extends(AnaglyphPostProcess, _super);
  20261. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20262. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20263. }
  20264. return AnaglyphPostProcess;
  20265. })(BABYLON.PostProcess);
  20266. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20267. })(BABYLON || (BABYLON = {}));
  20268. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20269. var BABYLON;
  20270. (function (BABYLON) {
  20271. var Tags = (function () {
  20272. function Tags() {
  20273. }
  20274. Tags.EnableFor = function (obj) {
  20275. obj._tags = obj._tags || {};
  20276. obj.hasTags = function () {
  20277. return Tags.HasTags(obj);
  20278. };
  20279. obj.addTags = function (tagsString) {
  20280. return Tags.AddTagsTo(obj, tagsString);
  20281. };
  20282. obj.removeTags = function (tagsString) {
  20283. return Tags.RemoveTagsFrom(obj, tagsString);
  20284. };
  20285. obj.matchesTagsQuery = function (tagsQuery) {
  20286. return Tags.MatchesQuery(obj, tagsQuery);
  20287. };
  20288. };
  20289. Tags.DisableFor = function (obj) {
  20290. delete obj._tags;
  20291. delete obj.hasTags;
  20292. delete obj.addTags;
  20293. delete obj.removeTags;
  20294. delete obj.matchesTagsQuery;
  20295. };
  20296. Tags.HasTags = function (obj) {
  20297. if (!obj._tags) {
  20298. return false;
  20299. }
  20300. return !BABYLON.Tools.IsEmpty(obj._tags);
  20301. };
  20302. Tags.GetTags = function (obj) {
  20303. if (!obj._tags) {
  20304. return null;
  20305. }
  20306. return obj._tags;
  20307. };
  20308. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20309. // a tag cannot start with '||', '&&', and '!'
  20310. // it cannot contain whitespaces
  20311. Tags.AddTagsTo = function (obj, tagsString) {
  20312. if (!tagsString) {
  20313. return;
  20314. }
  20315. var tags = tagsString.split(" ");
  20316. for (var t in tags) {
  20317. Tags._AddTagTo(obj, tags[t]);
  20318. }
  20319. };
  20320. Tags._AddTagTo = function (obj, tag) {
  20321. tag = tag.trim();
  20322. if (tag === "" || tag === "true" || tag === "false") {
  20323. return;
  20324. }
  20325. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20326. return;
  20327. }
  20328. Tags.EnableFor(obj);
  20329. obj._tags[tag] = true;
  20330. };
  20331. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20332. if (!Tags.HasTags(obj)) {
  20333. return;
  20334. }
  20335. var tags = tagsString.split(" ");
  20336. for (var t in tags) {
  20337. Tags._RemoveTagFrom(obj, tags[t]);
  20338. }
  20339. };
  20340. Tags._RemoveTagFrom = function (obj, tag) {
  20341. delete obj._tags[tag];
  20342. };
  20343. Tags.MatchesQuery = function (obj, tagsQuery) {
  20344. if (tagsQuery === undefined) {
  20345. return true;
  20346. }
  20347. if (tagsQuery === "") {
  20348. return Tags.HasTags(obj);
  20349. }
  20350. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20351. return Tags.HasTags(obj) && obj._tags[r];
  20352. });
  20353. };
  20354. return Tags;
  20355. })();
  20356. BABYLON.Tags = Tags;
  20357. })(BABYLON || (BABYLON = {}));
  20358. //# sourceMappingURL=babylon.tags.js.map
  20359. var BABYLON;
  20360. (function (BABYLON) {
  20361. (function (Internals) {
  20362. var AndOrNotEvaluator = (function () {
  20363. function AndOrNotEvaluator() {
  20364. }
  20365. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20366. if (!query.match(/\([^\(\)]*\)/g)) {
  20367. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20368. } else {
  20369. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20370. // remove parenthesis
  20371. r = r.slice(1, r.length - 1);
  20372. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20373. });
  20374. }
  20375. if (query === "true") {
  20376. return true;
  20377. }
  20378. if (query === "false") {
  20379. return false;
  20380. }
  20381. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20382. };
  20383. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20384. evaluateCallback = evaluateCallback || (function (r) {
  20385. return r === "true" ? true : false;
  20386. });
  20387. var result;
  20388. var or = parenthesisContent.split("||");
  20389. for (var i in or) {
  20390. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20391. var and = ori.split("&&");
  20392. if (and.length > 1) {
  20393. for (var j = 0; j < and.length; ++j) {
  20394. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20395. if (andj !== "true" && andj !== "false") {
  20396. if (andj[0] === "!") {
  20397. result = !evaluateCallback(andj.substring(1));
  20398. } else {
  20399. result = evaluateCallback(andj);
  20400. }
  20401. } else {
  20402. result = andj === "true" ? true : false;
  20403. }
  20404. if (!result) {
  20405. ori = "false";
  20406. break;
  20407. }
  20408. }
  20409. }
  20410. if (result || ori === "true") {
  20411. result = true;
  20412. break;
  20413. }
  20414. // result equals false (or undefined)
  20415. if (ori !== "true" && ori !== "false") {
  20416. if (ori[0] === "!") {
  20417. result = !evaluateCallback(ori.substring(1));
  20418. } else {
  20419. result = evaluateCallback(ori);
  20420. }
  20421. } else {
  20422. result = ori === "true" ? true : false;
  20423. }
  20424. }
  20425. // the whole parenthesis scope is replaced by 'true' or 'false'
  20426. return result ? "true" : "false";
  20427. };
  20428. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20429. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20430. // remove whitespaces
  20431. r = r.replace(/[\s]/g, function () {
  20432. return "";
  20433. });
  20434. return r.length % 2 ? "!" : "";
  20435. });
  20436. booleanString = booleanString.trim();
  20437. if (booleanString === "!true") {
  20438. booleanString = "false";
  20439. } else if (booleanString === "!false") {
  20440. booleanString = "true";
  20441. }
  20442. return booleanString;
  20443. };
  20444. return AndOrNotEvaluator;
  20445. })();
  20446. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20447. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20448. var Internals = BABYLON.Internals;
  20449. })(BABYLON || (BABYLON = {}));
  20450. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20451. var BABYLON;
  20452. (function (BABYLON) {
  20453. var PostProcessRenderPass = (function () {
  20454. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20455. this._enabled = true;
  20456. this._refCount = 0;
  20457. this._name = name;
  20458. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20459. this.setRenderList(renderList);
  20460. this._renderTexture.onBeforeRender = beforeRender;
  20461. this._renderTexture.onAfterRender = afterRender;
  20462. this._scene = scene;
  20463. this._renderList = renderList;
  20464. }
  20465. // private
  20466. PostProcessRenderPass.prototype._incRefCount = function () {
  20467. if (this._refCount === 0) {
  20468. this._scene.customRenderTargets.push(this._renderTexture);
  20469. }
  20470. return ++this._refCount;
  20471. };
  20472. PostProcessRenderPass.prototype._decRefCount = function () {
  20473. this._refCount--;
  20474. if (this._refCount <= 0) {
  20475. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20476. }
  20477. return this._refCount;
  20478. };
  20479. PostProcessRenderPass.prototype._update = function () {
  20480. this.setRenderList(this._renderList);
  20481. };
  20482. // public
  20483. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20484. this._renderTexture.renderList = renderList;
  20485. };
  20486. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20487. return this._renderTexture;
  20488. };
  20489. return PostProcessRenderPass;
  20490. })();
  20491. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20492. })(BABYLON || (BABYLON = {}));
  20493. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20494. var BABYLON;
  20495. (function (BABYLON) {
  20496. var PostProcessRenderEffect = (function () {
  20497. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20498. this._engine = engine;
  20499. this._name = name;
  20500. this._singleInstance = singleInstance || true;
  20501. this._getPostProcess = getPostProcess;
  20502. this._cameras = [];
  20503. this._indicesForCamera = [];
  20504. this._postProcesses = {};
  20505. this._renderPasses = {};
  20506. this._renderEffectAsPasses = {};
  20507. }
  20508. PostProcessRenderEffect.prototype._update = function () {
  20509. for (var renderPassName in this._renderPasses) {
  20510. this._renderPasses[renderPassName]._update();
  20511. }
  20512. };
  20513. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20514. this._renderPasses[renderPass._name] = renderPass;
  20515. this._linkParameters();
  20516. };
  20517. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20518. delete this._renderPasses[renderPass._name];
  20519. this._linkParameters();
  20520. };
  20521. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20522. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20523. this._linkParameters();
  20524. };
  20525. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20526. for (var renderPassName in this._renderPasses) {
  20527. if (renderPassName === passName) {
  20528. return this._renderPasses[passName];
  20529. }
  20530. }
  20531. };
  20532. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20533. this._renderPasses = {};
  20534. this._linkParameters();
  20535. };
  20536. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20537. var cameraKey;
  20538. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20539. for (var i = 0; i < _cam.length; i++) {
  20540. var camera = _cam[i];
  20541. var cameraName = camera.name;
  20542. if (this._singleInstance) {
  20543. cameraKey = 0;
  20544. } else {
  20545. cameraKey = cameraName;
  20546. }
  20547. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20548. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20549. if (!this._indicesForCamera[cameraName]) {
  20550. this._indicesForCamera[cameraName] = [];
  20551. }
  20552. this._indicesForCamera[cameraName].push(index);
  20553. if (this._cameras.indexOf(camera) === -1) {
  20554. this._cameras[cameraName] = camera;
  20555. }
  20556. for (var passName in this._renderPasses) {
  20557. this._renderPasses[passName]._incRefCount();
  20558. }
  20559. }
  20560. this._linkParameters();
  20561. };
  20562. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20564. for (var i = 0; i < _cam.length; i++) {
  20565. var camera = _cam[i];
  20566. var cameraName = camera.name;
  20567. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20568. var index = this._cameras.indexOf(cameraName);
  20569. this._indicesForCamera.splice(index, 1);
  20570. this._cameras.splice(index, 1);
  20571. for (var passName in this._renderPasses) {
  20572. this._renderPasses[passName]._decRefCount();
  20573. }
  20574. }
  20575. };
  20576. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20577. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20578. for (var i = 0; i < _cam.length; i++) {
  20579. var camera = _cam[i];
  20580. var cameraName = camera.name;
  20581. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20582. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20583. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20584. }
  20585. }
  20586. for (var passName in this._renderPasses) {
  20587. this._renderPasses[passName]._incRefCount();
  20588. }
  20589. }
  20590. };
  20591. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20593. for (var i = 0; i < _cam.length; i++) {
  20594. var camera = _cam[i];
  20595. var cameraName = camera.Name;
  20596. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20597. for (var passName in this._renderPasses) {
  20598. this._renderPasses[passName]._decRefCount();
  20599. }
  20600. }
  20601. };
  20602. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20603. if (this._singleInstance) {
  20604. return this._postProcesses[0];
  20605. } else {
  20606. return this._postProcesses[camera.name];
  20607. }
  20608. };
  20609. PostProcessRenderEffect.prototype._linkParameters = function () {
  20610. var _this = this;
  20611. for (var index in this._postProcesses) {
  20612. if (this.applyParameters) {
  20613. this.applyParameters(this._postProcesses[index]);
  20614. }
  20615. this._postProcesses[index].onBeforeRender = function (effect) {
  20616. _this._linkTextures(effect);
  20617. };
  20618. }
  20619. };
  20620. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20621. for (var renderPassName in this._renderPasses) {
  20622. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20623. }
  20624. for (var renderEffectName in this._renderEffectAsPasses) {
  20625. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20626. }
  20627. };
  20628. return PostProcessRenderEffect;
  20629. })();
  20630. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20631. })(BABYLON || (BABYLON = {}));
  20632. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20633. var BABYLON;
  20634. (function (BABYLON) {
  20635. var PostProcessRenderPipeline = (function () {
  20636. function PostProcessRenderPipeline(engine, name) {
  20637. this._engine = engine;
  20638. this._name = name;
  20639. this._renderEffects = {};
  20640. this._renderEffectsForIsolatedPass = {};
  20641. this._cameras = [];
  20642. }
  20643. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20644. this._renderEffects[renderEffect._name] = renderEffect;
  20645. };
  20646. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20647. var renderEffects = this._renderEffects[renderEffectName];
  20648. if (!renderEffects) {
  20649. return;
  20650. }
  20651. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20652. };
  20653. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20654. var renderEffects = this._renderEffects[renderEffectName];
  20655. if (!renderEffects) {
  20656. return;
  20657. }
  20658. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20659. };
  20660. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20661. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20662. var indicesToDelete = [];
  20663. for (var i = 0; i < _cam.length; i++) {
  20664. var camera = _cam[i];
  20665. var cameraName = camera.name;
  20666. if (this._cameras.indexOf(camera) === -1) {
  20667. this._cameras[cameraName] = camera;
  20668. } else if (unique) {
  20669. indicesToDelete.push(i);
  20670. }
  20671. }
  20672. for (var i = 0; i < indicesToDelete.length; i++) {
  20673. cameras.splice(indicesToDelete[i], 1);
  20674. }
  20675. for (var renderEffectName in this._renderEffects) {
  20676. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20677. }
  20678. };
  20679. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20680. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20681. for (var renderEffectName in this._renderEffects) {
  20682. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20683. }
  20684. for (var i = 0; i < _cam.length; i++) {
  20685. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20686. }
  20687. };
  20688. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20689. var _this = this;
  20690. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20691. var pass = null;
  20692. for (var renderEffectName in this._renderEffects) {
  20693. pass = this._renderEffects[renderEffectName].getPass(passName);
  20694. if (pass != null) {
  20695. break;
  20696. }
  20697. }
  20698. if (pass === null) {
  20699. return;
  20700. }
  20701. for (var renderEffectName in this._renderEffects) {
  20702. this._renderEffects[renderEffectName]._disable(_cam);
  20703. }
  20704. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20705. for (var i = 0; i < _cam.length; i++) {
  20706. var camera = _cam[i];
  20707. var cameraName = camera.name;
  20708. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20709. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20710. });
  20711. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20712. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20713. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20714. }
  20715. };
  20716. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20717. var _this = this;
  20718. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20719. for (var i = 0; i < _cam.length; i++) {
  20720. var camera = _cam[i];
  20721. var cameraName = camera.name;
  20722. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20723. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20724. });
  20725. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20726. }
  20727. for (var renderEffectName in this._renderEffects) {
  20728. this._renderEffects[renderEffectName]._enable(_cam);
  20729. }
  20730. };
  20731. PostProcessRenderPipeline.prototype._update = function () {
  20732. for (var renderEffectName in this._renderEffects) {
  20733. this._renderEffects[renderEffectName]._update();
  20734. }
  20735. for (var i = 0; i < this._cameras.length; i++) {
  20736. var cameraName = this._cameras[i].name;
  20737. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20738. this._renderEffectsForIsolatedPass[cameraName]._update();
  20739. }
  20740. }
  20741. };
  20742. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20743. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20744. return PostProcessRenderPipeline;
  20745. })();
  20746. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20747. })(BABYLON || (BABYLON = {}));
  20748. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20749. var BABYLON;
  20750. (function (BABYLON) {
  20751. var PostProcessRenderPipelineManager = (function () {
  20752. function PostProcessRenderPipelineManager() {
  20753. this._renderPipelines = {};
  20754. }
  20755. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20756. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20757. };
  20758. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20759. var renderPipeline = this._renderPipelines[renderPipelineName];
  20760. if (!renderPipeline) {
  20761. return;
  20762. }
  20763. renderPipeline._attachCameras(cameras, unique);
  20764. };
  20765. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20766. var renderPipeline = this._renderPipelines[renderPipelineName];
  20767. if (!renderPipeline) {
  20768. return;
  20769. }
  20770. renderPipeline._detachCameras(cameras);
  20771. };
  20772. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20773. var renderPipeline = this._renderPipelines[renderPipelineName];
  20774. if (!renderPipeline) {
  20775. return;
  20776. }
  20777. renderPipeline._enableEffect(renderEffectName, cameras);
  20778. };
  20779. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20780. var renderPipeline = this._renderPipelines[renderPipelineName];
  20781. if (!renderPipeline) {
  20782. return;
  20783. }
  20784. renderPipeline._disableEffect(renderEffectName, cameras);
  20785. };
  20786. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20787. var renderPipeline = this._renderPipelines[renderPipelineName];
  20788. if (!renderPipeline) {
  20789. return;
  20790. }
  20791. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20792. };
  20793. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20794. var renderPipeline = this._renderPipelines[renderPipelineName];
  20795. if (!renderPipeline) {
  20796. return;
  20797. }
  20798. renderPipeline._disableDisplayOnlyPass(cameras);
  20799. };
  20800. PostProcessRenderPipelineManager.prototype.update = function () {
  20801. for (var renderPipelineName in this._renderPipelines) {
  20802. this._renderPipelines[renderPipelineName]._update();
  20803. }
  20804. };
  20805. return PostProcessRenderPipelineManager;
  20806. })();
  20807. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20808. })(BABYLON || (BABYLON = {}));
  20809. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20810. var BABYLON;
  20811. (function (BABYLON) {
  20812. var DisplayPassPostProcess = (function (_super) {
  20813. __extends(DisplayPassPostProcess, _super);
  20814. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20815. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20816. }
  20817. return DisplayPassPostProcess;
  20818. })(BABYLON.PostProcess);
  20819. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20820. })(BABYLON || (BABYLON = {}));
  20821. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20822. var BABYLON;
  20823. (function (BABYLON) {
  20824. var BoundingBoxRenderer = (function () {
  20825. function BoundingBoxRenderer(scene) {
  20826. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20827. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20828. this.showBackLines = true;
  20829. this.renderList = new BABYLON.SmartArray(32);
  20830. this._scene = scene;
  20831. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20832. attributes: ["position"],
  20833. uniforms: ["worldViewProjection", "color"]
  20834. });
  20835. var engine = this._scene.getEngine();
  20836. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20837. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20838. 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]);
  20839. }
  20840. BoundingBoxRenderer.prototype.reset = function () {
  20841. this.renderList.reset();
  20842. };
  20843. BoundingBoxRenderer.prototype.render = function () {
  20844. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20845. return;
  20846. }
  20847. var engine = this._scene.getEngine();
  20848. engine.setDepthWrite(false);
  20849. this._colorShader._preBind();
  20850. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20851. var boundingBox = this.renderList.data[boundingBoxIndex];
  20852. var min = boundingBox.minimum;
  20853. var max = boundingBox.maximum;
  20854. var diff = max.subtract(min);
  20855. var median = min.add(diff.scale(0.5));
  20856. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20857. // VBOs
  20858. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20859. if (this.showBackLines) {
  20860. // Back
  20861. engine.setDepthFunctionToGreaterOrEqual();
  20862. this._scene.resetCachedMaterial();
  20863. this._colorShader.setColor4("color", this.backColor.toColor4());
  20864. this._colorShader.bind(worldMatrix);
  20865. // Draw order
  20866. engine.draw(false, 0, 24);
  20867. }
  20868. // Front
  20869. engine.setDepthFunctionToLess();
  20870. this._scene.resetCachedMaterial();
  20871. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20872. this._colorShader.bind(worldMatrix);
  20873. // Draw order
  20874. engine.draw(false, 0, 24);
  20875. }
  20876. this._colorShader.unbind();
  20877. engine.setDepthFunctionToLessOrEqual();
  20878. engine.setDepthWrite(true);
  20879. };
  20880. BoundingBoxRenderer.prototype.dispose = function () {
  20881. this._colorShader.dispose();
  20882. this._vb.dispose();
  20883. this._scene.getEngine()._releaseBuffer(this._ib);
  20884. };
  20885. return BoundingBoxRenderer;
  20886. })();
  20887. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20888. })(BABYLON || (BABYLON = {}));
  20889. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20890. /**
  20891. * Based on jsTGALoader - Javascript loader for TGA file
  20892. * By Vincent Thibault
  20893. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20894. */
  20895. var BABYLON;
  20896. (function (BABYLON) {
  20897. (function (Internals) {
  20898. var TGATools = (function () {
  20899. function TGATools() {
  20900. }
  20901. TGATools.GetTGAHeader = function (data) {
  20902. var offset = 0;
  20903. var header = {
  20904. id_length: data[offset++],
  20905. colormap_type: data[offset++],
  20906. image_type: data[offset++],
  20907. colormap_index: data[offset++] | data[offset++] << 8,
  20908. colormap_length: data[offset++] | data[offset++] << 8,
  20909. colormap_size: data[offset++],
  20910. origin: [
  20911. data[offset++] | data[offset++] << 8,
  20912. data[offset++] | data[offset++] << 8
  20913. ],
  20914. width: data[offset++] | data[offset++] << 8,
  20915. height: data[offset++] | data[offset++] << 8,
  20916. pixel_size: data[offset++],
  20917. flags: data[offset++]
  20918. };
  20919. return header;
  20920. };
  20921. TGATools.UploadContent = function (gl, data) {
  20922. // Not enough data to contain header ?
  20923. if (data.length < 19) {
  20924. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20925. return;
  20926. }
  20927. // Read Header
  20928. var offset = 18;
  20929. var header = TGATools.GetTGAHeader(data);
  20930. // Assume it's a valid Targa file.
  20931. if (header.id_length + offset > data.length) {
  20932. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20933. return;
  20934. }
  20935. // Skip not needed data
  20936. offset += header.id_length;
  20937. var use_rle = false;
  20938. var use_pal = false;
  20939. var use_rgb = false;
  20940. var use_grey = false;
  20941. switch (header.image_type) {
  20942. case TGATools._TYPE_RLE_INDEXED:
  20943. use_rle = true;
  20944. case TGATools._TYPE_INDEXED:
  20945. use_pal = true;
  20946. break;
  20947. case TGATools._TYPE_RLE_RGB:
  20948. use_rle = true;
  20949. case TGATools._TYPE_RGB:
  20950. use_rgb = true;
  20951. break;
  20952. case TGATools._TYPE_RLE_GREY:
  20953. use_rle = true;
  20954. case TGATools._TYPE_GREY:
  20955. use_grey = true;
  20956. break;
  20957. }
  20958. var pixel_data;
  20959. var numAlphaBits = header.flags & 0xf;
  20960. var pixel_size = header.pixel_size >> 3;
  20961. var pixel_total = header.width * header.height * pixel_size;
  20962. // Read palettes
  20963. var palettes;
  20964. if (use_pal) {
  20965. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20966. }
  20967. // Read LRE
  20968. if (use_rle) {
  20969. pixel_data = new Uint8Array(pixel_total);
  20970. var c, count, i;
  20971. var localOffset = 0;
  20972. var pixels = new Uint8Array(pixel_size);
  20973. while (offset < pixel_total && localOffset < pixel_total) {
  20974. c = data[offset++];
  20975. count = (c & 0x7f) + 1;
  20976. // RLE pixels
  20977. if (c & 0x80) {
  20978. for (i = 0; i < pixel_size; ++i) {
  20979. pixels[i] = data[offset++];
  20980. }
  20981. for (i = 0; i < count; ++i) {
  20982. pixel_data.set(pixels, localOffset + i * pixel_size);
  20983. }
  20984. localOffset += pixel_size * count;
  20985. } else {
  20986. count *= pixel_size;
  20987. for (i = 0; i < count; ++i) {
  20988. pixel_data[localOffset + i] = data[offset++];
  20989. }
  20990. localOffset += count;
  20991. }
  20992. }
  20993. } else {
  20994. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20995. }
  20996. // Load to texture
  20997. var x_start, y_start, x_step, y_step, y_end, x_end;
  20998. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20999. default:
  21000. case TGATools._ORIGIN_UL:
  21001. x_start = 0;
  21002. x_step = 1;
  21003. x_end = header.width;
  21004. y_start = 0;
  21005. y_step = 1;
  21006. y_end = header.height;
  21007. break;
  21008. case TGATools._ORIGIN_BL:
  21009. x_start = 0;
  21010. x_step = 1;
  21011. x_end = header.width;
  21012. y_start = header.height - 1;
  21013. y_step = -1;
  21014. y_end = -1;
  21015. break;
  21016. case TGATools._ORIGIN_UR:
  21017. x_start = header.width - 1;
  21018. x_step = -1;
  21019. x_end = -1;
  21020. y_start = 0;
  21021. y_step = 1;
  21022. y_end = header.height;
  21023. break;
  21024. case TGATools._ORIGIN_BR:
  21025. x_start = header.width - 1;
  21026. x_step = -1;
  21027. x_end = -1;
  21028. y_start = header.height - 1;
  21029. y_step = -1;
  21030. y_end = -1;
  21031. break;
  21032. }
  21033. // Load the specify method
  21034. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21035. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21036. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21037. };
  21038. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21039. var image = pixel_data, colormap = palettes;
  21040. var width = header.width, height = header.height;
  21041. var color, i = 0, x, y;
  21042. var imageData = new Uint8Array(width * height * 4);
  21043. for (y = y_start; y !== y_end; y += y_step) {
  21044. for (x = x_start; x !== x_end; x += x_step, i++) {
  21045. color = image[i];
  21046. imageData[(x + width * y) * 4 + 3] = 255;
  21047. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21048. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21049. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21050. }
  21051. }
  21052. return imageData;
  21053. };
  21054. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21055. var image = pixel_data;
  21056. var width = header.width, height = header.height;
  21057. var color, i = 0, x, y;
  21058. var imageData = new Uint8Array(width * height * 4);
  21059. for (y = y_start; y !== y_end; y += y_step) {
  21060. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21061. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21062. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21063. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21064. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21065. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21066. }
  21067. }
  21068. return imageData;
  21069. };
  21070. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21071. var image = pixel_data;
  21072. var width = header.width, height = header.height;
  21073. var i = 0, x, y;
  21074. var imageData = new Uint8Array(width * height * 4);
  21075. for (y = y_start; y !== y_end; y += y_step) {
  21076. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21077. imageData[(x + width * y) * 4 + 3] = 255;
  21078. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21079. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21080. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21081. }
  21082. }
  21083. return imageData;
  21084. };
  21085. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21086. var image = pixel_data;
  21087. var width = header.width, height = header.height;
  21088. var i = 0, x, y;
  21089. var imageData = new Uint8Array(width * height * 4);
  21090. for (y = y_start; y !== y_end; y += y_step) {
  21091. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21092. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21093. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21094. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21095. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21096. }
  21097. }
  21098. return imageData;
  21099. };
  21100. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21101. var image = pixel_data;
  21102. var width = header.width, height = header.height;
  21103. var color, i = 0, x, y;
  21104. var imageData = new Uint8Array(width * height * 4);
  21105. for (y = y_start; y !== y_end; y += y_step) {
  21106. for (x = x_start; x !== x_end; x += x_step, i++) {
  21107. color = image[i];
  21108. imageData[(x + width * y) * 4 + 0] = color;
  21109. imageData[(x + width * y) * 4 + 1] = color;
  21110. imageData[(x + width * y) * 4 + 2] = color;
  21111. imageData[(x + width * y) * 4 + 3] = 255;
  21112. }
  21113. }
  21114. return imageData;
  21115. };
  21116. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21117. var image = pixel_data;
  21118. var width = header.width, height = header.height;
  21119. var i = 0, x, y;
  21120. var imageData = new Uint8Array(width * height * 4);
  21121. for (y = y_start; y !== y_end; y += y_step) {
  21122. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21123. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21124. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21125. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21126. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21127. }
  21128. }
  21129. return imageData;
  21130. };
  21131. TGATools._TYPE_NO_DATA = 0;
  21132. TGATools._TYPE_INDEXED = 1;
  21133. TGATools._TYPE_RGB = 2;
  21134. TGATools._TYPE_GREY = 3;
  21135. TGATools._TYPE_RLE_INDEXED = 9;
  21136. TGATools._TYPE_RLE_RGB = 10;
  21137. TGATools._TYPE_RLE_GREY = 11;
  21138. TGATools._ORIGIN_MASK = 0x30;
  21139. TGATools._ORIGIN_SHIFT = 0x04;
  21140. TGATools._ORIGIN_BL = 0x00;
  21141. TGATools._ORIGIN_BR = 0x01;
  21142. TGATools._ORIGIN_UL = 0x02;
  21143. TGATools._ORIGIN_UR = 0x03;
  21144. return TGATools;
  21145. })();
  21146. Internals.TGATools = TGATools;
  21147. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21148. var Internals = BABYLON.Internals;
  21149. })(BABYLON || (BABYLON = {}));
  21150. //# sourceMappingURL=babylon.tools.tga.js.map
  21151. var BABYLON;
  21152. (function (BABYLON) {
  21153. (function (Internals) {
  21154. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21155. // All values and structures referenced from:
  21156. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21157. var DDS_MAGIC = 0x20534444;
  21158. 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;
  21159. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21160. 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;
  21161. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21162. function FourCCToInt32(value) {
  21163. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21164. }
  21165. function Int32ToFourCC(value) {
  21166. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21167. }
  21168. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21169. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21170. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21171. var headerLengthInt = 31;
  21172. // Offsets into the header array
  21173. var off_magic = 0;
  21174. var off_size = 1;
  21175. var off_flags = 2;
  21176. var off_height = 3;
  21177. var off_width = 4;
  21178. var off_mipmapCount = 7;
  21179. var off_pfFlags = 20;
  21180. var off_pfFourCC = 21;
  21181. var off_RGBbpp = 22;
  21182. var off_RMask = 23;
  21183. var off_GMask = 24;
  21184. var off_BMask = 25;
  21185. var off_AMask = 26;
  21186. var off_caps1 = 27;
  21187. var off_caps2 = 28;
  21188. ;
  21189. var DDSTools = (function () {
  21190. function DDSTools() {
  21191. }
  21192. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21193. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21194. var mipmapCount = 1;
  21195. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21196. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21197. }
  21198. return {
  21199. width: header[off_width],
  21200. height: header[off_height],
  21201. mipmapCount: mipmapCount,
  21202. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21203. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21204. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21205. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21206. };
  21207. };
  21208. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21209. var byteArray = new Uint8Array(dataLength);
  21210. var srcData = new Uint8Array(arrayBuffer);
  21211. var index = 0;
  21212. for (var y = height - 1; y >= 0; y--) {
  21213. for (var x = 0; x < width; x++) {
  21214. var srcPos = dataOffset + (x + y * width) * 4;
  21215. byteArray[index + 2] = srcData[srcPos];
  21216. byteArray[index + 1] = srcData[srcPos + 1];
  21217. byteArray[index] = srcData[srcPos + 2];
  21218. byteArray[index + 3] = srcData[srcPos + 3];
  21219. index += 4;
  21220. }
  21221. }
  21222. return byteArray;
  21223. };
  21224. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21225. var byteArray = new Uint8Array(dataLength);
  21226. var srcData = new Uint8Array(arrayBuffer);
  21227. var index = 0;
  21228. for (var y = height - 1; y >= 0; y--) {
  21229. for (var x = 0; x < width; x++) {
  21230. var srcPos = dataOffset + (x + y * width) * 3;
  21231. byteArray[index + 2] = srcData[srcPos];
  21232. byteArray[index + 1] = srcData[srcPos + 1];
  21233. byteArray[index] = srcData[srcPos + 2];
  21234. index += 3;
  21235. }
  21236. }
  21237. return byteArray;
  21238. };
  21239. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21240. var byteArray = new Uint8Array(dataLength);
  21241. var srcData = new Uint8Array(arrayBuffer);
  21242. var index = 0;
  21243. for (var y = height - 1; y >= 0; y--) {
  21244. for (var x = 0; x < width; x++) {
  21245. var srcPos = dataOffset + (x + y * width);
  21246. byteArray[index] = srcData[srcPos];
  21247. index++;
  21248. }
  21249. }
  21250. return byteArray;
  21251. };
  21252. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21253. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21254. if (header[off_magic] != DDS_MAGIC) {
  21255. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21256. return;
  21257. }
  21258. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21259. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21260. return;
  21261. }
  21262. if (info.isFourCC) {
  21263. fourCC = header[off_pfFourCC];
  21264. switch (fourCC) {
  21265. case FOURCC_DXT1:
  21266. blockBytes = 8;
  21267. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21268. break;
  21269. case FOURCC_DXT3:
  21270. blockBytes = 16;
  21271. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21272. break;
  21273. case FOURCC_DXT5:
  21274. blockBytes = 16;
  21275. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21276. break;
  21277. default:
  21278. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21279. return;
  21280. }
  21281. }
  21282. mipmapCount = 1;
  21283. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21284. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21285. }
  21286. var bpp = header[off_RGBbpp];
  21287. for (var face = 0; face < faces; face++) {
  21288. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21289. width = header[off_width];
  21290. height = header[off_height];
  21291. dataOffset = header[off_size] + 4;
  21292. for (i = 0; i < mipmapCount; ++i) {
  21293. if (info.isRGB) {
  21294. if (bpp == 24) {
  21295. dataLength = width * height * 3;
  21296. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21297. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21298. } else {
  21299. dataLength = width * height * 4;
  21300. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21301. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21302. }
  21303. } else if (info.isLuminance) {
  21304. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21305. var unpaddedRowSize = width;
  21306. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21307. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21308. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21309. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21310. } else {
  21311. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21312. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21313. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21314. }
  21315. dataOffset += dataLength;
  21316. width *= 0.5;
  21317. height *= 0.5;
  21318. width = Math.max(1.0, width);
  21319. height = Math.max(1.0, height);
  21320. }
  21321. }
  21322. };
  21323. return DDSTools;
  21324. })();
  21325. Internals.DDSTools = DDSTools;
  21326. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21327. var Internals = BABYLON.Internals;
  21328. })(BABYLON || (BABYLON = {}));
  21329. //# sourceMappingURL=babylon.tools.dds.js.map
  21330. var BABYLON;
  21331. (function (BABYLON) {
  21332. var SmartArray = (function () {
  21333. function SmartArray(capacity) {
  21334. this.length = 0;
  21335. this._duplicateId = 0;
  21336. this.data = new Array(capacity);
  21337. this._id = SmartArray._GlobalId++;
  21338. }
  21339. SmartArray.prototype.push = function (value) {
  21340. this.data[this.length++] = value;
  21341. if (this.length > this.data.length) {
  21342. this.data.length *= 2;
  21343. }
  21344. if (!value.__smartArrayFlags) {
  21345. value.__smartArrayFlags = {};
  21346. }
  21347. value.__smartArrayFlags[this._id] = this._duplicateId;
  21348. };
  21349. SmartArray.prototype.pushNoDuplicate = function (value) {
  21350. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21351. return;
  21352. }
  21353. this.push(value);
  21354. };
  21355. SmartArray.prototype.sort = function (compareFn) {
  21356. this.data.sort(compareFn);
  21357. };
  21358. SmartArray.prototype.reset = function () {
  21359. this.length = 0;
  21360. this._duplicateId++;
  21361. };
  21362. SmartArray.prototype.concat = function (array) {
  21363. if (array.length === 0) {
  21364. return;
  21365. }
  21366. if (this.length + array.length > this.data.length) {
  21367. this.data.length = (this.length + array.length) * 2;
  21368. }
  21369. for (var index = 0; index < array.length; index++) {
  21370. this.data[this.length++] = (array.data || array)[index];
  21371. }
  21372. };
  21373. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21374. if (array.length === 0) {
  21375. return;
  21376. }
  21377. if (this.length + array.length > this.data.length) {
  21378. this.data.length = (this.length + array.length) * 2;
  21379. }
  21380. for (var index = 0; index < array.length; index++) {
  21381. var item = (array.data || array)[index];
  21382. this.pushNoDuplicate(item);
  21383. }
  21384. };
  21385. SmartArray.prototype.indexOf = function (value) {
  21386. var position = this.data.indexOf(value);
  21387. if (position >= this.length) {
  21388. return -1;
  21389. }
  21390. return position;
  21391. };
  21392. SmartArray._GlobalId = 0;
  21393. return SmartArray;
  21394. })();
  21395. BABYLON.SmartArray = SmartArray;
  21396. })(BABYLON || (BABYLON = {}));
  21397. //# sourceMappingURL=babylon.smartArray.js.map
  21398. var BABYLON;
  21399. (function (BABYLON) {
  21400. var CannonJSPlugin = (function () {
  21401. function CannonJSPlugin() {
  21402. this._registeredMeshes = [];
  21403. this._physicsMaterials = [];
  21404. this.updateBodyPosition = function (mesh) {
  21405. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21406. var registeredMesh = this._registeredMeshes[index];
  21407. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21408. var body = registeredMesh.body;
  21409. var center = mesh.getBoundingInfo().boundingBox.center;
  21410. body.position.set(center.x, center.z, center.y);
  21411. body.quaternion.x = mesh.rotationQuaternion.x;
  21412. body.quaternion.z = mesh.rotationQuaternion.y;
  21413. body.quaternion.y = mesh.rotationQuaternion.z;
  21414. body.quaternion.w = -mesh.rotationQuaternion.w;
  21415. return;
  21416. }
  21417. }
  21418. };
  21419. }
  21420. CannonJSPlugin.prototype.initialize = function (iterations) {
  21421. if (typeof iterations === "undefined") { iterations = 10; }
  21422. this._world = new CANNON.World();
  21423. this._world.broadphase = new CANNON.NaiveBroadphase();
  21424. this._world.solver.iterations = iterations;
  21425. };
  21426. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21427. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21428. };
  21429. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21430. this._world.step(delta);
  21431. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21432. var registeredMesh = this._registeredMeshes[index];
  21433. if (registeredMesh.isChild) {
  21434. continue;
  21435. }
  21436. // Body position
  21437. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21438. var deltaPos = registeredMesh.delta;
  21439. if (deltaPos) {
  21440. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21441. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21442. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21443. } else {
  21444. registeredMesh.mesh.position.x = bodyX;
  21445. registeredMesh.mesh.position.y = bodyZ;
  21446. registeredMesh.mesh.position.z = bodyY;
  21447. }
  21448. if (!registeredMesh.mesh.rotationQuaternion) {
  21449. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21450. }
  21451. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21452. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21453. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21454. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21455. }
  21456. };
  21457. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21458. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21459. };
  21460. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21461. this.unregisterMesh(mesh);
  21462. mesh.computeWorldMatrix(true);
  21463. switch (impostor) {
  21464. case BABYLON.PhysicsEngine.SphereImpostor:
  21465. var bbox = mesh.getBoundingInfo().boundingBox;
  21466. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21467. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21468. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21469. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21470. case BABYLON.PhysicsEngine.BoxImpostor:
  21471. bbox = mesh.getBoundingInfo().boundingBox;
  21472. var min = bbox.minimumWorld;
  21473. var max = bbox.maximumWorld;
  21474. var box = max.subtract(min).scale(0.5);
  21475. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21476. case BABYLON.PhysicsEngine.PlaneImpostor:
  21477. return this._createPlane(mesh, options);
  21478. case BABYLON.PhysicsEngine.MeshImpostor:
  21479. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21480. var rawFaces = mesh.getIndices();
  21481. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21482. }
  21483. return null;
  21484. };
  21485. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21486. var shape = new CANNON.Sphere(radius);
  21487. if (!options) {
  21488. return shape;
  21489. }
  21490. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21491. };
  21492. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21493. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21494. if (!options) {
  21495. return shape;
  21496. }
  21497. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21498. };
  21499. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21500. var shape = new CANNON.Plane();
  21501. if (!options) {
  21502. return shape;
  21503. }
  21504. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21505. };
  21506. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21507. var verts = [], faces = [];
  21508. mesh.computeWorldMatrix(true);
  21509. for (var i = 0; i < rawVerts.length; i += 3) {
  21510. var transformed = BABYLON.Vector3.Zero();
  21511. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21512. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21513. }
  21514. for (var j = 0; j < rawFaces.length; j += 3) {
  21515. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21516. }
  21517. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21518. if (!options) {
  21519. return shape;
  21520. }
  21521. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21522. };
  21523. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21524. var index;
  21525. var mat;
  21526. for (index = 0; index < this._physicsMaterials.length; index++) {
  21527. mat = this._physicsMaterials[index];
  21528. if (mat.friction === friction && mat.restitution === restitution) {
  21529. return mat;
  21530. }
  21531. }
  21532. var currentMat = new CANNON.Material();
  21533. currentMat.friction = friction;
  21534. currentMat.restitution = restitution;
  21535. this._physicsMaterials.push(currentMat);
  21536. for (index = 0; index < this._physicsMaterials.length; index++) {
  21537. mat = this._physicsMaterials[index];
  21538. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21539. contactMaterial.contactEquationStiffness = 1e10;
  21540. contactMaterial.contactEquationRegularizationTime = 10;
  21541. this._world.addContactMaterial(contactMaterial);
  21542. }
  21543. return currentMat;
  21544. };
  21545. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21546. var initialRotation = null;
  21547. if (mesh.rotationQuaternion) {
  21548. initialRotation = mesh.rotationQuaternion.clone();
  21549. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21550. }
  21551. // The delta between the mesh position and the mesh bounding box center
  21552. var bbox = mesh.getBoundingInfo().boundingBox;
  21553. var deltaPosition = mesh.position.subtract(bbox.center);
  21554. var material = this._addMaterial(friction, restitution);
  21555. var body = new CANNON.RigidBody(mass, shape, material);
  21556. if (initialRotation) {
  21557. body.quaternion.x = initialRotation.x;
  21558. body.quaternion.z = initialRotation.y;
  21559. body.quaternion.y = initialRotation.z;
  21560. body.quaternion.w = -initialRotation.w;
  21561. }
  21562. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21563. this._world.add(body);
  21564. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21565. return body;
  21566. };
  21567. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21568. var compoundShape = new CANNON.Compound();
  21569. for (var index = 0; index < parts.length; index++) {
  21570. var mesh = parts[index].mesh;
  21571. var shape = this.registerMesh(mesh, parts[index].impostor);
  21572. if (index == 0) {
  21573. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21574. } else {
  21575. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21576. }
  21577. }
  21578. var initialMesh = parts[0].mesh;
  21579. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21580. body.parts = parts;
  21581. return body;
  21582. };
  21583. CannonJSPlugin.prototype._unbindBody = function (body) {
  21584. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21585. var registeredMesh = this._registeredMeshes[index];
  21586. if (registeredMesh.body === body) {
  21587. registeredMesh.body = null;
  21588. registeredMesh.delta = 0;
  21589. }
  21590. }
  21591. };
  21592. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21593. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21594. var registeredMesh = this._registeredMeshes[index];
  21595. if (registeredMesh.mesh === mesh) {
  21596. // Remove body
  21597. if (registeredMesh.body) {
  21598. this._world.remove(registeredMesh.body);
  21599. this._unbindBody(registeredMesh.body);
  21600. }
  21601. this._registeredMeshes.splice(index, 1);
  21602. return;
  21603. }
  21604. }
  21605. };
  21606. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21607. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21608. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21609. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21610. var registeredMesh = this._registeredMeshes[index];
  21611. if (registeredMesh.mesh === mesh) {
  21612. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21613. return;
  21614. }
  21615. }
  21616. };
  21617. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21618. var body1 = null, body2 = null;
  21619. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21620. var registeredMesh = this._registeredMeshes[index];
  21621. if (registeredMesh.mesh === mesh1) {
  21622. body1 = registeredMesh.body;
  21623. } else if (registeredMesh.mesh === mesh2) {
  21624. body2 = registeredMesh.body;
  21625. }
  21626. }
  21627. if (!body1 || !body2) {
  21628. return false;
  21629. }
  21630. 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));
  21631. this._world.addConstraint(constraint);
  21632. return true;
  21633. };
  21634. CannonJSPlugin.prototype.dispose = function () {
  21635. while (this._registeredMeshes.length) {
  21636. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21637. }
  21638. };
  21639. CannonJSPlugin.prototype.isSupported = function () {
  21640. return window.CANNON !== undefined;
  21641. };
  21642. return CannonJSPlugin;
  21643. })();
  21644. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21645. })(BABYLON || (BABYLON = {}));
  21646. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21647. var BABYLON;
  21648. (function (BABYLON) {
  21649. var Condition = (function () {
  21650. function Condition(actionManager) {
  21651. this._actionManager = actionManager;
  21652. }
  21653. Condition.prototype.isValid = function () {
  21654. return true;
  21655. };
  21656. Condition.prototype._getProperty = function (propertyPath) {
  21657. return this._actionManager._getProperty(propertyPath);
  21658. };
  21659. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21660. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21661. };
  21662. return Condition;
  21663. })();
  21664. BABYLON.Condition = Condition;
  21665. var ValueCondition = (function (_super) {
  21666. __extends(ValueCondition, _super);
  21667. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21668. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21669. _super.call(this, actionManager);
  21670. this.propertyPath = propertyPath;
  21671. this.value = value;
  21672. this.operator = operator;
  21673. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21674. this._property = this._getProperty(this.propertyPath);
  21675. }
  21676. Object.defineProperty(ValueCondition, "IsEqual", {
  21677. get: function () {
  21678. return ValueCondition._IsEqual;
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Object.defineProperty(ValueCondition, "IsDifferent", {
  21684. get: function () {
  21685. return ValueCondition._IsDifferent;
  21686. },
  21687. enumerable: true,
  21688. configurable: true
  21689. });
  21690. Object.defineProperty(ValueCondition, "IsGreater", {
  21691. get: function () {
  21692. return ValueCondition._IsGreater;
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Object.defineProperty(ValueCondition, "IsLesser", {
  21698. get: function () {
  21699. return ValueCondition._IsLesser;
  21700. },
  21701. enumerable: true,
  21702. configurable: true
  21703. });
  21704. // Methods
  21705. ValueCondition.prototype.isValid = function () {
  21706. switch (this.operator) {
  21707. case ValueCondition.IsGreater:
  21708. return this._target[this._property] > this.value;
  21709. case ValueCondition.IsLesser:
  21710. return this._target[this._property] < this.value;
  21711. case ValueCondition.IsEqual:
  21712. case ValueCondition.IsDifferent:
  21713. var check;
  21714. if (this.value.equals) {
  21715. check = this.value.equals(this._target[this._property]);
  21716. } else {
  21717. check = this.value === this._target[this._property];
  21718. }
  21719. return this.operator === ValueCondition.IsEqual ? check : !check;
  21720. }
  21721. return false;
  21722. };
  21723. ValueCondition._IsEqual = 0;
  21724. ValueCondition._IsDifferent = 1;
  21725. ValueCondition._IsGreater = 2;
  21726. ValueCondition._IsLesser = 3;
  21727. return ValueCondition;
  21728. })(Condition);
  21729. BABYLON.ValueCondition = ValueCondition;
  21730. var PredicateCondition = (function (_super) {
  21731. __extends(PredicateCondition, _super);
  21732. function PredicateCondition(actionManager, predicate) {
  21733. _super.call(this, actionManager);
  21734. this.predicate = predicate;
  21735. }
  21736. PredicateCondition.prototype.isValid = function () {
  21737. return this.predicate();
  21738. };
  21739. return PredicateCondition;
  21740. })(Condition);
  21741. BABYLON.PredicateCondition = PredicateCondition;
  21742. var StateCondition = (function (_super) {
  21743. __extends(StateCondition, _super);
  21744. function StateCondition(actionManager, target, value) {
  21745. _super.call(this, actionManager);
  21746. this.value = value;
  21747. this._target = target;
  21748. }
  21749. // Methods
  21750. StateCondition.prototype.isValid = function () {
  21751. return this._target.state === this.value;
  21752. };
  21753. return StateCondition;
  21754. })(Condition);
  21755. BABYLON.StateCondition = StateCondition;
  21756. })(BABYLON || (BABYLON = {}));
  21757. //# sourceMappingURL=babylon.condition.js.map
  21758. var BABYLON;
  21759. (function (BABYLON) {
  21760. var Action = (function () {
  21761. function Action(triggerOptions, condition) {
  21762. this.triggerOptions = triggerOptions;
  21763. if (triggerOptions.parameter) {
  21764. this.trigger = triggerOptions.trigger;
  21765. this._triggerParameter = triggerOptions.parameter;
  21766. } else {
  21767. this.trigger = triggerOptions;
  21768. }
  21769. this._nextActiveAction = this;
  21770. this._condition = condition;
  21771. }
  21772. // Methods
  21773. Action.prototype._prepare = function () {
  21774. };
  21775. Action.prototype.getTriggerParameter = function () {
  21776. return this._triggerParameter;
  21777. };
  21778. Action.prototype._executeCurrent = function (evt) {
  21779. if (this._condition) {
  21780. var currentRenderId = this._actionManager.getScene().getRenderId();
  21781. // We cache the current evaluation for the current frame
  21782. if (this._condition._evaluationId === currentRenderId) {
  21783. if (!this._condition._currentResult) {
  21784. return;
  21785. }
  21786. } else {
  21787. this._condition._evaluationId = currentRenderId;
  21788. if (!this._condition.isValid()) {
  21789. this._condition._currentResult = false;
  21790. return;
  21791. }
  21792. this._condition._currentResult = true;
  21793. }
  21794. }
  21795. this._nextActiveAction.execute(evt);
  21796. if (this._nextActiveAction._child) {
  21797. if (!this._nextActiveAction._child._actionManager) {
  21798. this._nextActiveAction._child._actionManager = this._actionManager;
  21799. }
  21800. this._nextActiveAction = this._nextActiveAction._child;
  21801. } else {
  21802. this._nextActiveAction = this;
  21803. }
  21804. };
  21805. Action.prototype.execute = function (evt) {
  21806. };
  21807. Action.prototype.then = function (action) {
  21808. this._child = action;
  21809. action._actionManager = this._actionManager;
  21810. action._prepare();
  21811. return action;
  21812. };
  21813. Action.prototype._getProperty = function (propertyPath) {
  21814. return this._actionManager._getProperty(propertyPath);
  21815. };
  21816. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21817. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21818. };
  21819. return Action;
  21820. })();
  21821. BABYLON.Action = Action;
  21822. })(BABYLON || (BABYLON = {}));
  21823. //# sourceMappingURL=babylon.action.js.map
  21824. var BABYLON;
  21825. (function (BABYLON) {
  21826. var ActionEvent = (function () {
  21827. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21828. this.source = source;
  21829. this.pointerX = pointerX;
  21830. this.pointerY = pointerY;
  21831. this.meshUnderPointer = meshUnderPointer;
  21832. this.sourceEvent = sourceEvent;
  21833. }
  21834. ActionEvent.CreateNew = function (source, evt) {
  21835. var scene = source.getScene();
  21836. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21837. };
  21838. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21839. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21840. };
  21841. return ActionEvent;
  21842. })();
  21843. BABYLON.ActionEvent = ActionEvent;
  21844. var ActionManager = (function () {
  21845. function ActionManager(scene) {
  21846. // Members
  21847. this.actions = new Array();
  21848. this._scene = scene;
  21849. scene._actionManagers.push(this);
  21850. }
  21851. Object.defineProperty(ActionManager, "NothingTrigger", {
  21852. get: function () {
  21853. return ActionManager._NothingTrigger;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21859. get: function () {
  21860. return ActionManager._OnPickTrigger;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21866. get: function () {
  21867. return ActionManager._OnLeftPickTrigger;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21873. get: function () {
  21874. return ActionManager._OnRightPickTrigger;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21880. get: function () {
  21881. return ActionManager._OnCenterPickTrigger;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21887. get: function () {
  21888. return ActionManager._OnPointerOverTrigger;
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21894. get: function () {
  21895. return ActionManager._OnPointerOutTrigger;
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21901. get: function () {
  21902. return ActionManager._OnEveryFrameTrigger;
  21903. },
  21904. enumerable: true,
  21905. configurable: true
  21906. });
  21907. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21908. get: function () {
  21909. return ActionManager._OnIntersectionEnterTrigger;
  21910. },
  21911. enumerable: true,
  21912. configurable: true
  21913. });
  21914. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21915. get: function () {
  21916. return ActionManager._OnIntersectionExitTrigger;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21922. get: function () {
  21923. return ActionManager._OnKeyDownTrigger;
  21924. },
  21925. enumerable: true,
  21926. configurable: true
  21927. });
  21928. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21929. get: function () {
  21930. return ActionManager._OnKeyUpTrigger;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. // Methods
  21936. ActionManager.prototype.dispose = function () {
  21937. var index = this._scene._actionManagers.indexOf(this);
  21938. if (index > -1) {
  21939. this._scene._actionManagers.splice(index, 1);
  21940. }
  21941. };
  21942. ActionManager.prototype.getScene = function () {
  21943. return this._scene;
  21944. };
  21945. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21946. for (var index = 0; index < this.actions.length; index++) {
  21947. var action = this.actions[index];
  21948. if (triggers.indexOf(action.trigger) > -1) {
  21949. return true;
  21950. }
  21951. }
  21952. return false;
  21953. };
  21954. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21955. get: function () {
  21956. for (var index = 0; index < this.actions.length; index++) {
  21957. var action = this.actions[index];
  21958. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21959. return true;
  21960. }
  21961. }
  21962. return false;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21968. get: function () {
  21969. for (var index = 0; index < this.actions.length; index++) {
  21970. var action = this.actions[index];
  21971. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21972. return true;
  21973. }
  21974. }
  21975. return false;
  21976. },
  21977. enumerable: true,
  21978. configurable: true
  21979. });
  21980. ActionManager.prototype.registerAction = function (action) {
  21981. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21982. if (this.getScene().actionManager !== this) {
  21983. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21984. return null;
  21985. }
  21986. }
  21987. this.actions.push(action);
  21988. action._actionManager = this;
  21989. action._prepare();
  21990. return action;
  21991. };
  21992. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21993. for (var index = 0; index < this.actions.length; index++) {
  21994. var action = this.actions[index];
  21995. if (action.trigger === trigger) {
  21996. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21997. var parameter = action.getTriggerParameter();
  21998. if (parameter) {
  21999. if (evt.sourceEvent.key !== parameter) {
  22000. continue;
  22001. }
  22002. }
  22003. }
  22004. action._executeCurrent(evt);
  22005. }
  22006. }
  22007. };
  22008. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22009. var properties = propertyPath.split(".");
  22010. for (var index = 0; index < properties.length - 1; index++) {
  22011. target = target[properties[index]];
  22012. }
  22013. return target;
  22014. };
  22015. ActionManager.prototype._getProperty = function (propertyPath) {
  22016. var properties = propertyPath.split(".");
  22017. return properties[properties.length - 1];
  22018. };
  22019. ActionManager._NothingTrigger = 0;
  22020. ActionManager._OnPickTrigger = 1;
  22021. ActionManager._OnLeftPickTrigger = 2;
  22022. ActionManager._OnRightPickTrigger = 3;
  22023. ActionManager._OnCenterPickTrigger = 4;
  22024. ActionManager._OnPointerOverTrigger = 5;
  22025. ActionManager._OnPointerOutTrigger = 6;
  22026. ActionManager._OnEveryFrameTrigger = 7;
  22027. ActionManager._OnIntersectionEnterTrigger = 8;
  22028. ActionManager._OnIntersectionExitTrigger = 9;
  22029. ActionManager._OnKeyDownTrigger = 10;
  22030. ActionManager._OnKeyUpTrigger = 11;
  22031. return ActionManager;
  22032. })();
  22033. BABYLON.ActionManager = ActionManager;
  22034. })(BABYLON || (BABYLON = {}));
  22035. //# sourceMappingURL=babylon.actionManager.js.map
  22036. var BABYLON;
  22037. (function (BABYLON) {
  22038. var InterpolateValueAction = (function (_super) {
  22039. __extends(InterpolateValueAction, _super);
  22040. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22041. if (typeof duration === "undefined") { duration = 1000; }
  22042. _super.call(this, triggerOptions, condition);
  22043. this.propertyPath = propertyPath;
  22044. this.value = value;
  22045. this.duration = duration;
  22046. this.stopOtherAnimations = stopOtherAnimations;
  22047. this._target = target;
  22048. }
  22049. InterpolateValueAction.prototype._prepare = function () {
  22050. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22051. this._property = this._getProperty(this.propertyPath);
  22052. };
  22053. InterpolateValueAction.prototype.execute = function () {
  22054. var scene = this._actionManager.getScene();
  22055. var keys = [
  22056. {
  22057. frame: 0,
  22058. value: this._target[this._property]
  22059. }, {
  22060. frame: 100,
  22061. value: this.value
  22062. }
  22063. ];
  22064. var dataType;
  22065. if (typeof this.value === "number") {
  22066. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22067. } else if (this.value instanceof BABYLON.Color3) {
  22068. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22069. } else if (this.value instanceof BABYLON.Vector3) {
  22070. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22071. } else if (this.value instanceof BABYLON.Matrix) {
  22072. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22073. } else if (this.value instanceof BABYLON.Quaternion) {
  22074. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22075. } else {
  22076. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22077. return;
  22078. }
  22079. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22080. animation.setKeys(keys);
  22081. if (this.stopOtherAnimations) {
  22082. scene.stopAnimation(this._target);
  22083. }
  22084. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22085. };
  22086. return InterpolateValueAction;
  22087. })(BABYLON.Action);
  22088. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22089. })(BABYLON || (BABYLON = {}));
  22090. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22091. var BABYLON;
  22092. (function (BABYLON) {
  22093. var SwitchBooleanAction = (function (_super) {
  22094. __extends(SwitchBooleanAction, _super);
  22095. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22096. _super.call(this, triggerOptions, condition);
  22097. this.propertyPath = propertyPath;
  22098. this._target = target;
  22099. }
  22100. SwitchBooleanAction.prototype._prepare = function () {
  22101. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22102. this._property = this._getProperty(this.propertyPath);
  22103. };
  22104. SwitchBooleanAction.prototype.execute = function () {
  22105. this._target[this._property] = !this._target[this._property];
  22106. };
  22107. return SwitchBooleanAction;
  22108. })(BABYLON.Action);
  22109. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22110. var SetStateAction = (function (_super) {
  22111. __extends(SetStateAction, _super);
  22112. function SetStateAction(triggerOptions, target, value, condition) {
  22113. _super.call(this, triggerOptions, condition);
  22114. this.value = value;
  22115. this._target = target;
  22116. }
  22117. SetStateAction.prototype.execute = function () {
  22118. this._target.state = this.value;
  22119. };
  22120. return SetStateAction;
  22121. })(BABYLON.Action);
  22122. BABYLON.SetStateAction = SetStateAction;
  22123. var SetValueAction = (function (_super) {
  22124. __extends(SetValueAction, _super);
  22125. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22126. _super.call(this, triggerOptions, condition);
  22127. this.propertyPath = propertyPath;
  22128. this.value = value;
  22129. this._target = target;
  22130. }
  22131. SetValueAction.prototype._prepare = function () {
  22132. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22133. this._property = this._getProperty(this.propertyPath);
  22134. };
  22135. SetValueAction.prototype.execute = function () {
  22136. this._target[this._property] = this.value;
  22137. };
  22138. return SetValueAction;
  22139. })(BABYLON.Action);
  22140. BABYLON.SetValueAction = SetValueAction;
  22141. var IncrementValueAction = (function (_super) {
  22142. __extends(IncrementValueAction, _super);
  22143. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22144. _super.call(this, triggerOptions, condition);
  22145. this.propertyPath = propertyPath;
  22146. this.value = value;
  22147. this._target = target;
  22148. }
  22149. IncrementValueAction.prototype._prepare = function () {
  22150. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22151. this._property = this._getProperty(this.propertyPath);
  22152. if (typeof this._target[this._property] !== "number") {
  22153. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22154. }
  22155. };
  22156. IncrementValueAction.prototype.execute = function () {
  22157. this._target[this._property] += this.value;
  22158. };
  22159. return IncrementValueAction;
  22160. })(BABYLON.Action);
  22161. BABYLON.IncrementValueAction = IncrementValueAction;
  22162. var PlayAnimationAction = (function (_super) {
  22163. __extends(PlayAnimationAction, _super);
  22164. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22165. _super.call(this, triggerOptions, condition);
  22166. this.from = from;
  22167. this.to = to;
  22168. this.loop = loop;
  22169. this._target = target;
  22170. }
  22171. PlayAnimationAction.prototype._prepare = function () {
  22172. };
  22173. PlayAnimationAction.prototype.execute = function () {
  22174. var scene = this._actionManager.getScene();
  22175. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22176. };
  22177. return PlayAnimationAction;
  22178. })(BABYLON.Action);
  22179. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22180. var StopAnimationAction = (function (_super) {
  22181. __extends(StopAnimationAction, _super);
  22182. function StopAnimationAction(triggerOptions, target, condition) {
  22183. _super.call(this, triggerOptions, condition);
  22184. this._target = target;
  22185. }
  22186. StopAnimationAction.prototype._prepare = function () {
  22187. };
  22188. StopAnimationAction.prototype.execute = function () {
  22189. var scene = this._actionManager.getScene();
  22190. scene.stopAnimation(this._target);
  22191. };
  22192. return StopAnimationAction;
  22193. })(BABYLON.Action);
  22194. BABYLON.StopAnimationAction = StopAnimationAction;
  22195. var DoNothingAction = (function (_super) {
  22196. __extends(DoNothingAction, _super);
  22197. function DoNothingAction(triggerOptions, condition) {
  22198. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22199. _super.call(this, triggerOptions, condition);
  22200. }
  22201. DoNothingAction.prototype.execute = function () {
  22202. };
  22203. return DoNothingAction;
  22204. })(BABYLON.Action);
  22205. BABYLON.DoNothingAction = DoNothingAction;
  22206. var CombineAction = (function (_super) {
  22207. __extends(CombineAction, _super);
  22208. function CombineAction(triggerOptions, children, condition) {
  22209. _super.call(this, triggerOptions, condition);
  22210. this.children = children;
  22211. }
  22212. CombineAction.prototype._prepare = function () {
  22213. for (var index = 0; index < this.children.length; index++) {
  22214. this.children[index]._actionManager = this._actionManager;
  22215. this.children[index]._prepare();
  22216. }
  22217. };
  22218. CombineAction.prototype.execute = function (evt) {
  22219. for (var index = 0; index < this.children.length; index++) {
  22220. this.children[index].execute(evt);
  22221. }
  22222. };
  22223. return CombineAction;
  22224. })(BABYLON.Action);
  22225. BABYLON.CombineAction = CombineAction;
  22226. var ExecuteCodeAction = (function (_super) {
  22227. __extends(ExecuteCodeAction, _super);
  22228. function ExecuteCodeAction(triggerOptions, func, condition) {
  22229. _super.call(this, triggerOptions, condition);
  22230. this.func = func;
  22231. }
  22232. ExecuteCodeAction.prototype.execute = function (evt) {
  22233. this.func(evt);
  22234. };
  22235. return ExecuteCodeAction;
  22236. })(BABYLON.Action);
  22237. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22238. var SetParentAction = (function (_super) {
  22239. __extends(SetParentAction, _super);
  22240. function SetParentAction(triggerOptions, target, parent, condition) {
  22241. _super.call(this, triggerOptions, condition);
  22242. this._target = target;
  22243. this._parent = parent;
  22244. }
  22245. SetParentAction.prototype._prepare = function () {
  22246. };
  22247. SetParentAction.prototype.execute = function () {
  22248. if (this._target.parent === this._parent) {
  22249. return;
  22250. }
  22251. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22252. invertParentWorldMatrix.invert();
  22253. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22254. this._target.parent = this._parent;
  22255. };
  22256. return SetParentAction;
  22257. })(BABYLON.Action);
  22258. BABYLON.SetParentAction = SetParentAction;
  22259. })(BABYLON || (BABYLON = {}));
  22260. //# sourceMappingURL=babylon.directActions.js.map
  22261. var BABYLON;
  22262. (function (BABYLON) {
  22263. var Geometry = (function () {
  22264. function Geometry(id, scene, vertexData, updatable, mesh) {
  22265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22266. this._totalVertices = 0;
  22267. this._indices = [];
  22268. this.id = id;
  22269. this._engine = scene.getEngine();
  22270. this._meshes = [];
  22271. this._scene = scene;
  22272. // vertexData
  22273. if (vertexData) {
  22274. this.setAllVerticesData(vertexData, updatable);
  22275. } else {
  22276. this._totalVertices = 0;
  22277. this._indices = [];
  22278. }
  22279. // applyToMesh
  22280. if (mesh) {
  22281. this.applyToMesh(mesh);
  22282. }
  22283. }
  22284. Geometry.prototype.getScene = function () {
  22285. return this._scene;
  22286. };
  22287. Geometry.prototype.getEngine = function () {
  22288. return this._engine;
  22289. };
  22290. Geometry.prototype.isReady = function () {
  22291. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22292. };
  22293. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22294. vertexData.applyToGeometry(this, updatable);
  22295. };
  22296. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22297. this._vertexBuffers = this._vertexBuffers || {};
  22298. if (this._vertexBuffers[kind]) {
  22299. this._vertexBuffers[kind].dispose();
  22300. }
  22301. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22302. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22303. stride = this._vertexBuffers[kind].getStrideSize();
  22304. this._totalVertices = data.length / stride;
  22305. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22306. var meshes = this._meshes;
  22307. var numOfMeshes = meshes.length;
  22308. for (var index = 0; index < numOfMeshes; index++) {
  22309. var mesh = meshes[index];
  22310. mesh._resetPointsArrayCache();
  22311. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22312. mesh._createGlobalSubMesh();
  22313. mesh.computeWorldMatrix(true);
  22314. }
  22315. }
  22316. };
  22317. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22318. var vertexBuffer = this.getVertexBuffer(kind);
  22319. if (!vertexBuffer) {
  22320. return;
  22321. }
  22322. vertexBuffer.updateDirectly(data, offset);
  22323. };
  22324. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22325. var vertexBuffer = this.getVertexBuffer(kind);
  22326. if (!vertexBuffer) {
  22327. return;
  22328. }
  22329. vertexBuffer.update(data);
  22330. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22331. var extend;
  22332. var stride = vertexBuffer.getStrideSize();
  22333. this._totalVertices = data.length / stride;
  22334. if (updateExtends) {
  22335. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22336. }
  22337. var meshes = this._meshes;
  22338. var numOfMeshes = meshes.length;
  22339. for (var index = 0; index < numOfMeshes; index++) {
  22340. var mesh = meshes[index];
  22341. mesh._resetPointsArrayCache();
  22342. if (updateExtends) {
  22343. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22344. }
  22345. }
  22346. }
  22347. };
  22348. Geometry.prototype.getTotalVertices = function () {
  22349. if (!this.isReady()) {
  22350. return 0;
  22351. }
  22352. return this._totalVertices;
  22353. };
  22354. Geometry.prototype.getVerticesData = function (kind) {
  22355. var vertexBuffer = this.getVertexBuffer(kind);
  22356. if (!vertexBuffer) {
  22357. return null;
  22358. }
  22359. return vertexBuffer.getData();
  22360. };
  22361. Geometry.prototype.getVertexBuffer = function (kind) {
  22362. if (!this.isReady()) {
  22363. return null;
  22364. }
  22365. return this._vertexBuffers[kind];
  22366. };
  22367. Geometry.prototype.getVertexBuffers = function () {
  22368. if (!this.isReady()) {
  22369. return null;
  22370. }
  22371. return this._vertexBuffers;
  22372. };
  22373. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22374. if (!this._vertexBuffers) {
  22375. if (this._delayInfo) {
  22376. return this._delayInfo.indexOf(kind) !== -1;
  22377. }
  22378. return false;
  22379. }
  22380. return this._vertexBuffers[kind] !== undefined;
  22381. };
  22382. Geometry.prototype.getVerticesDataKinds = function () {
  22383. var result = [];
  22384. if (!this._vertexBuffers && this._delayInfo) {
  22385. for (var kind in this._delayInfo) {
  22386. result.push(kind);
  22387. }
  22388. } else {
  22389. for (kind in this._vertexBuffers) {
  22390. result.push(kind);
  22391. }
  22392. }
  22393. return result;
  22394. };
  22395. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22396. if (this._indexBuffer) {
  22397. this._engine._releaseBuffer(this._indexBuffer);
  22398. }
  22399. this._indices = indices;
  22400. if (this._meshes.length !== 0 && this._indices) {
  22401. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22402. }
  22403. if (totalVertices !== undefined) {
  22404. this._totalVertices = totalVertices;
  22405. }
  22406. var meshes = this._meshes;
  22407. var numOfMeshes = meshes.length;
  22408. for (var index = 0; index < numOfMeshes; index++) {
  22409. meshes[index]._createGlobalSubMesh();
  22410. }
  22411. };
  22412. Geometry.prototype.getTotalIndices = function () {
  22413. if (!this.isReady()) {
  22414. return 0;
  22415. }
  22416. return this._indices.length;
  22417. };
  22418. Geometry.prototype.getIndices = function () {
  22419. if (!this.isReady()) {
  22420. return null;
  22421. }
  22422. return this._indices;
  22423. };
  22424. Geometry.prototype.getIndexBuffer = function () {
  22425. if (!this.isReady()) {
  22426. return null;
  22427. }
  22428. return this._indexBuffer;
  22429. };
  22430. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22431. var meshes = this._meshes;
  22432. var index = meshes.indexOf(mesh);
  22433. if (index === -1) {
  22434. return;
  22435. }
  22436. for (var kind in this._vertexBuffers) {
  22437. this._vertexBuffers[kind].dispose();
  22438. }
  22439. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22440. this._indexBuffer = null;
  22441. }
  22442. meshes.splice(index, 1);
  22443. mesh._geometry = null;
  22444. if (meshes.length === 0 && shouldDispose) {
  22445. this.dispose();
  22446. }
  22447. };
  22448. Geometry.prototype.applyToMesh = function (mesh) {
  22449. if (mesh._geometry === this) {
  22450. return;
  22451. }
  22452. var previousGeometry = mesh._geometry;
  22453. if (previousGeometry) {
  22454. previousGeometry.releaseForMesh(mesh);
  22455. }
  22456. var meshes = this._meshes;
  22457. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22458. mesh._geometry = this;
  22459. this._scene.pushGeometry(this);
  22460. meshes.push(mesh);
  22461. if (this.isReady()) {
  22462. this._applyToMesh(mesh);
  22463. } else {
  22464. mesh._boundingInfo = this._boundingInfo;
  22465. }
  22466. };
  22467. Geometry.prototype._applyToMesh = function (mesh) {
  22468. var numOfMeshes = this._meshes.length;
  22469. for (var kind in this._vertexBuffers) {
  22470. if (numOfMeshes === 1) {
  22471. this._vertexBuffers[kind].create();
  22472. }
  22473. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22474. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22475. mesh._resetPointsArrayCache();
  22476. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22477. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22478. mesh._createGlobalSubMesh();
  22479. //bounding info was just created again, world matrix should be applied again.
  22480. mesh._updateBoundingInfo();
  22481. }
  22482. }
  22483. // indexBuffer
  22484. if (numOfMeshes === 1 && this._indices) {
  22485. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22486. }
  22487. if (this._indexBuffer) {
  22488. this._indexBuffer.references = numOfMeshes;
  22489. }
  22490. };
  22491. Geometry.prototype.load = function (scene, onLoaded) {
  22492. var _this = this;
  22493. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22494. return;
  22495. }
  22496. if (this.isReady()) {
  22497. if (onLoaded) {
  22498. onLoaded();
  22499. }
  22500. return;
  22501. }
  22502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22503. scene._addPendingData(this);
  22504. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22505. _this._delayLoadingFunction(JSON.parse(data), _this);
  22506. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22507. _this._delayInfo = [];
  22508. scene._removePendingData(_this);
  22509. var meshes = _this._meshes;
  22510. var numOfMeshes = meshes.length;
  22511. for (var index = 0; index < numOfMeshes; index++) {
  22512. _this._applyToMesh(meshes[index]);
  22513. }
  22514. if (onLoaded) {
  22515. onLoaded();
  22516. }
  22517. }, function () {
  22518. }, scene.database);
  22519. };
  22520. Geometry.prototype.dispose = function () {
  22521. var meshes = this._meshes;
  22522. var numOfMeshes = meshes.length;
  22523. var index;
  22524. for (index = 0; index < numOfMeshes; index++) {
  22525. this.releaseForMesh(meshes[index]);
  22526. }
  22527. this._meshes = [];
  22528. for (var kind in this._vertexBuffers) {
  22529. this._vertexBuffers[kind].dispose();
  22530. }
  22531. this._vertexBuffers = [];
  22532. this._totalVertices = 0;
  22533. if (this._indexBuffer) {
  22534. this._engine._releaseBuffer(this._indexBuffer);
  22535. }
  22536. this._indexBuffer = null;
  22537. this._indices = [];
  22538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22539. this.delayLoadingFile = null;
  22540. this._delayLoadingFunction = null;
  22541. this._delayInfo = [];
  22542. this._boundingInfo = null; // todo: .dispose()
  22543. var geometries = this._scene.getGeometries();
  22544. index = geometries.indexOf(this);
  22545. if (index > -1) {
  22546. geometries.splice(index, 1);
  22547. }
  22548. };
  22549. Geometry.prototype.copy = function (id) {
  22550. var vertexData = new BABYLON.VertexData();
  22551. vertexData.indices = [];
  22552. var indices = this.getIndices();
  22553. for (var index = 0; index < indices.length; index++) {
  22554. vertexData.indices.push(indices[index]);
  22555. }
  22556. var updatable = false;
  22557. var stopChecking = false;
  22558. for (var kind in this._vertexBuffers) {
  22559. vertexData.set(this.getVerticesData(kind), kind);
  22560. if (!stopChecking) {
  22561. updatable = this.getVertexBuffer(kind).isUpdatable();
  22562. stopChecking = !updatable;
  22563. }
  22564. }
  22565. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22566. geometry.delayLoadState = this.delayLoadState;
  22567. geometry.delayLoadingFile = this.delayLoadingFile;
  22568. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22569. for (kind in this._delayInfo) {
  22570. geometry._delayInfo = geometry._delayInfo || [];
  22571. geometry._delayInfo.push(kind);
  22572. }
  22573. // Bounding info
  22574. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22575. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22576. return geometry;
  22577. };
  22578. // Statics
  22579. Geometry.ExtractFromMesh = function (mesh, id) {
  22580. var geometry = mesh._geometry;
  22581. if (!geometry) {
  22582. return null;
  22583. }
  22584. return geometry.copy(id);
  22585. };
  22586. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22587. // be aware Math.random() could cause collisions
  22588. Geometry.RandomId = function () {
  22589. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22590. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22591. return v.toString(16);
  22592. });
  22593. };
  22594. return Geometry;
  22595. })();
  22596. BABYLON.Geometry = Geometry;
  22597. (function (Geometry) {
  22598. /////// Primitives //////////////////////////////////////////////
  22599. (function (Primitives) {
  22600. /// Abstract class
  22601. var _Primitive = (function (_super) {
  22602. __extends(_Primitive, _super);
  22603. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22604. this._beingRegenerated = true;
  22605. this._canBeRegenerated = canBeRegenerated;
  22606. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22607. this._beingRegenerated = false;
  22608. }
  22609. _Primitive.prototype.canBeRegenerated = function () {
  22610. return this._canBeRegenerated;
  22611. };
  22612. _Primitive.prototype.regenerate = function () {
  22613. if (!this._canBeRegenerated) {
  22614. return;
  22615. }
  22616. this._beingRegenerated = true;
  22617. this.setAllVerticesData(this._regenerateVertexData(), false);
  22618. this._beingRegenerated = false;
  22619. };
  22620. _Primitive.prototype.asNewGeometry = function (id) {
  22621. return _super.prototype.copy.call(this, id);
  22622. };
  22623. // overrides
  22624. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22625. if (!this._beingRegenerated) {
  22626. return;
  22627. }
  22628. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22629. };
  22630. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22631. if (!this._beingRegenerated) {
  22632. return;
  22633. }
  22634. _super.prototype.setVerticesData.call(this, kind, data, false);
  22635. };
  22636. // to override
  22637. // protected
  22638. _Primitive.prototype._regenerateVertexData = function () {
  22639. throw new Error("Abstract method");
  22640. };
  22641. _Primitive.prototype.copy = function (id) {
  22642. throw new Error("Must be overriden in sub-classes.");
  22643. };
  22644. return _Primitive;
  22645. })(Geometry);
  22646. Primitives._Primitive = _Primitive;
  22647. var Box = (function (_super) {
  22648. __extends(Box, _super);
  22649. function Box(id, scene, size, canBeRegenerated, mesh) {
  22650. this.size = size;
  22651. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22652. }
  22653. Box.prototype._regenerateVertexData = function () {
  22654. return BABYLON.VertexData.CreateBox(this.size);
  22655. };
  22656. Box.prototype.copy = function (id) {
  22657. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22658. };
  22659. return Box;
  22660. })(_Primitive);
  22661. Primitives.Box = Box;
  22662. var Sphere = (function (_super) {
  22663. __extends(Sphere, _super);
  22664. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22665. this.segments = segments;
  22666. this.diameter = diameter;
  22667. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22668. }
  22669. Sphere.prototype._regenerateVertexData = function () {
  22670. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22671. };
  22672. Sphere.prototype.copy = function (id) {
  22673. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22674. };
  22675. return Sphere;
  22676. })(_Primitive);
  22677. Primitives.Sphere = Sphere;
  22678. var Cylinder = (function (_super) {
  22679. __extends(Cylinder, _super);
  22680. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22681. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22682. this.height = height;
  22683. this.diameterTop = diameterTop;
  22684. this.diameterBottom = diameterBottom;
  22685. this.tessellation = tessellation;
  22686. this.subdivisions = subdivisions;
  22687. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22688. }
  22689. Cylinder.prototype._regenerateVertexData = function () {
  22690. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22691. };
  22692. Cylinder.prototype.copy = function (id) {
  22693. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22694. };
  22695. return Cylinder;
  22696. })(_Primitive);
  22697. Primitives.Cylinder = Cylinder;
  22698. var Torus = (function (_super) {
  22699. __extends(Torus, _super);
  22700. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22701. this.diameter = diameter;
  22702. this.thickness = thickness;
  22703. this.tessellation = tessellation;
  22704. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22705. }
  22706. Torus.prototype._regenerateVertexData = function () {
  22707. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22708. };
  22709. Torus.prototype.copy = function (id) {
  22710. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22711. };
  22712. return Torus;
  22713. })(_Primitive);
  22714. Primitives.Torus = Torus;
  22715. var Ground = (function (_super) {
  22716. __extends(Ground, _super);
  22717. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22718. this.width = width;
  22719. this.height = height;
  22720. this.subdivisions = subdivisions;
  22721. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22722. }
  22723. Ground.prototype._regenerateVertexData = function () {
  22724. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22725. };
  22726. Ground.prototype.copy = function (id) {
  22727. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22728. };
  22729. return Ground;
  22730. })(_Primitive);
  22731. Primitives.Ground = Ground;
  22732. var TiledGround = (function (_super) {
  22733. __extends(TiledGround, _super);
  22734. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22735. this.xmin = xmin;
  22736. this.zmin = zmin;
  22737. this.xmax = xmax;
  22738. this.zmax = zmax;
  22739. this.subdivisions = subdivisions;
  22740. this.precision = precision;
  22741. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22742. }
  22743. TiledGround.prototype._regenerateVertexData = function () {
  22744. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22745. };
  22746. TiledGround.prototype.copy = function (id) {
  22747. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22748. };
  22749. return TiledGround;
  22750. })(_Primitive);
  22751. Primitives.TiledGround = TiledGround;
  22752. var Plane = (function (_super) {
  22753. __extends(Plane, _super);
  22754. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22755. this.size = size;
  22756. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22757. }
  22758. Plane.prototype._regenerateVertexData = function () {
  22759. return BABYLON.VertexData.CreatePlane(this.size);
  22760. };
  22761. Plane.prototype.copy = function (id) {
  22762. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22763. };
  22764. return Plane;
  22765. })(_Primitive);
  22766. Primitives.Plane = Plane;
  22767. var TorusKnot = (function (_super) {
  22768. __extends(TorusKnot, _super);
  22769. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22770. this.radius = radius;
  22771. this.tube = tube;
  22772. this.radialSegments = radialSegments;
  22773. this.tubularSegments = tubularSegments;
  22774. this.p = p;
  22775. this.q = q;
  22776. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22777. }
  22778. TorusKnot.prototype._regenerateVertexData = function () {
  22779. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22780. };
  22781. TorusKnot.prototype.copy = function (id) {
  22782. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22783. };
  22784. return TorusKnot;
  22785. })(_Primitive);
  22786. Primitives.TorusKnot = TorusKnot;
  22787. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22788. var Primitives = Geometry.Primitives;
  22789. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22790. var Geometry = BABYLON.Geometry;
  22791. })(BABYLON || (BABYLON = {}));
  22792. //# sourceMappingURL=babylon.geometry.js.map
  22793. var BABYLON;
  22794. (function (BABYLON) {
  22795. var Gamepads = (function () {
  22796. function Gamepads(ongamedpadconnected) {
  22797. var _this = this;
  22798. this.babylonGamepads = [];
  22799. this.oneGamepadConnected = false;
  22800. this.isMonitoring = false;
  22801. this.gamepadEventSupported = 'GamepadEvent' in window;
  22802. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22803. 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=";
  22804. this._callbackGamepadConnected = ongamedpadconnected;
  22805. if (this.gamepadSupportAvailable) {
  22806. // Checking if the gamepad connected event is supported (like in Firefox)
  22807. if (this.gamepadEventSupported) {
  22808. window.addEventListener('gamepadconnected', function (evt) {
  22809. _this._onGamepadConnected(evt);
  22810. }, false);
  22811. window.addEventListener('gamepaddisconnected', function (evt) {
  22812. _this._onGamepadDisconnected(evt);
  22813. }, false);
  22814. } else {
  22815. this._startMonitoringGamepads();
  22816. }
  22817. if (!this.oneGamepadConnected) {
  22818. this._insertGamepadDOMInstructions();
  22819. }
  22820. } else {
  22821. this._insertGamepadDOMNotSupported();
  22822. }
  22823. }
  22824. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22825. Gamepads.gamepadDOMInfo = document.createElement("div");
  22826. var buttonAImage = document.createElement("img");
  22827. buttonAImage.src = this.buttonADataURL;
  22828. var spanMessage = document.createElement("span");
  22829. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22830. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22831. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22832. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22833. Gamepads.gamepadDOMInfo.style.width = "100%";
  22834. Gamepads.gamepadDOMInfo.style.height = "48px";
  22835. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22836. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22837. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22838. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22839. buttonAImage.style.position = "relative";
  22840. buttonAImage.style.bottom = "8px";
  22841. spanMessage.style.position = "relative";
  22842. spanMessage.style.fontSize = "32px";
  22843. spanMessage.style.bottom = "32px";
  22844. spanMessage.style.color = "green";
  22845. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22846. };
  22847. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22848. Gamepads.gamepadDOMInfo = document.createElement("div");
  22849. var spanMessage = document.createElement("span");
  22850. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22851. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22852. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22853. Gamepads.gamepadDOMInfo.style.width = "100%";
  22854. Gamepads.gamepadDOMInfo.style.height = "40px";
  22855. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22856. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22857. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22858. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22859. spanMessage.style.position = "relative";
  22860. spanMessage.style.fontSize = "32px";
  22861. spanMessage.style.color = "red";
  22862. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22863. };
  22864. Gamepads.prototype.dispose = function () {
  22865. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22866. };
  22867. Gamepads.prototype._onGamepadConnected = function (evt) {
  22868. var newGamepad = this._addNewGamepad(evt.gamepad);
  22869. if (this._callbackGamepadConnected)
  22870. this._callbackGamepadConnected(newGamepad);
  22871. this._startMonitoringGamepads();
  22872. };
  22873. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22874. if (!this.oneGamepadConnected) {
  22875. this.oneGamepadConnected = true;
  22876. if (Gamepads.gamepadDOMInfo) {
  22877. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22878. Gamepads.gamepadDOMInfo = null;
  22879. }
  22880. }
  22881. var newGamepad;
  22882. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22883. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22884. } else {
  22885. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22886. }
  22887. this.babylonGamepads.push(newGamepad);
  22888. return newGamepad;
  22889. };
  22890. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22891. for (var i in this.babylonGamepads) {
  22892. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22893. this.babylonGamepads.splice(i, 1);
  22894. break;
  22895. }
  22896. }
  22897. // If no gamepads are left, stop the polling loop.
  22898. if (this.babylonGamepads.length == 0) {
  22899. this._stopMonitoringGamepads();
  22900. }
  22901. };
  22902. Gamepads.prototype._startMonitoringGamepads = function () {
  22903. if (!this.isMonitoring) {
  22904. this.isMonitoring = true;
  22905. this._checkGamepadsStatus();
  22906. }
  22907. };
  22908. Gamepads.prototype._stopMonitoringGamepads = function () {
  22909. this.isMonitoring = false;
  22910. };
  22911. Gamepads.prototype._checkGamepadsStatus = function () {
  22912. var _this = this;
  22913. // updating gamepad objects
  22914. this._updateGamepadObjects();
  22915. for (var i in this.babylonGamepads) {
  22916. this.babylonGamepads[i].update();
  22917. }
  22918. if (this.isMonitoring) {
  22919. if (window.requestAnimationFrame) {
  22920. window.requestAnimationFrame(function () {
  22921. _this._checkGamepadsStatus();
  22922. });
  22923. } else if (window.mozRequestAnimationFrame) {
  22924. window.mozRequestAnimationFrame(function () {
  22925. _this._checkGamepadsStatus();
  22926. });
  22927. } else if (window.webkitRequestAnimationFrame) {
  22928. window.webkitRequestAnimationFrame(function () {
  22929. _this._checkGamepadsStatus();
  22930. });
  22931. }
  22932. }
  22933. };
  22934. // This function is called only on Chrome, which does not yet support
  22935. // connection/disconnection events, but requires you to monitor
  22936. // an array for changes.
  22937. Gamepads.prototype._updateGamepadObjects = function () {
  22938. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22939. for (var i = 0; i < gamepads.length; i++) {
  22940. if (gamepads[i]) {
  22941. if (!(gamepads[i].index in this.babylonGamepads)) {
  22942. var newGamepad = this._addNewGamepad(gamepads[i]);
  22943. if (this._callbackGamepadConnected) {
  22944. this._callbackGamepadConnected(newGamepad);
  22945. }
  22946. } else {
  22947. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22948. }
  22949. }
  22950. }
  22951. };
  22952. return Gamepads;
  22953. })();
  22954. BABYLON.Gamepads = Gamepads;
  22955. var StickValues = (function () {
  22956. function StickValues(x, y) {
  22957. this.x = x;
  22958. this.y = y;
  22959. }
  22960. return StickValues;
  22961. })();
  22962. BABYLON.StickValues = StickValues;
  22963. var Gamepad = (function () {
  22964. function Gamepad(id, index, browserGamepad) {
  22965. this.id = id;
  22966. this.index = index;
  22967. this.browserGamepad = browserGamepad;
  22968. if (this.browserGamepad.axes.length >= 2) {
  22969. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22970. }
  22971. if (this.browserGamepad.axes.length >= 4) {
  22972. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22973. }
  22974. }
  22975. Gamepad.prototype.onleftstickchanged = function (callback) {
  22976. this._onleftstickchanged = callback;
  22977. };
  22978. Gamepad.prototype.onrightstickchanged = function (callback) {
  22979. this._onrightstickchanged = callback;
  22980. };
  22981. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22982. get: function () {
  22983. return this._leftStick;
  22984. },
  22985. set: function (newValues) {
  22986. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22987. this._onleftstickchanged(newValues);
  22988. }
  22989. this._leftStick = newValues;
  22990. },
  22991. enumerable: true,
  22992. configurable: true
  22993. });
  22994. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22995. get: function () {
  22996. return this._rightStick;
  22997. },
  22998. set: function (newValues) {
  22999. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23000. this._onrightstickchanged(newValues);
  23001. }
  23002. this._rightStick = newValues;
  23003. },
  23004. enumerable: true,
  23005. configurable: true
  23006. });
  23007. Gamepad.prototype.update = function () {
  23008. if (this._leftStick) {
  23009. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23010. }
  23011. if (this._rightStick) {
  23012. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23013. }
  23014. };
  23015. return Gamepad;
  23016. })();
  23017. BABYLON.Gamepad = Gamepad;
  23018. var GenericPad = (function (_super) {
  23019. __extends(GenericPad, _super);
  23020. function GenericPad(id, index, gamepad) {
  23021. _super.call(this, id, index, gamepad);
  23022. this.id = id;
  23023. this.index = index;
  23024. this.gamepad = gamepad;
  23025. this._buttons = new Array(gamepad.buttons.length);
  23026. }
  23027. GenericPad.prototype.onbuttondown = function (callback) {
  23028. this._onbuttondown = callback;
  23029. };
  23030. GenericPad.prototype.onbuttonup = function (callback) {
  23031. this._onbuttonup = callback;
  23032. };
  23033. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23034. if (newValue !== currentValue) {
  23035. if (this._onbuttondown && newValue === 1) {
  23036. this._onbuttondown(buttonIndex);
  23037. }
  23038. if (this._onbuttonup && newValue === 0) {
  23039. this._onbuttonup(buttonIndex);
  23040. }
  23041. }
  23042. return newValue;
  23043. };
  23044. GenericPad.prototype.update = function () {
  23045. _super.prototype.update.call(this);
  23046. for (var index = 0; index < this._buttons.length; index++) {
  23047. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23048. }
  23049. };
  23050. return GenericPad;
  23051. })(Gamepad);
  23052. BABYLON.GenericPad = GenericPad;
  23053. (function (Xbox360Button) {
  23054. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23055. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23056. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23057. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23058. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23059. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23060. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23061. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23062. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23063. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23064. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23065. var Xbox360Button = BABYLON.Xbox360Button;
  23066. (function (Xbox360Dpad) {
  23067. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23068. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23069. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23070. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23071. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23072. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23073. var Xbox360Pad = (function (_super) {
  23074. __extends(Xbox360Pad, _super);
  23075. function Xbox360Pad() {
  23076. _super.apply(this, arguments);
  23077. this._leftTrigger = 0;
  23078. this._rightTrigger = 0;
  23079. this._buttonA = 0;
  23080. this._buttonB = 0;
  23081. this._buttonX = 0;
  23082. this._buttonY = 0;
  23083. this._buttonBack = 0;
  23084. this._buttonStart = 0;
  23085. this._buttonLB = 0;
  23086. this._buttonRB = 0;
  23087. this._buttonLeftStick = 0;
  23088. this._buttonRightStick = 0;
  23089. this._dPadUp = 0;
  23090. this._dPadDown = 0;
  23091. this._dPadLeft = 0;
  23092. this._dPadRight = 0;
  23093. }
  23094. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23095. this._onlefttriggerchanged = callback;
  23096. };
  23097. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23098. this._onrighttriggerchanged = callback;
  23099. };
  23100. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23101. get: function () {
  23102. return this._leftTrigger;
  23103. },
  23104. set: function (newValue) {
  23105. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23106. this._onlefttriggerchanged(newValue);
  23107. }
  23108. this._leftTrigger = newValue;
  23109. },
  23110. enumerable: true,
  23111. configurable: true
  23112. });
  23113. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23114. get: function () {
  23115. return this._rightTrigger;
  23116. },
  23117. set: function (newValue) {
  23118. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23119. this._onrighttriggerchanged(newValue);
  23120. }
  23121. this._rightTrigger = newValue;
  23122. },
  23123. enumerable: true,
  23124. configurable: true
  23125. });
  23126. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23127. this._onbuttondown = callback;
  23128. };
  23129. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23130. this._onbuttonup = callback;
  23131. };
  23132. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23133. this._ondpaddown = callback;
  23134. };
  23135. Xbox360Pad.prototype.ondpadup = function (callback) {
  23136. this._ondpadup = callback;
  23137. };
  23138. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23139. if (newValue !== currentValue) {
  23140. if (this._onbuttondown && newValue === 1) {
  23141. this._onbuttondown(buttonType);
  23142. }
  23143. if (this._onbuttonup && newValue === 0) {
  23144. this._onbuttonup(buttonType);
  23145. }
  23146. }
  23147. return newValue;
  23148. };
  23149. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23150. if (newValue !== currentValue) {
  23151. if (this._ondpaddown && newValue === 1) {
  23152. this._ondpaddown(buttonType);
  23153. }
  23154. if (this._ondpadup && newValue === 0) {
  23155. this._ondpadup(buttonType);
  23156. }
  23157. }
  23158. return newValue;
  23159. };
  23160. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23161. get: function () {
  23162. return this._buttonA;
  23163. },
  23164. set: function (value) {
  23165. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23166. },
  23167. enumerable: true,
  23168. configurable: true
  23169. });
  23170. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23171. get: function () {
  23172. return this._buttonB;
  23173. },
  23174. set: function (value) {
  23175. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23176. },
  23177. enumerable: true,
  23178. configurable: true
  23179. });
  23180. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23181. get: function () {
  23182. return this._buttonX;
  23183. },
  23184. set: function (value) {
  23185. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23186. },
  23187. enumerable: true,
  23188. configurable: true
  23189. });
  23190. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23191. get: function () {
  23192. return this._buttonY;
  23193. },
  23194. set: function (value) {
  23195. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23196. },
  23197. enumerable: true,
  23198. configurable: true
  23199. });
  23200. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23201. get: function () {
  23202. return this._buttonStart;
  23203. },
  23204. set: function (value) {
  23205. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23206. },
  23207. enumerable: true,
  23208. configurable: true
  23209. });
  23210. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23211. get: function () {
  23212. return this._buttonBack;
  23213. },
  23214. set: function (value) {
  23215. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23216. },
  23217. enumerable: true,
  23218. configurable: true
  23219. });
  23220. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23221. get: function () {
  23222. return this._buttonLB;
  23223. },
  23224. set: function (value) {
  23225. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23226. },
  23227. enumerable: true,
  23228. configurable: true
  23229. });
  23230. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23231. get: function () {
  23232. return this._buttonRB;
  23233. },
  23234. set: function (value) {
  23235. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23241. get: function () {
  23242. return this._buttonLeftStick;
  23243. },
  23244. set: function (value) {
  23245. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23246. },
  23247. enumerable: true,
  23248. configurable: true
  23249. });
  23250. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23251. get: function () {
  23252. return this._buttonRightStick;
  23253. },
  23254. set: function (value) {
  23255. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23261. get: function () {
  23262. return this._dPadUp;
  23263. },
  23264. set: function (value) {
  23265. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23266. },
  23267. enumerable: true,
  23268. configurable: true
  23269. });
  23270. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23271. get: function () {
  23272. return this._dPadDown;
  23273. },
  23274. set: function (value) {
  23275. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23281. get: function () {
  23282. return this._dPadLeft;
  23283. },
  23284. set: function (value) {
  23285. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23291. get: function () {
  23292. return this._dPadRight;
  23293. },
  23294. set: function (value) {
  23295. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23296. },
  23297. enumerable: true,
  23298. configurable: true
  23299. });
  23300. Xbox360Pad.prototype.update = function () {
  23301. _super.prototype.update.call(this);
  23302. this.buttonA = this.browserGamepad.buttons[0].value;
  23303. this.buttonB = this.browserGamepad.buttons[1].value;
  23304. this.buttonX = this.browserGamepad.buttons[2].value;
  23305. this.buttonY = this.browserGamepad.buttons[3].value;
  23306. this.buttonLB = this.browserGamepad.buttons[4].value;
  23307. this.buttonRB = this.browserGamepad.buttons[5].value;
  23308. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23309. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23310. this.buttonBack = this.browserGamepad.buttons[8].value;
  23311. this.buttonStart = this.browserGamepad.buttons[9].value;
  23312. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23313. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23314. this.dPadUp = this.browserGamepad.buttons[12].value;
  23315. this.dPadDown = this.browserGamepad.buttons[13].value;
  23316. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23317. this.dPadRight = this.browserGamepad.buttons[15].value;
  23318. };
  23319. return Xbox360Pad;
  23320. })(Gamepad);
  23321. BABYLON.Xbox360Pad = Xbox360Pad;
  23322. })(BABYLON || (BABYLON = {}));
  23323. //# sourceMappingURL=babylon.gamepads.js.map
  23324. var BABYLON;
  23325. (function (BABYLON) {
  23326. // We're mainly based on the logic defined into the FreeCamera code
  23327. var GamepadCamera = (function (_super) {
  23328. __extends(GamepadCamera, _super);
  23329. function GamepadCamera(name, position, scene) {
  23330. var _this = this;
  23331. _super.call(this, name, position, scene);
  23332. this.angularSensibility = 200;
  23333. this.moveSensibility = 75;
  23334. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23335. _this._onNewGameConnected(gamepad);
  23336. });
  23337. }
  23338. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23339. // Only the first gamepad can control the camera
  23340. if (gamepad.index === 0) {
  23341. this._gamepad = gamepad;
  23342. }
  23343. };
  23344. GamepadCamera.prototype._checkInputs = function () {
  23345. if (!this._gamepad) {
  23346. return;
  23347. }
  23348. var LSValues = this._gamepad.leftStick;
  23349. var normalizedLX = LSValues.x / this.moveSensibility;
  23350. var normalizedLY = LSValues.y / this.moveSensibility;
  23351. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23352. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23353. var RSValues = this._gamepad.rightStick;
  23354. var normalizedRX = RSValues.x / this.angularSensibility;
  23355. var normalizedRY = RSValues.y / this.angularSensibility;
  23356. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23357. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23358. ;
  23359. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23360. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23361. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23362. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23363. };
  23364. GamepadCamera.prototype.dispose = function () {
  23365. this._gamepads.dispose();
  23366. _super.prototype.dispose.call(this);
  23367. };
  23368. return GamepadCamera;
  23369. })(BABYLON.FreeCamera);
  23370. BABYLON.GamepadCamera = GamepadCamera;
  23371. })(BABYLON || (BABYLON = {}));
  23372. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23373. var BABYLON;
  23374. (function (BABYLON) {
  23375. var LinesMesh = (function (_super) {
  23376. __extends(LinesMesh, _super);
  23377. function LinesMesh(name, scene, updatable) {
  23378. if (typeof updatable === "undefined") { updatable = false; }
  23379. _super.call(this, name, scene);
  23380. this.color = new BABYLON.Color3(1, 1, 1);
  23381. this.alpha = 1;
  23382. this._indices = new Array();
  23383. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23384. attributes: ["position"],
  23385. uniforms: ["worldViewProjection", "color"],
  23386. needAlphaBlending: true
  23387. });
  23388. }
  23389. Object.defineProperty(LinesMesh.prototype, "material", {
  23390. get: function () {
  23391. return this._colorShader;
  23392. },
  23393. enumerable: true,
  23394. configurable: true
  23395. });
  23396. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23397. get: function () {
  23398. return false;
  23399. },
  23400. enumerable: true,
  23401. configurable: true
  23402. });
  23403. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23404. get: function () {
  23405. return false;
  23406. },
  23407. enumerable: true,
  23408. configurable: true
  23409. });
  23410. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23411. var engine = this.getScene().getEngine();
  23412. var indexToBind = this._geometry.getIndexBuffer();
  23413. // VBOs
  23414. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23415. // Color
  23416. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23417. };
  23418. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23419. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23420. return;
  23421. }
  23422. var engine = this.getScene().getEngine();
  23423. // Draw order
  23424. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23425. };
  23426. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23427. return null;
  23428. };
  23429. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23430. this._colorShader.dispose();
  23431. _super.prototype.dispose.call(this, doNotRecurse);
  23432. };
  23433. return LinesMesh;
  23434. })(BABYLON.Mesh);
  23435. BABYLON.LinesMesh = LinesMesh;
  23436. })(BABYLON || (BABYLON = {}));
  23437. //# sourceMappingURL=babylon.linesMesh.js.map
  23438. var BABYLON;
  23439. (function (BABYLON) {
  23440. var OutlineRenderer = (function () {
  23441. function OutlineRenderer(scene) {
  23442. this._scene = scene;
  23443. }
  23444. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23445. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23446. var scene = this._scene;
  23447. var engine = this._scene.getEngine();
  23448. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23449. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23450. return;
  23451. }
  23452. var mesh = subMesh.getRenderingMesh();
  23453. var material = subMesh.getMaterial();
  23454. engine.enableEffect(this._effect);
  23455. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23456. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23457. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23458. // Bones
  23459. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23460. if (useBones) {
  23461. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23462. }
  23463. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23464. // Alpha test
  23465. if (material && material.needAlphaTesting()) {
  23466. var alphaTexture = material.getAlphaTestTexture();
  23467. this._effect.setTexture("diffuseSampler", alphaTexture);
  23468. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23469. }
  23470. if (hardwareInstancedRendering) {
  23471. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23472. } else {
  23473. if (batch.renderSelf[subMesh._id]) {
  23474. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23475. // Draw
  23476. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23477. }
  23478. if (batch.visibleInstances[subMesh._id]) {
  23479. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23480. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23481. this._effect.setMatrix("world", instance.getWorldMatrix());
  23482. // Draw
  23483. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23484. }
  23485. }
  23486. }
  23487. };
  23488. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23489. var defines = [];
  23490. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23491. var mesh = subMesh.getMesh();
  23492. var material = subMesh.getMaterial();
  23493. // Alpha test
  23494. if (material && material.needAlphaTesting()) {
  23495. defines.push("#define ALPHATEST");
  23496. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23497. attribs.push(BABYLON.VertexBuffer.UVKind);
  23498. defines.push("#define UV1");
  23499. }
  23500. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23501. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23502. defines.push("#define UV2");
  23503. }
  23504. }
  23505. // Bones
  23506. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23509. defines.push("#define BONES");
  23510. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23511. }
  23512. // Instances
  23513. if (useInstances) {
  23514. defines.push("#define INSTANCES");
  23515. attribs.push("world0");
  23516. attribs.push("world1");
  23517. attribs.push("world2");
  23518. attribs.push("world3");
  23519. }
  23520. // Get correct effect
  23521. var join = defines.join("\n");
  23522. if (this._cachedDefines != join) {
  23523. this._cachedDefines = join;
  23524. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23525. }
  23526. return this._effect.isReady();
  23527. };
  23528. return OutlineRenderer;
  23529. })();
  23530. BABYLON.OutlineRenderer = OutlineRenderer;
  23531. })(BABYLON || (BABYLON = {}));
  23532. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23533. var BABYLON;
  23534. (function (BABYLON) {
  23535. var MeshAssetTask = (function () {
  23536. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23537. this.name = name;
  23538. this.meshesNames = meshesNames;
  23539. this.rootUrl = rootUrl;
  23540. this.sceneFilename = sceneFilename;
  23541. this.isCompleted = false;
  23542. }
  23543. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23544. var _this = this;
  23545. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23546. _this.loadedMeshes = meshes;
  23547. _this.loadedParticleSystems = particleSystems;
  23548. _this.loadedSkeletons = skeletons;
  23549. _this.isCompleted = true;
  23550. if (_this.onSuccess) {
  23551. _this.onSuccess(_this);
  23552. }
  23553. onSuccess();
  23554. }, null, function () {
  23555. if (_this.onError) {
  23556. _this.onError(_this);
  23557. }
  23558. onError();
  23559. });
  23560. };
  23561. return MeshAssetTask;
  23562. })();
  23563. BABYLON.MeshAssetTask = MeshAssetTask;
  23564. var TextFileAssetTask = (function () {
  23565. function TextFileAssetTask(name, url) {
  23566. this.name = name;
  23567. this.url = url;
  23568. this.isCompleted = false;
  23569. }
  23570. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23571. var _this = this;
  23572. BABYLON.Tools.LoadFile(this.url, function (data) {
  23573. _this.text = data;
  23574. _this.isCompleted = true;
  23575. if (_this.onSuccess) {
  23576. _this.onSuccess(_this);
  23577. }
  23578. onSuccess();
  23579. }, null, scene.database, false, function () {
  23580. if (_this.onError) {
  23581. _this.onError(_this);
  23582. }
  23583. onError();
  23584. });
  23585. };
  23586. return TextFileAssetTask;
  23587. })();
  23588. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23589. var BinaryFileAssetTask = (function () {
  23590. function BinaryFileAssetTask(name, url) {
  23591. this.name = name;
  23592. this.url = url;
  23593. this.isCompleted = false;
  23594. }
  23595. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23596. var _this = this;
  23597. BABYLON.Tools.LoadFile(this.url, function (data) {
  23598. _this.data = data;
  23599. _this.isCompleted = true;
  23600. if (_this.onSuccess) {
  23601. _this.onSuccess(_this);
  23602. }
  23603. onSuccess();
  23604. }, null, scene.database, true, function () {
  23605. if (_this.onError) {
  23606. _this.onError(_this);
  23607. }
  23608. onError();
  23609. });
  23610. };
  23611. return BinaryFileAssetTask;
  23612. })();
  23613. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23614. var ImageAssetTask = (function () {
  23615. function ImageAssetTask(name, url) {
  23616. this.name = name;
  23617. this.url = url;
  23618. this.isCompleted = false;
  23619. }
  23620. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23621. var _this = this;
  23622. var img = new Image();
  23623. img.onload = function () {
  23624. _this.image = img;
  23625. _this.isCompleted = true;
  23626. if (_this.onSuccess) {
  23627. _this.onSuccess(_this);
  23628. }
  23629. onSuccess();
  23630. };
  23631. img.onerror = function () {
  23632. if (_this.onError) {
  23633. _this.onError(_this);
  23634. }
  23635. onError();
  23636. };
  23637. img.src = this.url;
  23638. };
  23639. return ImageAssetTask;
  23640. })();
  23641. BABYLON.ImageAssetTask = ImageAssetTask;
  23642. var TextureAssetTask = (function () {
  23643. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23644. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23645. this.name = name;
  23646. this.url = url;
  23647. this.noMipmap = noMipmap;
  23648. this.invertY = invertY;
  23649. this.samplingMode = samplingMode;
  23650. this.isCompleted = false;
  23651. }
  23652. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23653. var _this = this;
  23654. var onload = function () {
  23655. _this.isCompleted = true;
  23656. if (_this.onSuccess) {
  23657. _this.onSuccess(_this);
  23658. }
  23659. onSuccess();
  23660. };
  23661. var onerror = function () {
  23662. if (_this.onError) {
  23663. _this.onError(_this);
  23664. }
  23665. onError();
  23666. };
  23667. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23668. };
  23669. return TextureAssetTask;
  23670. })();
  23671. BABYLON.TextureAssetTask = TextureAssetTask;
  23672. var AssetsManager = (function () {
  23673. function AssetsManager(scene) {
  23674. this._tasks = new Array();
  23675. this._waitingTasksCount = 0;
  23676. this.useDefaultLoadingScreen = true;
  23677. this._scene = scene;
  23678. }
  23679. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23680. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23681. this._tasks.push(task);
  23682. return task;
  23683. };
  23684. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23685. var task = new TextFileAssetTask(taskName, url);
  23686. this._tasks.push(task);
  23687. return task;
  23688. };
  23689. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23690. var task = new BinaryFileAssetTask(taskName, url);
  23691. this._tasks.push(task);
  23692. return task;
  23693. };
  23694. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23695. var task = new ImageAssetTask(taskName, url);
  23696. this._tasks.push(task);
  23697. return task;
  23698. };
  23699. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23700. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23701. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23702. this._tasks.push(task);
  23703. return task;
  23704. };
  23705. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23706. this._waitingTasksCount--;
  23707. if (this._waitingTasksCount === 0) {
  23708. if (this.onFinish) {
  23709. this.onFinish(this._tasks);
  23710. }
  23711. this._scene.getEngine().hideLoadingUI();
  23712. }
  23713. };
  23714. AssetsManager.prototype._runTask = function (task) {
  23715. var _this = this;
  23716. task.run(this._scene, function () {
  23717. if (_this.onTaskSuccess) {
  23718. _this.onTaskSuccess(task);
  23719. }
  23720. _this._decreaseWaitingTasksCount();
  23721. }, function () {
  23722. if (_this.onTaskError) {
  23723. _this.onTaskError(task);
  23724. }
  23725. _this._decreaseWaitingTasksCount();
  23726. });
  23727. };
  23728. AssetsManager.prototype.reset = function () {
  23729. this._tasks = new Array();
  23730. return this;
  23731. };
  23732. AssetsManager.prototype.load = function () {
  23733. this._waitingTasksCount = this._tasks.length;
  23734. if (this._waitingTasksCount === 0) {
  23735. if (this.onFinish) {
  23736. this.onFinish(this._tasks);
  23737. }
  23738. return this;
  23739. }
  23740. if (this.useDefaultLoadingScreen) {
  23741. this._scene.getEngine().displayLoadingUI();
  23742. }
  23743. for (var index = 0; index < this._tasks.length; index++) {
  23744. var task = this._tasks[index];
  23745. this._runTask(task);
  23746. }
  23747. return this;
  23748. };
  23749. return AssetsManager;
  23750. })();
  23751. BABYLON.AssetsManager = AssetsManager;
  23752. })(BABYLON || (BABYLON = {}));
  23753. //# sourceMappingURL=babylon.assetsManager.js.map
  23754. var BABYLON;
  23755. (function (BABYLON) {
  23756. var VRDeviceOrientationCamera = (function (_super) {
  23757. __extends(VRDeviceOrientationCamera, _super);
  23758. function VRDeviceOrientationCamera(name, position, scene) {
  23759. _super.call(this, name, position, scene);
  23760. this._alpha = 0;
  23761. this._beta = 0;
  23762. this._gamma = 0;
  23763. }
  23764. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23765. this._alpha = +evt.alpha | 0;
  23766. this._beta = +evt.beta | 0;
  23767. this._gamma = +evt.gamma | 0;
  23768. if (this._gamma < 0) {
  23769. this._gamma = 90 + this._gamma;
  23770. } else {
  23771. // Incline it in the correct angle.
  23772. this._gamma = 270 - this._gamma;
  23773. }
  23774. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23775. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23776. this.rotation.z = this._beta / 180.0 * Math.PI;
  23777. };
  23778. return VRDeviceOrientationCamera;
  23779. })(BABYLON.OculusCamera);
  23780. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23781. })(BABYLON || (BABYLON = {}));
  23782. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23783. var BABYLON;
  23784. (function (BABYLON) {
  23785. var WebVRCamera = (function (_super) {
  23786. __extends(WebVRCamera, _super);
  23787. function WebVRCamera(name, position, scene) {
  23788. _super.call(this, name, position, scene);
  23789. this._hmdDevice = null;
  23790. this._sensorDevice = null;
  23791. this._cacheState = null;
  23792. this._cacheQuaternion = new BABYLON.Quaternion();
  23793. this._cacheRotation = BABYLON.Vector3.Zero();
  23794. this._vrEnabled = false;
  23795. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23796. }
  23797. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23798. var size = devices.length;
  23799. var i = 0;
  23800. // Reset devices.
  23801. this._sensorDevice = null;
  23802. this._hmdDevice = null;
  23803. while (i < size && this._hmdDevice === null) {
  23804. if (devices[i] instanceof HMDVRDevice) {
  23805. this._hmdDevice = devices[i];
  23806. }
  23807. i++;
  23808. }
  23809. i = 0;
  23810. while (i < size && this._sensorDevice === null) {
  23811. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23812. this._sensorDevice = devices[i];
  23813. }
  23814. i++;
  23815. }
  23816. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23817. };
  23818. WebVRCamera.prototype._update = function () {
  23819. if (this._vrEnabled) {
  23820. this._cacheState = this._sensorDevice.getState();
  23821. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23822. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23823. this.rotation.x = -this._cacheRotation.z;
  23824. this.rotation.y = -this._cacheRotation.y;
  23825. this.rotation.z = this._cacheRotation.x;
  23826. }
  23827. _super.prototype._update.call(this);
  23828. };
  23829. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23830. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23831. if (navigator.getVRDevices) {
  23832. navigator.getVRDevices().then(this._getWebVRDevices);
  23833. } else if (navigator.mozGetVRDevices) {
  23834. navigator.mozGetVRDevices(this._getWebVRDevices);
  23835. }
  23836. };
  23837. WebVRCamera.prototype.detachControl = function (element) {
  23838. _super.prototype.detachControl.call(this, element);
  23839. this._vrEnabled = false;
  23840. };
  23841. return WebVRCamera;
  23842. })(BABYLON.OculusCamera);
  23843. BABYLON.WebVRCamera = WebVRCamera;
  23844. })(BABYLON || (BABYLON = {}));
  23845. //# sourceMappingURL=babylon.webVRCamera.js.map
  23846. var BABYLON;
  23847. (function (BABYLON) {
  23848. // Standard optimizations
  23849. var SceneOptimization = (function () {
  23850. function SceneOptimization(priority) {
  23851. if (typeof priority === "undefined") { priority = 0; }
  23852. this.priority = priority;
  23853. this.apply = function (scene) {
  23854. return true;
  23855. };
  23856. }
  23857. return SceneOptimization;
  23858. })();
  23859. BABYLON.SceneOptimization = SceneOptimization;
  23860. var TextureOptimization = (function (_super) {
  23861. __extends(TextureOptimization, _super);
  23862. function TextureOptimization(priority, maximumSize) {
  23863. if (typeof priority === "undefined") { priority = 0; }
  23864. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23865. var _this = this;
  23866. _super.call(this, priority);
  23867. this.priority = priority;
  23868. this.maximumSize = maximumSize;
  23869. this.apply = function (scene) {
  23870. var allDone = true;
  23871. for (var index = 0; index < scene.textures.length; index++) {
  23872. var texture = scene.textures[index];
  23873. if (!texture.canRescale) {
  23874. continue;
  23875. }
  23876. var currentSize = texture.getSize();
  23877. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23878. if (maxDimension > _this.maximumSize) {
  23879. texture.scale(0.5);
  23880. allDone = false;
  23881. }
  23882. }
  23883. return allDone;
  23884. };
  23885. }
  23886. return TextureOptimization;
  23887. })(SceneOptimization);
  23888. BABYLON.TextureOptimization = TextureOptimization;
  23889. var HardwareScalingOptimization = (function (_super) {
  23890. __extends(HardwareScalingOptimization, _super);
  23891. function HardwareScalingOptimization(priority, maximumScale) {
  23892. if (typeof priority === "undefined") { priority = 0; }
  23893. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23894. var _this = this;
  23895. _super.call(this, priority);
  23896. this.priority = priority;
  23897. this.maximumScale = maximumScale;
  23898. this._currentScale = 1;
  23899. this.apply = function (scene) {
  23900. _this._currentScale++;
  23901. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23902. return _this._currentScale >= _this.maximumScale;
  23903. };
  23904. }
  23905. return HardwareScalingOptimization;
  23906. })(SceneOptimization);
  23907. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23908. var ShadowsOptimization = (function (_super) {
  23909. __extends(ShadowsOptimization, _super);
  23910. function ShadowsOptimization() {
  23911. _super.apply(this, arguments);
  23912. this.apply = function (scene) {
  23913. scene.shadowsEnabled = false;
  23914. return true;
  23915. };
  23916. }
  23917. return ShadowsOptimization;
  23918. })(SceneOptimization);
  23919. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23920. var PostProcessesOptimization = (function (_super) {
  23921. __extends(PostProcessesOptimization, _super);
  23922. function PostProcessesOptimization() {
  23923. _super.apply(this, arguments);
  23924. this.apply = function (scene) {
  23925. scene.postProcessesEnabled = false;
  23926. return true;
  23927. };
  23928. }
  23929. return PostProcessesOptimization;
  23930. })(SceneOptimization);
  23931. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23932. var LensFlaresOptimization = (function (_super) {
  23933. __extends(LensFlaresOptimization, _super);
  23934. function LensFlaresOptimization() {
  23935. _super.apply(this, arguments);
  23936. this.apply = function (scene) {
  23937. scene.lensFlaresEnabled = false;
  23938. return true;
  23939. };
  23940. }
  23941. return LensFlaresOptimization;
  23942. })(SceneOptimization);
  23943. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23944. var ParticlesOptimization = (function (_super) {
  23945. __extends(ParticlesOptimization, _super);
  23946. function ParticlesOptimization() {
  23947. _super.apply(this, arguments);
  23948. this.apply = function (scene) {
  23949. scene.particlesEnabled = false;
  23950. return true;
  23951. };
  23952. }
  23953. return ParticlesOptimization;
  23954. })(SceneOptimization);
  23955. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23956. var RenderTargetsOptimization = (function (_super) {
  23957. __extends(RenderTargetsOptimization, _super);
  23958. function RenderTargetsOptimization() {
  23959. _super.apply(this, arguments);
  23960. this.apply = function (scene) {
  23961. scene.renderTargetsEnabled = false;
  23962. return true;
  23963. };
  23964. }
  23965. return RenderTargetsOptimization;
  23966. })(SceneOptimization);
  23967. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23968. var MergeMeshesOptimization = (function (_super) {
  23969. __extends(MergeMeshesOptimization, _super);
  23970. function MergeMeshesOptimization() {
  23971. _super.apply(this, arguments);
  23972. var _this = this;
  23973. this._canBeMerged = function (abstractMesh) {
  23974. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23975. return false;
  23976. }
  23977. var mesh = abstractMesh;
  23978. if (!mesh.isVisible || !mesh.isEnabled()) {
  23979. return false;
  23980. }
  23981. if (mesh.instances.length > 0) {
  23982. return false;
  23983. }
  23984. if (mesh.skeleton || mesh.hasLODLevels) {
  23985. return false;
  23986. }
  23987. return true;
  23988. };
  23989. this.apply = function (scene) {
  23990. var globalPool = scene.meshes.slice(0);
  23991. var globalLength = globalPool.length;
  23992. for (var index = 0; index < globalLength; index++) {
  23993. var currentPool = new Array();
  23994. var current = globalPool[index];
  23995. // Checks
  23996. if (!_this._canBeMerged(current)) {
  23997. continue;
  23998. }
  23999. currentPool.push(current);
  24000. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24001. var otherMesh = globalPool[subIndex];
  24002. if (!_this._canBeMerged(otherMesh)) {
  24003. continue;
  24004. }
  24005. if (otherMesh.material !== current.material) {
  24006. continue;
  24007. }
  24008. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24009. continue;
  24010. }
  24011. currentPool.push(otherMesh);
  24012. globalLength--;
  24013. globalPool.splice(subIndex, 1);
  24014. subIndex--;
  24015. }
  24016. if (currentPool.length < 2) {
  24017. continue;
  24018. }
  24019. // Merge meshes
  24020. BABYLON.Mesh.MergeMeshes(currentPool);
  24021. }
  24022. return true;
  24023. };
  24024. }
  24025. return MergeMeshesOptimization;
  24026. })(SceneOptimization);
  24027. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24028. // Options
  24029. var SceneOptimizerOptions = (function () {
  24030. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24031. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24032. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24033. this.targetFrameRate = targetFrameRate;
  24034. this.trackerDuration = trackerDuration;
  24035. this.optimizations = new Array();
  24036. }
  24037. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24038. var result = new SceneOptimizerOptions(targetFrameRate);
  24039. var priority = 0;
  24040. result.optimizations.push(new MergeMeshesOptimization(priority));
  24041. result.optimizations.push(new ShadowsOptimization(priority));
  24042. result.optimizations.push(new LensFlaresOptimization(priority));
  24043. // Next priority
  24044. priority++;
  24045. result.optimizations.push(new PostProcessesOptimization(priority));
  24046. result.optimizations.push(new ParticlesOptimization(priority));
  24047. // Next priority
  24048. priority++;
  24049. result.optimizations.push(new TextureOptimization(priority, 1024));
  24050. return result;
  24051. };
  24052. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24053. var result = new SceneOptimizerOptions(targetFrameRate);
  24054. var priority = 0;
  24055. result.optimizations.push(new MergeMeshesOptimization(priority));
  24056. result.optimizations.push(new ShadowsOptimization(priority));
  24057. result.optimizations.push(new LensFlaresOptimization(priority));
  24058. // Next priority
  24059. priority++;
  24060. result.optimizations.push(new PostProcessesOptimization(priority));
  24061. result.optimizations.push(new ParticlesOptimization(priority));
  24062. // Next priority
  24063. priority++;
  24064. result.optimizations.push(new TextureOptimization(priority, 512));
  24065. // Next priority
  24066. priority++;
  24067. result.optimizations.push(new RenderTargetsOptimization(priority));
  24068. // Next priority
  24069. priority++;
  24070. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24071. return result;
  24072. };
  24073. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24074. var result = new SceneOptimizerOptions(targetFrameRate);
  24075. var priority = 0;
  24076. result.optimizations.push(new MergeMeshesOptimization(priority));
  24077. result.optimizations.push(new ShadowsOptimization(priority));
  24078. result.optimizations.push(new LensFlaresOptimization(priority));
  24079. // Next priority
  24080. priority++;
  24081. result.optimizations.push(new PostProcessesOptimization(priority));
  24082. result.optimizations.push(new ParticlesOptimization(priority));
  24083. // Next priority
  24084. priority++;
  24085. result.optimizations.push(new TextureOptimization(priority, 256));
  24086. // Next priority
  24087. priority++;
  24088. result.optimizations.push(new RenderTargetsOptimization(priority));
  24089. // Next priority
  24090. priority++;
  24091. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24092. return result;
  24093. };
  24094. return SceneOptimizerOptions;
  24095. })();
  24096. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24097. // Scene optimizer tool
  24098. var SceneOptimizer = (function () {
  24099. function SceneOptimizer() {
  24100. }
  24101. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24102. // TODO: add an epsilon
  24103. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24104. if (onSuccess) {
  24105. onSuccess();
  24106. }
  24107. return;
  24108. }
  24109. // Apply current level of optimizations
  24110. var allDone = true;
  24111. var noOptimizationApplied = true;
  24112. for (var index = 0; index < options.optimizations.length; index++) {
  24113. var optimization = options.optimizations[index];
  24114. if (optimization.priority === currentPriorityLevel) {
  24115. noOptimizationApplied = false;
  24116. allDone = allDone && optimization.apply(scene);
  24117. }
  24118. }
  24119. // If no optimization was applied, this is a failure :(
  24120. if (noOptimizationApplied) {
  24121. if (onFailure) {
  24122. onFailure();
  24123. }
  24124. return;
  24125. }
  24126. // If all optimizations were done, move to next level
  24127. if (allDone) {
  24128. currentPriorityLevel++;
  24129. }
  24130. // Let's the system running for a specific amount of time before checking FPS
  24131. scene.executeWhenReady(function () {
  24132. setTimeout(function () {
  24133. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24134. }, options.trackerDuration);
  24135. });
  24136. };
  24137. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24138. if (!options) {
  24139. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24140. }
  24141. // Let's the system running for a specific amount of time before checking FPS
  24142. scene.executeWhenReady(function () {
  24143. setTimeout(function () {
  24144. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24145. }, options.trackerDuration);
  24146. });
  24147. };
  24148. return SceneOptimizer;
  24149. })();
  24150. BABYLON.SceneOptimizer = SceneOptimizer;
  24151. })(BABYLON || (BABYLON = {}));
  24152. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24153. var BABYLON;
  24154. (function (BABYLON) {
  24155. (function (Internals) {
  24156. var MeshLODLevel = (function () {
  24157. function MeshLODLevel(distance, mesh) {
  24158. this.distance = distance;
  24159. this.mesh = mesh;
  24160. }
  24161. return MeshLODLevel;
  24162. })();
  24163. Internals.MeshLODLevel = MeshLODLevel;
  24164. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24165. var Internals = BABYLON.Internals;
  24166. })(BABYLON || (BABYLON = {}));
  24167. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24168. var BABYLON;
  24169. (function (BABYLON) {
  24170. var AudioEngine = (function () {
  24171. function AudioEngine() {
  24172. this.audioContext = null;
  24173. this.canUseWebAudio = false;
  24174. try {
  24175. if (typeof AudioContext !== 'undefined') {
  24176. this.audioContext = new AudioContext();
  24177. this.canUseWebAudio = true;
  24178. } else if (typeof webkitAudioContext !== 'undefined') {
  24179. this.audioContext = new webkitAudioContext();
  24180. this.canUseWebAudio = true;
  24181. }
  24182. } catch (e) {
  24183. this.canUseWebAudio = false;
  24184. }
  24185. // create a global volume gain node
  24186. if (this.canUseWebAudio) {
  24187. this.masterGain = this.audioContext.createGain();
  24188. this.masterGain.gain.value = 1;
  24189. this.masterGain.connect(this.audioContext.destination);
  24190. }
  24191. }
  24192. AudioEngine.prototype.getGlobalVolume = function () {
  24193. if (this.canUseWebAudio) {
  24194. return this.masterGain.gain.value;
  24195. } else {
  24196. return -1;
  24197. }
  24198. };
  24199. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24200. if (this.canUseWebAudio) {
  24201. this.masterGain.gain.value = newVolume;
  24202. }
  24203. };
  24204. return AudioEngine;
  24205. })();
  24206. BABYLON.AudioEngine = AudioEngine;
  24207. })(BABYLON || (BABYLON = {}));
  24208. //# sourceMappingURL=babylon.audioengine.js.map
  24209. var BABYLON;
  24210. (function (BABYLON) {
  24211. var Sound = (function () {
  24212. /**
  24213. * Create a sound and attach it to a scene
  24214. * @param name Name of your sound
  24215. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24216. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24217. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24218. */
  24219. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24220. var _this = this;
  24221. this.autoplay = false;
  24222. this.loop = false;
  24223. this.useCustomAttenuation = false;
  24224. this.spatialSound = false;
  24225. this.refDistance = 1;
  24226. this.rolloffFactor = 1;
  24227. this.maxDistance = 100;
  24228. this.distanceModel = "linear";
  24229. this.panningModel = "HRTF";
  24230. this.startTime = 0;
  24231. this.startOffset = 0;
  24232. this._position = BABYLON.Vector3.Zero();
  24233. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24234. this._volume = 1;
  24235. this._isLoaded = false;
  24236. this._isReadyToPlay = false;
  24237. this._isPlaying = false;
  24238. this._isDirectional = false;
  24239. // Used if you'd like to create a directional sound.
  24240. // If not set, the sound will be omnidirectional
  24241. this._coneInnerAngle = 360;
  24242. this._coneOuterAngle = 360;
  24243. this._coneOuterGain = 0;
  24244. this._name = name;
  24245. this._scene = scene;
  24246. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24247. this._readyToPlayCallback = readyToPlayCallback;
  24248. // Default custom attenuation function is a linear attenuation
  24249. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24250. if (currentDistance < maxDistance) {
  24251. return currentVolume * (1 - currentDistance / maxDistance);
  24252. } else {
  24253. return 0;
  24254. }
  24255. };
  24256. if (options) {
  24257. this.autoplay = options.autoplay || false;
  24258. this.loop = options.loop || false;
  24259. this._volume = options.volume || 1;
  24260. this.spatialSound = options.spatialSound || false;
  24261. this.maxDistance = options.maxDistance || 100;
  24262. this.useCustomAttenuation = options.useCustomAttenation || false;
  24263. this.rolloffFactor = options.rolloffFactor || 1;
  24264. this.refDistance = options.refDistance || 1;
  24265. this.distanceModel = options.distanceModel || "linear";
  24266. this.panningModel = options.panningModel || "HRTF";
  24267. }
  24268. if (this._audioEngine.canUseWebAudio) {
  24269. this._soundGain = this._audioEngine.audioContext.createGain();
  24270. this._soundGain.gain.value = this._volume;
  24271. if (this.spatialSound) {
  24272. this._createSpatialParameters();
  24273. } else {
  24274. this._audioNode = this._soundGain;
  24275. }
  24276. this._scene.mainSoundTrack.AddSound(this);
  24277. if (typeof (urlOrArrayBuffer) === "string") {
  24278. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24279. _this._soundLoaded(data);
  24280. }, null, null, true);
  24281. } else {
  24282. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24283. this._soundLoaded(urlOrArrayBuffer);
  24284. } else {
  24285. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24286. }
  24287. }
  24288. }
  24289. }
  24290. Sound.prototype.updateOptions = function (options) {
  24291. if (options) {
  24292. this.loop = options.loop || this.loop;
  24293. this.maxDistance = options.maxDistance || this.maxDistance;
  24294. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24295. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24296. this.refDistance = options.refDistance || this.refDistance;
  24297. this.distanceModel = options.distanceModel || this.distanceModel;
  24298. this.panningModel = options.panningModel || this.panningModel;
  24299. }
  24300. };
  24301. Sound.prototype._createSpatialParameters = function () {
  24302. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24303. if (this.useCustomAttenuation) {
  24304. // Tricks to disable in a way embedded Web Audio attenuation
  24305. this._soundPanner.distanceModel = "linear";
  24306. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24307. this._soundPanner.refDistance = 1;
  24308. this._soundPanner.rolloffFactor = 1;
  24309. this._soundPanner.panningModel = "HRTF";
  24310. } else {
  24311. this._soundPanner.distanceModel = this.distanceModel;
  24312. this._soundPanner.maxDistance = this.maxDistance;
  24313. this._soundPanner.refDistance = this.refDistance;
  24314. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24315. this._soundPanner.panningModel = this.panningModel;
  24316. }
  24317. this._soundPanner.connect(this._soundGain);
  24318. this._audioNode = this._soundPanner;
  24319. };
  24320. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24321. if (this._audioEngine.canUseWebAudio) {
  24322. this._audioNode.disconnect();
  24323. this._audioNode.connect(soundTrackAudioNode);
  24324. }
  24325. };
  24326. /**
  24327. * Transform this sound into a directional source
  24328. * @param coneInnerAngle Size of the inner cone in degree
  24329. * @param coneOuterAngle Size of the outer cone in degree
  24330. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24331. */
  24332. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24333. if (coneOuterAngle < coneInnerAngle) {
  24334. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24335. return;
  24336. }
  24337. this._coneInnerAngle = coneInnerAngle;
  24338. this._coneOuterAngle = coneOuterAngle;
  24339. this._coneOuterGain = coneOuterGain;
  24340. this._isDirectional = true;
  24341. if (this._isPlaying && this.loop) {
  24342. this.stop();
  24343. this.play();
  24344. }
  24345. };
  24346. Sound.prototype.setPosition = function (newPosition) {
  24347. this._position = newPosition;
  24348. if (this._isPlaying && this.spatialSound) {
  24349. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24350. }
  24351. };
  24352. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24353. this._localDirection = newLocalDirection;
  24354. if (this._connectedMesh && this._isPlaying) {
  24355. this._updateDirection();
  24356. }
  24357. };
  24358. Sound.prototype._updateDirection = function () {
  24359. var mat = this._connectedMesh.getWorldMatrix();
  24360. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24361. direction.normalize();
  24362. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24363. };
  24364. Sound.prototype.updateDistanceFromListener = function () {
  24365. if (this._connectedMesh && this.useCustomAttenuation) {
  24366. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24367. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24368. }
  24369. };
  24370. Sound.prototype.setAttenuationFunction = function (callback) {
  24371. this._customAttenuationFunction = callback;
  24372. };
  24373. /**
  24374. * Play the sound
  24375. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24376. */
  24377. Sound.prototype.play = function (time) {
  24378. if (this._isReadyToPlay) {
  24379. try {
  24380. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24381. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24382. this._soundSource.buffer = this._audioBuffer;
  24383. if (this.spatialSound) {
  24384. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24385. if (this._isDirectional) {
  24386. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24387. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24388. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24389. if (this._connectedMesh) {
  24390. this._updateDirection();
  24391. } else {
  24392. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24393. }
  24394. }
  24395. }
  24396. this._soundSource.connect(this._audioNode);
  24397. this._soundSource.loop = this.loop;
  24398. this.startTime = startTime;
  24399. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24400. this._isPlaying = true;
  24401. } catch (ex) {
  24402. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24403. }
  24404. }
  24405. };
  24406. /**
  24407. * Stop the sound
  24408. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24409. */
  24410. Sound.prototype.stop = function (time) {
  24411. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24412. this._soundSource.stop(stopTime);
  24413. this._isPlaying = false;
  24414. };
  24415. Sound.prototype.pause = function () {
  24416. this._soundSource.stop(0);
  24417. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24418. };
  24419. Sound.prototype.setVolume = function (newVolume) {
  24420. this._volume = newVolume;
  24421. this._soundGain.gain.value = newVolume;
  24422. };
  24423. Sound.prototype.getVolume = function () {
  24424. return this._volume;
  24425. };
  24426. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24427. var _this = this;
  24428. this._connectedMesh = meshToConnectTo;
  24429. if (!this.spatialSound) {
  24430. this._createSpatialParameters();
  24431. this.spatialSound = true;
  24432. if (this._isPlaying && this.loop) {
  24433. this.stop();
  24434. this.play();
  24435. }
  24436. }
  24437. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24438. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24439. });
  24440. };
  24441. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24442. this.setPosition(connectedMesh.position);
  24443. if (this._isDirectional && this._isPlaying) {
  24444. this._updateDirection();
  24445. }
  24446. };
  24447. Sound.prototype._soundLoaded = function (audioData) {
  24448. var _this = this;
  24449. this._isLoaded = true;
  24450. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24451. _this._audioBuffer = buffer;
  24452. _this._isReadyToPlay = true;
  24453. if (_this.autoplay) {
  24454. _this.play();
  24455. }
  24456. if (_this._readyToPlayCallback) {
  24457. _this._readyToPlayCallback();
  24458. }
  24459. }, function (error) {
  24460. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24461. });
  24462. };
  24463. return Sound;
  24464. })();
  24465. BABYLON.Sound = Sound;
  24466. })(BABYLON || (BABYLON = {}));
  24467. //# sourceMappingURL=babylon.sound.js.map
  24468. var BABYLON;
  24469. (function (BABYLON) {
  24470. var SoundTrack = (function () {
  24471. function SoundTrack(scene, options) {
  24472. this.id = -1;
  24473. this._isMainTrack = false;
  24474. this._scene = scene;
  24475. this._audioEngine = scene.getEngine().getAudioEngine();
  24476. this.soundCollection = new Array();
  24477. if (this._audioEngine.canUseWebAudio) {
  24478. this._trackGain = this._audioEngine.audioContext.createGain();
  24479. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24480. //this._trackConvolver.connect(this._trackGain);
  24481. this._trackGain.connect(this._audioEngine.masterGain);
  24482. if (options) {
  24483. if (options.volume) {
  24484. this._trackGain.gain.value = options.volume;
  24485. }
  24486. if (options.mainTrack) {
  24487. this._isMainTrack = options.mainTrack;
  24488. }
  24489. }
  24490. }
  24491. if (!this._isMainTrack) {
  24492. this._scene.soundTracks.push(this);
  24493. this.id = this._scene.soundTracks.length - 1;
  24494. }
  24495. }
  24496. SoundTrack.prototype.AddSound = function (sound) {
  24497. sound.connectToSoundTrackAudioNode(this._trackGain);
  24498. if (sound.soundTrackId) {
  24499. if (sound.soundTrackId === -1) {
  24500. this._scene.mainSoundTrack.RemoveSound(sound);
  24501. } else {
  24502. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24503. }
  24504. }
  24505. this.soundCollection.push(sound);
  24506. sound.soundTrackId = this.id;
  24507. };
  24508. SoundTrack.prototype.RemoveSound = function (sound) {
  24509. var index = this.soundCollection.indexOf(sound);
  24510. if (index !== -1) {
  24511. this.soundCollection.splice(index, 1);
  24512. }
  24513. };
  24514. SoundTrack.prototype.setVolume = function (newVolume) {
  24515. if (this._audioEngine.canUseWebAudio) {
  24516. this._trackGain.gain.value = newVolume;
  24517. }
  24518. };
  24519. return SoundTrack;
  24520. })();
  24521. BABYLON.SoundTrack = SoundTrack;
  24522. })(BABYLON || (BABYLON = {}));
  24523. //# sourceMappingURL=babylon.soundtrack.js.map
  24524. var BABYLON;
  24525. (function (BABYLON) {
  24526. var DebugLayer = (function () {
  24527. function DebugLayer(scene) {
  24528. var _this = this;
  24529. this._enabled = false;
  24530. this._labelsEnabled = false;
  24531. this._displayStatistics = true;
  24532. this._displayTree = false;
  24533. this._displayLogs = false;
  24534. this._identityMatrix = BABYLON.Matrix.Identity();
  24535. this.axisRatio = 0.02;
  24536. this.accentColor = "orange";
  24537. this._scene = scene;
  24538. this._syncPositions = function () {
  24539. var engine = _this._scene.getEngine();
  24540. var canvasRect = engine.getRenderingCanvasClientRect();
  24541. if (_this._showUI) {
  24542. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24543. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24544. _this._statsDiv.style.width = "300px";
  24545. _this._statsDiv.style.height = "360px";
  24546. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24547. _this._optionsDiv.style.left = "0px";
  24548. _this._optionsDiv.style.top = "10px";
  24549. _this._optionsDiv.style.width = "200px";
  24550. _this._optionsDiv.style.height = "auto";
  24551. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24552. _this._logDiv.style.left = "0px";
  24553. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24554. _this._logDiv.style.width = "600px";
  24555. _this._logDiv.style.height = "160px";
  24556. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24557. _this._treeDiv.style.top = "10px";
  24558. _this._treeDiv.style.width = "300px";
  24559. _this._treeDiv.style.height = "auto";
  24560. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24561. }
  24562. _this._globalDiv.style.left = canvasRect.left + "px";
  24563. _this._globalDiv.style.top = canvasRect.top + "px";
  24564. _this._drawingCanvas.style.left = "0px";
  24565. _this._drawingCanvas.style.top = "0px";
  24566. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24567. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24568. var devicePixelRatio = window.devicePixelRatio || 1;
  24569. var context = _this._drawingContext;
  24570. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24571. _this._ratio = devicePixelRatio / backingStoreRatio;
  24572. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24573. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24574. };
  24575. this._onCanvasClick = function (evt) {
  24576. _this._clickPosition = {
  24577. x: evt.clientX * _this._ratio,
  24578. y: evt.clientY * _this._ratio
  24579. };
  24580. };
  24581. this._syncData = function () {
  24582. if (_this._showUI) {
  24583. if (_this._displayStatistics) {
  24584. _this._displayStats();
  24585. _this._statsDiv.style.display = "";
  24586. } else {
  24587. _this._statsDiv.style.display = "none";
  24588. }
  24589. if (_this._displayLogs) {
  24590. _this._logDiv.style.display = "";
  24591. } else {
  24592. _this._logDiv.style.display = "none";
  24593. }
  24594. if (_this._displayTree) {
  24595. _this._treeDiv.style.display = "";
  24596. if (_this._needToRefreshMeshesTree) {
  24597. _this._needToRefreshMeshesTree = false;
  24598. _this._refreshMeshesTreeContent();
  24599. }
  24600. } else {
  24601. _this._treeDiv.style.display = "none";
  24602. }
  24603. }
  24604. if (_this._labelsEnabled || !_this._showUI) {
  24605. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24606. var engine = _this._scene.getEngine();
  24607. var viewport = _this._scene.activeCamera.viewport;
  24608. var globalViewport = viewport.toGlobal(engine);
  24609. // Meshes
  24610. var meshes = _this._scene.getActiveMeshes();
  24611. for (var index = 0; index < meshes.length; index++) {
  24612. var mesh = meshes.data[index];
  24613. var position = mesh.getBoundingInfo().boundingSphere.center;
  24614. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24615. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24616. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24617. }
  24618. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24619. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24620. mesh.renderOverlay = !mesh.renderOverlay;
  24621. }, function () {
  24622. return mesh.renderOverlay ? 'red' : 'black';
  24623. });
  24624. }
  24625. }
  24626. // Cameras
  24627. var cameras = _this._scene.cameras;
  24628. for (index = 0; index < cameras.length; index++) {
  24629. var camera = cameras[index];
  24630. if (camera === _this._scene.activeCamera) {
  24631. continue;
  24632. }
  24633. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24634. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24635. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24636. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24637. _this._scene.activeCamera = camera;
  24638. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24639. }, function () {
  24640. return "purple";
  24641. });
  24642. }
  24643. }
  24644. // Lights
  24645. var lights = _this._scene.lights;
  24646. for (index = 0; index < lights.length; index++) {
  24647. var light = lights[index];
  24648. if (light.position) {
  24649. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24650. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24651. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24652. light.setEnabled(!light.isEnabled());
  24653. }, function () {
  24654. return light.isEnabled() ? "orange" : "gray";
  24655. });
  24656. }
  24657. }
  24658. }
  24659. }
  24660. _this._clickPosition = undefined;
  24661. };
  24662. }
  24663. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24664. while (this._treeSubsetDiv.hasChildNodes()) {
  24665. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24666. }
  24667. // Add meshes
  24668. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24669. sortedArray.sort(function (a, b) {
  24670. if (a.name === b.name) {
  24671. return 0;
  24672. }
  24673. return (a.name > b.name) ? 1 : -1;
  24674. });
  24675. for (var index = 0; index < sortedArray.length; index++) {
  24676. var mesh = sortedArray[index];
  24677. if (!mesh.isEnabled()) {
  24678. continue;
  24679. }
  24680. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24681. m.isVisible = element.checked;
  24682. }, mesh);
  24683. }
  24684. };
  24685. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24686. this._drawingContext.beginPath();
  24687. this._drawingContext.moveTo(zero.x, zero.y);
  24688. this._drawingContext.lineTo(unit.x, unit.y);
  24689. this._drawingContext.strokeStyle = color;
  24690. this._drawingContext.lineWidth = 4;
  24691. this._drawingContext.stroke();
  24692. this._drawingContext.font = "normal 14px Segoe UI";
  24693. this._drawingContext.fillStyle = color;
  24694. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24695. };
  24696. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24697. var position = mesh.getBoundingInfo().boundingSphere.center;
  24698. var worldMatrix = mesh.getWorldMatrix();
  24699. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  24700. var unit = (unprojectedVector.subtract(position)).length();
  24701. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24702. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24703. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24704. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24705. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24706. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24707. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24708. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24709. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24710. };
  24711. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24712. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24713. this._drawingContext.font = "normal 12px Segoe UI";
  24714. var textMetrics = this._drawingContext.measureText(text);
  24715. var centerX = projectedPosition.x - textMetrics.width / 2;
  24716. var centerY = projectedPosition.y;
  24717. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24718. onClick();
  24719. }
  24720. this._drawingContext.beginPath();
  24721. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24722. this._drawingContext.fillStyle = getFillStyle();
  24723. this._drawingContext.globalAlpha = 0.5;
  24724. this._drawingContext.fill();
  24725. this._drawingContext.globalAlpha = 1.0;
  24726. this._drawingContext.strokeStyle = '#FFFFFF';
  24727. this._drawingContext.lineWidth = 1;
  24728. this._drawingContext.stroke();
  24729. this._drawingContext.fillStyle = "#FFFFFF";
  24730. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24731. this._drawingContext.beginPath();
  24732. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24733. this._drawingContext.fill();
  24734. }
  24735. };
  24736. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24737. if (!this._clickPosition) {
  24738. return false;
  24739. }
  24740. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24741. return false;
  24742. }
  24743. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24744. return false;
  24745. }
  24746. return true;
  24747. };
  24748. DebugLayer.prototype.isVisible = function () {
  24749. return this._enabled;
  24750. };
  24751. DebugLayer.prototype.hide = function () {
  24752. if (!this._enabled) {
  24753. return;
  24754. }
  24755. this._enabled = false;
  24756. var engine = this._scene.getEngine();
  24757. this._scene.unregisterAfterRender(this._syncData);
  24758. document.body.removeChild(this._globalDiv);
  24759. window.removeEventListener("resize", this._syncPositions);
  24760. this._scene.forceShowBoundingBoxes = false;
  24761. this._scene.forceWireframe = false;
  24762. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24763. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24764. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24765. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24766. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24767. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24768. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24769. this._scene.shadowsEnabled = true;
  24770. this._scene.particlesEnabled = true;
  24771. this._scene.postProcessesEnabled = true;
  24772. this._scene.collisionsEnabled = true;
  24773. this._scene.lightsEnabled = true;
  24774. this._scene.texturesEnabled = true;
  24775. this._scene.lensFlaresEnabled = true;
  24776. this._scene.proceduralTexturesEnabled = true;
  24777. this._scene.renderTargetsEnabled = true;
  24778. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24779. };
  24780. DebugLayer.prototype.show = function (showUI) {
  24781. if (typeof showUI === "undefined") { showUI = true; }
  24782. if (this._enabled) {
  24783. return;
  24784. }
  24785. this._enabled = true;
  24786. this._showUI = showUI;
  24787. var engine = this._scene.getEngine();
  24788. this._globalDiv = document.createElement("div");
  24789. document.body.appendChild(this._globalDiv);
  24790. this._generateDOMelements();
  24791. window.addEventListener("resize", this._syncPositions);
  24792. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24793. this._syncPositions();
  24794. this._scene.registerAfterRender(this._syncData);
  24795. };
  24796. DebugLayer.prototype._clearLabels = function () {
  24797. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24798. for (var index = 0; index < this._scene.meshes.length; index++) {
  24799. var mesh = this._scene.meshes[index];
  24800. mesh.renderOverlay = false;
  24801. }
  24802. };
  24803. DebugLayer.prototype._generateheader = function (root, text) {
  24804. var header = document.createElement("div");
  24805. header.innerHTML = text + "&nbsp;";
  24806. header.style.textAlign = "right";
  24807. header.style.width = "100%";
  24808. header.style.color = "white";
  24809. header.style.backgroundColor = "Black";
  24810. header.style.padding = "5px 5px 4px 0px";
  24811. header.style.marginLeft = "-5px";
  24812. header.style.fontWeight = "bold";
  24813. root.appendChild(header);
  24814. };
  24815. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24816. var label = document.createElement("label");
  24817. label.innerHTML = title;
  24818. label.style.color = color;
  24819. root.appendChild(label);
  24820. root.appendChild(document.createElement("br"));
  24821. };
  24822. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24823. if (typeof tag === "undefined") { tag = null; }
  24824. var label = document.createElement("label");
  24825. var boundingBoxesCheckbox = document.createElement("input");
  24826. boundingBoxesCheckbox.type = "checkbox";
  24827. boundingBoxesCheckbox.checked = initialState;
  24828. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24829. task(evt.target, tag);
  24830. });
  24831. label.appendChild(boundingBoxesCheckbox);
  24832. var container = document.createElement("span");
  24833. var leftPart = document.createElement("span");
  24834. var rightPart = document.createElement("span");
  24835. rightPart.style.cssFloat = "right";
  24836. leftPart.innerHTML = leftTitle;
  24837. rightPart.innerHTML = rightTitle;
  24838. rightPart.style.fontSize = "12px";
  24839. rightPart.style.maxWidth = "200px";
  24840. container.appendChild(leftPart);
  24841. container.appendChild(rightPart);
  24842. label.appendChild(container);
  24843. root.appendChild(label);
  24844. root.appendChild(document.createElement("br"));
  24845. };
  24846. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24847. if (typeof tag === "undefined") { tag = null; }
  24848. var label = document.createElement("label");
  24849. var boundingBoxesCheckbox = document.createElement("input");
  24850. boundingBoxesCheckbox.type = "checkbox";
  24851. boundingBoxesCheckbox.checked = initialState;
  24852. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24853. task(evt.target, tag);
  24854. });
  24855. label.appendChild(boundingBoxesCheckbox);
  24856. label.appendChild(document.createTextNode(title));
  24857. root.appendChild(label);
  24858. root.appendChild(document.createElement("br"));
  24859. };
  24860. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24861. if (typeof tag === "undefined") { tag = null; }
  24862. var label = document.createElement("label");
  24863. var boundingBoxesRadio = document.createElement("input");
  24864. boundingBoxesRadio.type = "radio";
  24865. boundingBoxesRadio.name = name;
  24866. boundingBoxesRadio.checked = initialState;
  24867. boundingBoxesRadio.addEventListener("change", function (evt) {
  24868. task(evt.target, tag);
  24869. });
  24870. label.appendChild(boundingBoxesRadio);
  24871. label.appendChild(document.createTextNode(title));
  24872. root.appendChild(label);
  24873. root.appendChild(document.createElement("br"));
  24874. };
  24875. DebugLayer.prototype._generateDOMelements = function () {
  24876. var _this = this;
  24877. this._globalDiv.id = "DebugLayer";
  24878. this._globalDiv.style.position = "absolute";
  24879. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24880. this._globalDiv.style.fontSize = "14px";
  24881. this._globalDiv.style.color = "white";
  24882. // Drawing canvas
  24883. this._drawingCanvas = document.createElement("canvas");
  24884. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24885. this._drawingCanvas.style.position = "absolute";
  24886. this._drawingCanvas.style.pointerEvents = "none";
  24887. this._drawingContext = this._drawingCanvas.getContext("2d");
  24888. this._globalDiv.appendChild(this._drawingCanvas);
  24889. if (this._showUI) {
  24890. var background = "rgba(128, 128, 128, 0.4)";
  24891. var border = "rgb(180, 180, 180) solid 1px";
  24892. // Stats
  24893. this._statsDiv = document.createElement("div");
  24894. this._statsDiv.id = "DebugLayerStats";
  24895. this._statsDiv.style.border = border;
  24896. this._statsDiv.style.position = "absolute";
  24897. this._statsDiv.style.background = background;
  24898. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24899. this._statsDiv.style.pointerEvents = "none";
  24900. this._statsDiv.style.overflowY = "auto";
  24901. this._generateheader(this._statsDiv, "STATISTICS");
  24902. this._statsSubsetDiv = document.createElement("div");
  24903. this._statsSubsetDiv.style.paddingTop = "5px";
  24904. this._statsSubsetDiv.style.paddingBottom = "5px";
  24905. this._statsDiv.appendChild(this._statsSubsetDiv);
  24906. // Tree
  24907. this._treeDiv = document.createElement("div");
  24908. this._treeDiv.id = "DebugLayerTree";
  24909. this._treeDiv.style.border = border;
  24910. this._treeDiv.style.position = "absolute";
  24911. this._treeDiv.style.background = background;
  24912. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24913. this._treeDiv.style.display = "none";
  24914. this._generateheader(this._treeDiv, "MESHES TREE");
  24915. this._treeSubsetDiv = document.createElement("div");
  24916. this._treeSubsetDiv.style.paddingTop = "5px";
  24917. this._treeSubsetDiv.style.paddingRight = "5px";
  24918. this._treeSubsetDiv.style.overflowY = "auto";
  24919. this._treeSubsetDiv.style.maxHeight = "300px";
  24920. this._treeDiv.appendChild(this._treeSubsetDiv);
  24921. this._needToRefreshMeshesTree = true;
  24922. // Logs
  24923. this._logDiv = document.createElement("div");
  24924. this._logDiv.style.border = border;
  24925. this._logDiv.id = "DebugLayerLogs";
  24926. this._logDiv.style.position = "absolute";
  24927. this._logDiv.style.background = background;
  24928. this._logDiv.style.padding = "0px 0px 0px 5px";
  24929. this._logDiv.style.display = "none";
  24930. this._generateheader(this._logDiv, "LOGS");
  24931. this._logSubsetDiv = document.createElement("div");
  24932. this._logSubsetDiv.style.height = "127px";
  24933. this._logSubsetDiv.style.paddingTop = "5px";
  24934. this._logSubsetDiv.style.overflowY = "auto";
  24935. this._logSubsetDiv.style.fontSize = "12px";
  24936. this._logSubsetDiv.style.fontFamily = "consolas";
  24937. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24938. this._logDiv.appendChild(this._logSubsetDiv);
  24939. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24940. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24941. };
  24942. // Options
  24943. this._optionsDiv = document.createElement("div");
  24944. this._optionsDiv.id = "DebugLayerOptions";
  24945. this._optionsDiv.style.border = border;
  24946. this._optionsDiv.style.position = "absolute";
  24947. this._optionsDiv.style.background = background;
  24948. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24949. this._optionsDiv.style.overflowY = "auto";
  24950. this._generateheader(this._optionsDiv, "OPTIONS");
  24951. this._optionsSubsetDiv = document.createElement("div");
  24952. this._optionsSubsetDiv.style.paddingTop = "5px";
  24953. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24954. this._optionsSubsetDiv.style.overflowY = "auto";
  24955. this._optionsSubsetDiv.style.maxHeight = "200px";
  24956. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24957. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24958. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24959. _this._displayStatistics = element.checked;
  24960. });
  24961. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24962. _this._displayLogs = element.checked;
  24963. });
  24964. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24965. _this._displayTree = element.checked;
  24966. _this._needToRefreshMeshesTree = true;
  24967. });
  24968. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24969. _this._scene.forceShowBoundingBoxes = element.checked;
  24970. });
  24971. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24972. _this._labelsEnabled = element.checked;
  24973. if (!_this._labelsEnabled) {
  24974. _this._clearLabels();
  24975. }
  24976. });
  24977. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24978. if (element.checked) {
  24979. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24980. } else {
  24981. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24982. }
  24983. });
  24984. ;
  24985. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24986. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24987. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24988. if (element.checked) {
  24989. _this._scene.forceWireframe = false;
  24990. _this._scene.forcePointsCloud = false;
  24991. }
  24992. });
  24993. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24994. if (element.checked) {
  24995. _this._scene.forceWireframe = true;
  24996. _this._scene.forcePointsCloud = false;
  24997. }
  24998. });
  24999. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25000. if (element.checked) {
  25001. _this._scene.forceWireframe = false;
  25002. _this._scene.forcePointsCloud = true;
  25003. }
  25004. });
  25005. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25006. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25007. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25008. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25009. });
  25010. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25011. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25012. });
  25013. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25014. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25015. });
  25016. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25017. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25018. });
  25019. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25020. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25021. });
  25022. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25023. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25024. });
  25025. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25026. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25027. });
  25028. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25029. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25030. });
  25031. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25032. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25033. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25034. _this._scene.animationsEnabled = element.checked;
  25035. });
  25036. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25037. _this._scene.collisionsEnabled = element.checked;
  25038. });
  25039. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25040. _this._scene.fogEnabled = element.checked;
  25041. });
  25042. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25043. _this._scene.lensFlaresEnabled = element.checked;
  25044. });
  25045. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25046. _this._scene.lightsEnabled = element.checked;
  25047. });
  25048. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25049. _this._scene.particlesEnabled = element.checked;
  25050. });
  25051. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25052. _this._scene.postProcessesEnabled = element.checked;
  25053. });
  25054. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25055. _this._scene.proceduralTexturesEnabled = element.checked;
  25056. });
  25057. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25058. _this._scene.renderTargetsEnabled = element.checked;
  25059. });
  25060. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25061. _this._scene.shadowsEnabled = element.checked;
  25062. });
  25063. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25064. _this._scene.skeletonsEnabled = element.checked;
  25065. });
  25066. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25067. _this._scene.texturesEnabled = element.checked;
  25068. });
  25069. this._globalDiv.appendChild(this._statsDiv);
  25070. this._globalDiv.appendChild(this._logDiv);
  25071. this._globalDiv.appendChild(this._optionsDiv);
  25072. this._globalDiv.appendChild(this._treeDiv);
  25073. }
  25074. };
  25075. DebugLayer.prototype._displayStats = function () {
  25076. var scene = this._scene;
  25077. var engine = scene.getEngine();
  25078. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.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 bones: " + scene.getActiveBones() + "<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>";
  25079. };
  25080. return DebugLayer;
  25081. })();
  25082. BABYLON.DebugLayer = DebugLayer;
  25083. })(BABYLON || (BABYLON = {}));
  25084. //# sourceMappingURL=babylon.debugLayer.js.map
  25085. var BABYLON;
  25086. (function (BABYLON) {
  25087. var RawTexture = (function (_super) {
  25088. __extends(RawTexture, _super);
  25089. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25090. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25091. if (typeof invertY === "undefined") { invertY = false; }
  25092. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25093. _super.call(this, null, scene, !generateMipMaps, invertY);
  25094. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25095. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25096. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25097. }
  25098. // Statics
  25099. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25100. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25101. if (typeof invertY === "undefined") { invertY = false; }
  25102. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25103. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25104. };
  25105. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25106. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25107. if (typeof invertY === "undefined") { invertY = false; }
  25108. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25109. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25110. };
  25111. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25112. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25113. if (typeof invertY === "undefined") { invertY = false; }
  25114. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25115. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25116. };
  25117. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25118. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25119. if (typeof invertY === "undefined") { invertY = false; }
  25120. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25121. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25122. };
  25123. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25124. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25125. if (typeof invertY === "undefined") { invertY = false; }
  25126. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25127. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25128. };
  25129. return RawTexture;
  25130. })(BABYLON.Texture);
  25131. BABYLON.RawTexture = RawTexture;
  25132. })(BABYLON || (BABYLON = {}));
  25133. //# sourceMappingURL=babylon.rawTexture.js.map
  25134. var BABYLON;
  25135. (function (BABYLON) {
  25136. var IndexedVector2 = (function (_super) {
  25137. __extends(IndexedVector2, _super);
  25138. function IndexedVector2(original, index) {
  25139. _super.call(this, original.x, original.y);
  25140. this.index = index;
  25141. }
  25142. return IndexedVector2;
  25143. })(BABYLON.Vector2);
  25144. var PolygonPoints = (function () {
  25145. function PolygonPoints() {
  25146. this.elements = new Array();
  25147. }
  25148. PolygonPoints.prototype.add = function (originalPoints) {
  25149. var _this = this;
  25150. var result = new Array();
  25151. originalPoints.forEach(function (point) {
  25152. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25153. var newPoint = new IndexedVector2(point, _this.elements.length);
  25154. result.push(newPoint);
  25155. _this.elements.push(newPoint);
  25156. }
  25157. });
  25158. return result;
  25159. };
  25160. PolygonPoints.prototype.computeBounds = function () {
  25161. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25162. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25163. this.elements.forEach(function (point) {
  25164. // x
  25165. if (point.x < lmin.x) {
  25166. lmin.x = point.x;
  25167. } else if (point.x > lmax.x) {
  25168. lmax.x = point.x;
  25169. }
  25170. // y
  25171. if (point.y < lmin.y) {
  25172. lmin.y = point.y;
  25173. } else if (point.y > lmax.y) {
  25174. lmax.y = point.y;
  25175. }
  25176. });
  25177. return {
  25178. min: lmin,
  25179. max: lmax,
  25180. width: lmax.x - lmin.x,
  25181. height: lmax.y - lmin.y
  25182. };
  25183. };
  25184. return PolygonPoints;
  25185. })();
  25186. var Polygon = (function () {
  25187. function Polygon() {
  25188. }
  25189. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25190. return [
  25191. new BABYLON.Vector2(xmin, ymin),
  25192. new BABYLON.Vector2(xmax, ymin),
  25193. new BABYLON.Vector2(xmax, ymax),
  25194. new BABYLON.Vector2(xmin, ymax)
  25195. ];
  25196. };
  25197. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25198. if (typeof cx === "undefined") { cx = 0; }
  25199. if (typeof cy === "undefined") { cy = 0; }
  25200. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25201. var result = new Array();
  25202. var angle = 0;
  25203. var increment = (Math.PI * 2) / numberOfSides;
  25204. for (var i = 0; i < numberOfSides; i++) {
  25205. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25206. angle -= increment;
  25207. }
  25208. return result;
  25209. };
  25210. Polygon.Parse = function (input) {
  25211. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25212. return (!isNaN(val));
  25213. });
  25214. var i, result = [];
  25215. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25216. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25217. }
  25218. return result;
  25219. };
  25220. Polygon.StartingAt = function (x, y) {
  25221. return BABYLON.Path2.StartingAt(x, y);
  25222. };
  25223. return Polygon;
  25224. })();
  25225. BABYLON.Polygon = Polygon;
  25226. var PolygonMeshBuilder = (function () {
  25227. function PolygonMeshBuilder(name, contours, scene) {
  25228. this._points = new PolygonPoints();
  25229. if (!("poly2tri" in window)) {
  25230. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25231. }
  25232. this._name = name;
  25233. this._scene = scene;
  25234. var points;
  25235. if (contours instanceof BABYLON.Path2) {
  25236. points = contours.getPoints();
  25237. } else {
  25238. points = contours;
  25239. }
  25240. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25241. }
  25242. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25243. this._swctx.addHole(this._points.add(hole));
  25244. return this;
  25245. };
  25246. PolygonMeshBuilder.prototype.build = function (updatable) {
  25247. if (typeof updatable === "undefined") { updatable = false; }
  25248. var result = new BABYLON.Mesh(this._name, this._scene);
  25249. var normals = [];
  25250. var positions = [];
  25251. var uvs = [];
  25252. var bounds = this._points.computeBounds();
  25253. this._points.elements.forEach(function (p) {
  25254. normals.push(0, 1.0, 0);
  25255. positions.push(p.x, 0, p.y);
  25256. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25257. });
  25258. var indices = [];
  25259. this._swctx.triangulate();
  25260. this._swctx.getTriangles().forEach(function (triangle) {
  25261. triangle.getPoints().forEach(function (point) {
  25262. indices.push(point.index);
  25263. });
  25264. });
  25265. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25266. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25267. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25268. result.setIndices(indices);
  25269. return result;
  25270. };
  25271. return PolygonMeshBuilder;
  25272. })();
  25273. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25274. })(BABYLON || (BABYLON = {}));
  25275. //# sourceMappingURL=babylon.polygonMesh.js.map