babylon.2.0-alpha.debug.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635
  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) {
  2512. var num = a - b;
  2513. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2514. };
  2515. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2516. for (var prop in source) {
  2517. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2518. continue;
  2519. }
  2520. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2521. continue;
  2522. }
  2523. var sourceValue = source[prop];
  2524. var typeOfSourceValue = typeof sourceValue;
  2525. if (typeOfSourceValue == "function") {
  2526. continue;
  2527. }
  2528. if (typeOfSourceValue == "object") {
  2529. if (sourceValue instanceof Array) {
  2530. destination[prop] = [];
  2531. if (sourceValue.length > 0) {
  2532. if (typeof sourceValue[0] == "object") {
  2533. for (var index = 0; index < sourceValue.length; index++) {
  2534. var clonedValue = cloneValue(sourceValue[index], destination);
  2535. if (destination[prop].indexOf(clonedValue) === -1) {
  2536. destination[prop].push(clonedValue);
  2537. }
  2538. }
  2539. } else {
  2540. destination[prop] = sourceValue.slice(0);
  2541. }
  2542. }
  2543. } else {
  2544. destination[prop] = cloneValue(sourceValue, destination);
  2545. }
  2546. } else {
  2547. destination[prop] = sourceValue;
  2548. }
  2549. }
  2550. };
  2551. Tools.IsEmpty = function (obj) {
  2552. for (var i in obj) {
  2553. return false;
  2554. }
  2555. return true;
  2556. };
  2557. Tools.RegisterTopRootEvents = function (events) {
  2558. for (var index = 0; index < events.length; index++) {
  2559. var event = events[index];
  2560. window.addEventListener(event.name, event.handler, false);
  2561. try {
  2562. if (window.parent) {
  2563. window.parent.addEventListener(event.name, event.handler, false);
  2564. }
  2565. } catch (e) {
  2566. // Silently fails...
  2567. }
  2568. }
  2569. };
  2570. Tools.UnregisterTopRootEvents = function (events) {
  2571. for (var index = 0; index < events.length; index++) {
  2572. var event = events[index];
  2573. window.removeEventListener(event.name, event.handler);
  2574. try {
  2575. if (window.parent) {
  2576. window.parent.removeEventListener(event.name, event.handler);
  2577. }
  2578. } catch (e) {
  2579. // Silently fails...
  2580. }
  2581. }
  2582. };
  2583. Tools.CreateScreenshot = function (engine, camera, size) {
  2584. var width;
  2585. var height;
  2586. var scene = camera.getScene();
  2587. var previousCamera = null;
  2588. if (scene.activeCamera !== camera) {
  2589. previousCamera = scene.activeCamera;
  2590. scene.activeCamera = camera;
  2591. }
  2592. //If a precision value is specified
  2593. if (size.precision) {
  2594. width = Math.round(engine.getRenderWidth() * size.precision);
  2595. height = Math.round(width / engine.getAspectRatio(camera));
  2596. size = { width: width, height: height };
  2597. } else if (size.width && size.height) {
  2598. width = size.width;
  2599. height = size.height;
  2600. } else if (size.width && !size.height) {
  2601. width = size.width;
  2602. height = Math.round(width / engine.getAspectRatio(camera));
  2603. size = { width: width, height: height };
  2604. } else if (size.height && !size.width) {
  2605. height = size.height;
  2606. width = Math.round(height * engine.getAspectRatio(camera));
  2607. size = { width: width, height: height };
  2608. } else if (!isNaN(size)) {
  2609. height = size;
  2610. width = size;
  2611. } else {
  2612. Tools.Error("Invalid 'size' parameter !");
  2613. return;
  2614. }
  2615. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2616. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2617. texture.renderList = engine.scenes[0].meshes;
  2618. texture.onAfterRender = function () {
  2619. // Read the contents of the framebuffer
  2620. var numberOfChannelsByLine = width * 4;
  2621. var halfHeight = height / 2;
  2622. //Reading datas from WebGL
  2623. var data = engine.readPixels(0, 0, width, height);
  2624. for (var i = 0; i < halfHeight; i++) {
  2625. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2626. var currentCell = j + i * numberOfChannelsByLine;
  2627. var targetLine = height - i - 1;
  2628. var targetCell = j + targetLine * numberOfChannelsByLine;
  2629. var temp = data[currentCell];
  2630. data[currentCell] = data[targetCell];
  2631. data[targetCell] = temp;
  2632. }
  2633. }
  2634. // Create a 2D canvas to store the result
  2635. if (!screenshotCanvas) {
  2636. screenshotCanvas = document.createElement('canvas');
  2637. }
  2638. screenshotCanvas.width = width;
  2639. screenshotCanvas.height = height;
  2640. var context = screenshotCanvas.getContext('2d');
  2641. // Copy the pixels to a 2D canvas
  2642. var imageData = context.createImageData(width, height);
  2643. imageData.data.set(data);
  2644. context.putImageData(imageData, 0, 0);
  2645. var base64Image = screenshotCanvas.toDataURL();
  2646. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2647. if (("download" in document.createElement("a"))) {
  2648. var a = window.document.createElement("a");
  2649. a.href = base64Image;
  2650. var date = new Date();
  2651. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2652. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2653. window.document.body.appendChild(a);
  2654. a.addEventListener("click", function () {
  2655. a.parentElement.removeChild(a);
  2656. });
  2657. a.click();
  2658. //Or opening a new tab with the image if it is not possible to automatically start download.
  2659. } else {
  2660. var newWindow = window.open("");
  2661. var img = newWindow.document.createElement("img");
  2662. img.src = base64Image;
  2663. newWindow.document.body.appendChild(img);
  2664. }
  2665. };
  2666. texture.render(true);
  2667. texture.dispose();
  2668. if (previousCamera) {
  2669. scene.activeCamera = previousCamera;
  2670. }
  2671. };
  2672. // XHR response validator for local file scenario
  2673. Tools.ValidateXHRData = function (xhr, dataType) {
  2674. if (typeof dataType === "undefined") { dataType = 7; }
  2675. try {
  2676. if (dataType & 1) {
  2677. if (xhr.responseText && xhr.responseText.length > 0) {
  2678. return true;
  2679. } else if (dataType === 1) {
  2680. return false;
  2681. }
  2682. }
  2683. if (dataType & 2) {
  2684. // Check header width and height since there is no "TGA" magic number
  2685. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2686. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2687. return true;
  2688. } else if (dataType === 2) {
  2689. return false;
  2690. }
  2691. }
  2692. if (dataType & 4) {
  2693. // Check for the "DDS" magic number
  2694. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2695. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2696. return true;
  2697. } else {
  2698. return false;
  2699. }
  2700. }
  2701. } catch (e) {
  2702. // Global protection
  2703. }
  2704. return false;
  2705. };
  2706. Object.defineProperty(Tools, "NoneLogLevel", {
  2707. get: function () {
  2708. return Tools._NoneLogLevel;
  2709. },
  2710. enumerable: true,
  2711. configurable: true
  2712. });
  2713. Object.defineProperty(Tools, "MessageLogLevel", {
  2714. get: function () {
  2715. return Tools._MessageLogLevel;
  2716. },
  2717. enumerable: true,
  2718. configurable: true
  2719. });
  2720. Object.defineProperty(Tools, "WarningLogLevel", {
  2721. get: function () {
  2722. return Tools._WarningLogLevel;
  2723. },
  2724. enumerable: true,
  2725. configurable: true
  2726. });
  2727. Object.defineProperty(Tools, "ErrorLogLevel", {
  2728. get: function () {
  2729. return Tools._ErrorLogLevel;
  2730. },
  2731. enumerable: true,
  2732. configurable: true
  2733. });
  2734. Object.defineProperty(Tools, "AllLogLevel", {
  2735. get: function () {
  2736. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2737. },
  2738. enumerable: true,
  2739. configurable: true
  2740. });
  2741. Tools._AddLogEntry = function (entry) {
  2742. Tools._LogCache = entry + Tools._LogCache;
  2743. if (Tools.OnNewCacheEntry) {
  2744. Tools.OnNewCacheEntry(entry);
  2745. }
  2746. };
  2747. Tools._FormatMessage = function (message) {
  2748. var padStr = function (i) {
  2749. return (i < 10) ? "0" + i : "" + i;
  2750. };
  2751. var date = new Date();
  2752. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2753. };
  2754. Tools._LogDisabled = function (message) {
  2755. // nothing to do
  2756. };
  2757. Tools._LogEnabled = function (message) {
  2758. var formattedMessage = Tools._FormatMessage(message);
  2759. console.log("BJS - " + formattedMessage);
  2760. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2761. Tools._AddLogEntry(entry);
  2762. };
  2763. Tools._WarnDisabled = function (message) {
  2764. // nothing to do
  2765. };
  2766. Tools._WarnEnabled = function (message) {
  2767. var formattedMessage = Tools._FormatMessage(message);
  2768. console.warn("BJS - " + formattedMessage);
  2769. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2770. Tools._AddLogEntry(entry);
  2771. };
  2772. Tools._ErrorDisabled = function (message) {
  2773. // nothing to do
  2774. };
  2775. Tools._ErrorEnabled = function (message) {
  2776. var formattedMessage = Tools._FormatMessage(message);
  2777. console.error("BJS - " + formattedMessage);
  2778. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2779. Tools._AddLogEntry(entry);
  2780. };
  2781. Object.defineProperty(Tools, "LogCache", {
  2782. get: function () {
  2783. return Tools._LogCache;
  2784. },
  2785. enumerable: true,
  2786. configurable: true
  2787. });
  2788. Object.defineProperty(Tools, "LogLevels", {
  2789. set: function (level) {
  2790. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2791. Tools.Log = Tools._LogEnabled;
  2792. } else {
  2793. Tools.Log = Tools._LogDisabled;
  2794. }
  2795. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2796. Tools.Warn = Tools._WarnEnabled;
  2797. } else {
  2798. Tools.Warn = Tools._WarnDisabled;
  2799. }
  2800. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2801. Tools.Error = Tools._ErrorEnabled;
  2802. } else {
  2803. Tools.Error = Tools._ErrorDisabled;
  2804. }
  2805. },
  2806. enumerable: true,
  2807. configurable: true
  2808. });
  2809. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2810. get: function () {
  2811. return Tools._PerformanceNoneLogLevel;
  2812. },
  2813. enumerable: true,
  2814. configurable: true
  2815. });
  2816. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2817. get: function () {
  2818. return Tools._PerformanceUserMarkLogLevel;
  2819. },
  2820. enumerable: true,
  2821. configurable: true
  2822. });
  2823. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2824. get: function () {
  2825. return Tools._PerformanceConsoleLogLevel;
  2826. },
  2827. enumerable: true,
  2828. configurable: true
  2829. });
  2830. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2831. set: function (level) {
  2832. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2833. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2834. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2835. return;
  2836. }
  2837. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2838. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2839. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2840. return;
  2841. }
  2842. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2843. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2844. },
  2845. enumerable: true,
  2846. configurable: true
  2847. });
  2848. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2849. };
  2850. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2851. };
  2852. Tools._StartUserMark = function (counterName, condition) {
  2853. if (typeof condition === "undefined") { condition = true; }
  2854. if (!condition || !Tools._performance.mark) {
  2855. return;
  2856. }
  2857. Tools._performance.mark(counterName + "-Begin");
  2858. };
  2859. Tools._EndUserMark = function (counterName, condition) {
  2860. if (typeof condition === "undefined") { condition = true; }
  2861. if (!condition || !Tools._performance.mark) {
  2862. return;
  2863. }
  2864. Tools._performance.mark(counterName + "-End");
  2865. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2866. };
  2867. Tools._StartPerformanceConsole = function (counterName, condition) {
  2868. if (typeof condition === "undefined") { condition = true; }
  2869. if (!condition) {
  2870. return;
  2871. }
  2872. Tools._StartUserMark(counterName, condition);
  2873. if (console.time) {
  2874. console.time(counterName);
  2875. }
  2876. };
  2877. Tools._EndPerformanceConsole = function (counterName, condition) {
  2878. if (typeof condition === "undefined") { condition = true; }
  2879. if (!condition) {
  2880. return;
  2881. }
  2882. Tools._EndUserMark(counterName, condition);
  2883. if (console.time) {
  2884. console.timeEnd(counterName);
  2885. }
  2886. };
  2887. Object.defineProperty(Tools, "Now", {
  2888. get: function () {
  2889. if (window.performance && window.performance.now) {
  2890. return window.performance.now();
  2891. }
  2892. return new Date().getTime();
  2893. },
  2894. enumerable: true,
  2895. configurable: true
  2896. });
  2897. // Deprecated
  2898. Tools.GetFps = function () {
  2899. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2900. return 0;
  2901. };
  2902. Tools.BaseUrl = "";
  2903. Tools.GetExponantOfTwo = function (value, max) {
  2904. var count = 1;
  2905. do {
  2906. count *= 2;
  2907. } while(count < value);
  2908. if (count > max)
  2909. count = max;
  2910. return count;
  2911. };
  2912. Tools._NoneLogLevel = 0;
  2913. Tools._MessageLogLevel = 1;
  2914. Tools._WarningLogLevel = 2;
  2915. Tools._ErrorLogLevel = 4;
  2916. Tools._LogCache = "";
  2917. Tools.Log = Tools._LogEnabled;
  2918. Tools.Warn = Tools._WarnEnabled;
  2919. Tools.Error = Tools._ErrorEnabled;
  2920. Tools._PerformanceNoneLogLevel = 0;
  2921. Tools._PerformanceUserMarkLogLevel = 1;
  2922. Tools._PerformanceConsoleLogLevel = 2;
  2923. Tools._performance = window.performance;
  2924. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2925. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2926. return Tools;
  2927. })();
  2928. BABYLON.Tools = Tools;
  2929. })(BABYLON || (BABYLON = {}));
  2930. //# sourceMappingURL=babylon.tools.js.map
  2931. var BABYLON;
  2932. (function (BABYLON) {
  2933. var _DepthCullingState = (function () {
  2934. function _DepthCullingState() {
  2935. this._isDepthTestDirty = false;
  2936. this._isDepthMaskDirty = false;
  2937. this._isDepthFuncDirty = false;
  2938. this._isCullFaceDirty = false;
  2939. this._isCullDirty = false;
  2940. }
  2941. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2942. get: function () {
  2943. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2944. },
  2945. enumerable: true,
  2946. configurable: true
  2947. });
  2948. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2949. get: function () {
  2950. return this._cullFace;
  2951. },
  2952. set: function (value) {
  2953. if (this._cullFace === value) {
  2954. return;
  2955. }
  2956. this._cullFace = value;
  2957. this._isCullFaceDirty = true;
  2958. },
  2959. enumerable: true,
  2960. configurable: true
  2961. });
  2962. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2963. get: function () {
  2964. return this._cull;
  2965. },
  2966. set: function (value) {
  2967. if (this._cull === value) {
  2968. return;
  2969. }
  2970. this._cull = value;
  2971. this._isCullDirty = true;
  2972. },
  2973. enumerable: true,
  2974. configurable: true
  2975. });
  2976. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2977. get: function () {
  2978. return this._depthFunc;
  2979. },
  2980. set: function (value) {
  2981. if (this._depthFunc === value) {
  2982. return;
  2983. }
  2984. this._depthFunc = value;
  2985. this._isDepthFuncDirty = true;
  2986. },
  2987. enumerable: true,
  2988. configurable: true
  2989. });
  2990. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2991. get: function () {
  2992. return this._depthMask;
  2993. },
  2994. set: function (value) {
  2995. if (this._depthMask === value) {
  2996. return;
  2997. }
  2998. this._depthMask = value;
  2999. this._isDepthMaskDirty = true;
  3000. },
  3001. enumerable: true,
  3002. configurable: true
  3003. });
  3004. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3005. get: function () {
  3006. return this._depthTest;
  3007. },
  3008. set: function (value) {
  3009. if (this._depthTest === value) {
  3010. return;
  3011. }
  3012. this._depthTest = value;
  3013. this._isDepthTestDirty = true;
  3014. },
  3015. enumerable: true,
  3016. configurable: true
  3017. });
  3018. _DepthCullingState.prototype.reset = function () {
  3019. this._depthMask = true;
  3020. this._depthTest = true;
  3021. this._depthFunc = null;
  3022. this._cull = null;
  3023. this._cullFace = null;
  3024. this._isDepthTestDirty = true;
  3025. this._isDepthMaskDirty = true;
  3026. this._isDepthFuncDirty = false;
  3027. this._isCullFaceDirty = false;
  3028. this._isCullDirty = false;
  3029. };
  3030. _DepthCullingState.prototype.apply = function (gl) {
  3031. if (!this.isDirty) {
  3032. return;
  3033. }
  3034. // Cull
  3035. if (this._isCullDirty) {
  3036. if (this.cull === true) {
  3037. gl.enable(gl.CULL_FACE);
  3038. } else if (this.cull === false) {
  3039. gl.disable(gl.CULL_FACE);
  3040. }
  3041. this._isCullDirty = false;
  3042. }
  3043. // Cull face
  3044. if (this._isCullFaceDirty) {
  3045. gl.cullFace(this.cullFace);
  3046. this._isCullFaceDirty = false;
  3047. }
  3048. // Depth mask
  3049. if (this._isDepthMaskDirty) {
  3050. gl.depthMask(this.depthMask);
  3051. this._isDepthMaskDirty = false;
  3052. }
  3053. // Depth test
  3054. if (this._isDepthTestDirty) {
  3055. if (this.depthTest === true) {
  3056. gl.enable(gl.DEPTH_TEST);
  3057. } else if (this.depthTest === false) {
  3058. gl.disable(gl.DEPTH_TEST);
  3059. }
  3060. this._isDepthTestDirty = false;
  3061. }
  3062. // Depth func
  3063. if (this._isDepthFuncDirty) {
  3064. gl.depthFunc(this.depthFunc);
  3065. this._isDepthFuncDirty = false;
  3066. }
  3067. };
  3068. return _DepthCullingState;
  3069. })();
  3070. BABYLON._DepthCullingState = _DepthCullingState;
  3071. var _AlphaState = (function () {
  3072. function _AlphaState() {
  3073. this._isAlphaBlendDirty = false;
  3074. this._isBlendFunctionParametersDirty = false;
  3075. this._alphaBlend = false;
  3076. this._blendFunctionParameters = new Array(4);
  3077. }
  3078. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3079. get: function () {
  3080. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3081. },
  3082. enumerable: true,
  3083. configurable: true
  3084. });
  3085. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3086. get: function () {
  3087. return this._alphaBlend;
  3088. },
  3089. set: function (value) {
  3090. if (this._alphaBlend === value) {
  3091. return;
  3092. }
  3093. this._alphaBlend = value;
  3094. this._isAlphaBlendDirty = true;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3100. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3101. return;
  3102. }
  3103. this._blendFunctionParameters[0] = value0;
  3104. this._blendFunctionParameters[1] = value1;
  3105. this._blendFunctionParameters[2] = value2;
  3106. this._blendFunctionParameters[3] = value3;
  3107. this._isBlendFunctionParametersDirty = true;
  3108. };
  3109. _AlphaState.prototype.reset = function () {
  3110. this._alphaBlend = false;
  3111. this._blendFunctionParameters[0] = null;
  3112. this._blendFunctionParameters[1] = null;
  3113. this._blendFunctionParameters[2] = null;
  3114. this._blendFunctionParameters[3] = null;
  3115. this._isAlphaBlendDirty = true;
  3116. this._isBlendFunctionParametersDirty = false;
  3117. };
  3118. _AlphaState.prototype.apply = function (gl) {
  3119. if (!this.isDirty) {
  3120. return;
  3121. }
  3122. // Alpha blend
  3123. if (this._isAlphaBlendDirty) {
  3124. if (this._alphaBlend === true) {
  3125. gl.enable(gl.BLEND);
  3126. } else if (this._alphaBlend === false) {
  3127. gl.disable(gl.BLEND);
  3128. }
  3129. this._isAlphaBlendDirty = false;
  3130. }
  3131. // Alpha function
  3132. if (this._isBlendFunctionParametersDirty) {
  3133. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3134. this._isBlendFunctionParametersDirty = false;
  3135. }
  3136. };
  3137. return _AlphaState;
  3138. })();
  3139. BABYLON._AlphaState = _AlphaState;
  3140. var compileShader = function (gl, source, type, defines) {
  3141. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3142. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3143. gl.compileShader(shader);
  3144. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3145. throw new Error(gl.getShaderInfoLog(shader));
  3146. }
  3147. return shader;
  3148. };
  3149. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3150. var magFilter = gl.NEAREST;
  3151. var minFilter = gl.NEAREST;
  3152. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3153. magFilter = gl.LINEAR;
  3154. if (generateMipMaps) {
  3155. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3156. } else {
  3157. minFilter = gl.LINEAR;
  3158. }
  3159. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3160. magFilter = gl.LINEAR;
  3161. if (generateMipMaps) {
  3162. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3163. } else {
  3164. minFilter = gl.LINEAR;
  3165. }
  3166. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3167. magFilter = gl.NEAREST;
  3168. if (generateMipMaps) {
  3169. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3170. } else {
  3171. minFilter = gl.NEAREST;
  3172. }
  3173. }
  3174. return {
  3175. min: minFilter,
  3176. mag: magFilter
  3177. };
  3178. };
  3179. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3180. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3181. var engine = scene.getEngine();
  3182. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3183. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3184. gl.bindTexture(gl.TEXTURE_2D, texture);
  3185. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3186. processFunction(potWidth, potHeight);
  3187. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3190. if (!noMipmap && !isCompressed) {
  3191. gl.generateMipmap(gl.TEXTURE_2D);
  3192. }
  3193. gl.bindTexture(gl.TEXTURE_2D, null);
  3194. engine._activeTexturesCache = [];
  3195. texture._baseWidth = width;
  3196. texture._baseHeight = height;
  3197. texture._width = potWidth;
  3198. texture._height = potHeight;
  3199. texture.isReady = true;
  3200. texture.samplingMode = samplingMode;
  3201. scene._removePendingData(texture);
  3202. };
  3203. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3204. var img;
  3205. var onload = function () {
  3206. loadedImages[index] = img;
  3207. loadedImages._internalCount++;
  3208. scene._removePendingData(img);
  3209. if (loadedImages._internalCount == 6) {
  3210. onfinish(loadedImages);
  3211. }
  3212. };
  3213. var onerror = function () {
  3214. scene._removePendingData(img);
  3215. };
  3216. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3217. scene._addPendingData(img);
  3218. };
  3219. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3220. var loadedImages = [];
  3221. loadedImages._internalCount = 0;
  3222. for (var index = 0; index < 6; index++) {
  3223. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3224. }
  3225. };
  3226. var EngineCapabilities = (function () {
  3227. function EngineCapabilities() {
  3228. }
  3229. return EngineCapabilities;
  3230. })();
  3231. BABYLON.EngineCapabilities = EngineCapabilities;
  3232. var Engine = (function () {
  3233. function Engine(canvas, antialias, options) {
  3234. var _this = this;
  3235. // Public members
  3236. this.isFullscreen = false;
  3237. this.isPointerLock = false;
  3238. this.cullBackFaces = true;
  3239. this.renderEvenInBackground = true;
  3240. this.scenes = new Array();
  3241. this._windowIsBackground = false;
  3242. this._loadingDivBackgroundColor = "black";
  3243. this._drawCalls = 0;
  3244. this._renderingQueueLaunched = false;
  3245. this._activeRenderLoops = [];
  3246. // FPS
  3247. this.fpsRange = 60;
  3248. this.previousFramesDuration = [];
  3249. this.fps = 60;
  3250. this.deltaTime = 0;
  3251. // States
  3252. this._depthCullingState = new _DepthCullingState();
  3253. this._alphaState = new _AlphaState();
  3254. this._alphaMode = Engine.ALPHA_DISABLE;
  3255. // Cache
  3256. this._loadedTexturesCache = new Array();
  3257. this._activeTexturesCache = new Array();
  3258. this._compiledEffects = {};
  3259. this._uintIndicesCurrentlySet = false;
  3260. this._renderingCanvas = canvas;
  3261. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3262. options = options || {};
  3263. options.antialias = antialias;
  3264. try {
  3265. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3266. } catch (e) {
  3267. throw new Error("WebGL not supported");
  3268. }
  3269. if (!this._gl) {
  3270. throw new Error("WebGL not supported");
  3271. }
  3272. this._onBlur = function () {
  3273. _this._windowIsBackground = true;
  3274. };
  3275. this._onFocus = function () {
  3276. _this._windowIsBackground = false;
  3277. };
  3278. window.addEventListener("blur", this._onBlur);
  3279. window.addEventListener("focus", this._onFocus);
  3280. // Textures
  3281. this._workingCanvas = document.createElement("canvas");
  3282. this._workingContext = this._workingCanvas.getContext("2d");
  3283. // Viewport
  3284. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3285. this.resize();
  3286. // Caps
  3287. this._caps = new EngineCapabilities();
  3288. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3289. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3290. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3291. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3292. // Extensions
  3293. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3295. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3296. 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');
  3297. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3298. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3299. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3300. // Depth buffer
  3301. this.setDepthBuffer(true);
  3302. this.setDepthFunctionToLessOrEqual();
  3303. this.setDepthWrite(true);
  3304. // Fullscreen
  3305. this._onFullscreenChange = function () {
  3306. if (document.fullscreen !== undefined) {
  3307. _this.isFullscreen = document.fullscreen;
  3308. } else if (document.mozFullScreen !== undefined) {
  3309. _this.isFullscreen = document.mozFullScreen;
  3310. } else if (document.webkitIsFullScreen !== undefined) {
  3311. _this.isFullscreen = document.webkitIsFullScreen;
  3312. } else if (document.msIsFullScreen !== undefined) {
  3313. _this.isFullscreen = document.msIsFullScreen;
  3314. }
  3315. // Pointer lock
  3316. if (_this.isFullscreen && _this._pointerLockRequested) {
  3317. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3318. if (canvas.requestPointerLock) {
  3319. canvas.requestPointerLock();
  3320. }
  3321. }
  3322. };
  3323. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3324. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3325. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3326. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3327. // Pointer lock
  3328. this._onPointerLockChange = function () {
  3329. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3330. };
  3331. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3332. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3333. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3334. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3335. this._audioEngine = new BABYLON.AudioEngine();
  3336. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3337. }
  3338. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3339. get: function () {
  3340. return Engine._ALPHA_DISABLE;
  3341. },
  3342. enumerable: true,
  3343. configurable: true
  3344. });
  3345. Object.defineProperty(Engine, "ALPHA_ADD", {
  3346. get: function () {
  3347. return Engine._ALPHA_ADD;
  3348. },
  3349. enumerable: true,
  3350. configurable: true
  3351. });
  3352. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3353. get: function () {
  3354. return Engine._ALPHA_COMBINE;
  3355. },
  3356. enumerable: true,
  3357. configurable: true
  3358. });
  3359. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3360. get: function () {
  3361. return Engine._DELAYLOADSTATE_NONE;
  3362. },
  3363. enumerable: true,
  3364. configurable: true
  3365. });
  3366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3367. get: function () {
  3368. return Engine._DELAYLOADSTATE_LOADED;
  3369. },
  3370. enumerable: true,
  3371. configurable: true
  3372. });
  3373. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3374. get: function () {
  3375. return Engine._DELAYLOADSTATE_LOADING;
  3376. },
  3377. enumerable: true,
  3378. configurable: true
  3379. });
  3380. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3381. get: function () {
  3382. return Engine._DELAYLOADSTATE_NOTLOADED;
  3383. },
  3384. enumerable: true,
  3385. configurable: true
  3386. });
  3387. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3388. get: function () {
  3389. return Engine._TEXTUREFORMAT_ALPHA;
  3390. },
  3391. enumerable: true,
  3392. configurable: true
  3393. });
  3394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3395. get: function () {
  3396. return Engine._TEXTUREFORMAT_LUMINANCE;
  3397. },
  3398. enumerable: true,
  3399. configurable: true
  3400. });
  3401. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3402. get: function () {
  3403. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3404. },
  3405. enumerable: true,
  3406. configurable: true
  3407. });
  3408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3409. get: function () {
  3410. return Engine._TEXTUREFORMAT_RGB;
  3411. },
  3412. enumerable: true,
  3413. configurable: true
  3414. });
  3415. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3416. get: function () {
  3417. return Engine._TEXTUREFORMAT_RGBA;
  3418. },
  3419. enumerable: true,
  3420. configurable: true
  3421. });
  3422. Object.defineProperty(Engine, "Version", {
  3423. get: function () {
  3424. return "2.0.0";
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Engine.prototype.getAudioEngine = function () {
  3430. return this._audioEngine;
  3431. };
  3432. Engine.prototype.getAspectRatio = function (camera) {
  3433. var viewport = camera.viewport;
  3434. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3435. };
  3436. Engine.prototype.getRenderWidth = function () {
  3437. if (this._currentRenderTarget) {
  3438. return this._currentRenderTarget._width;
  3439. }
  3440. return this._renderingCanvas.width;
  3441. };
  3442. Engine.prototype.getRenderHeight = function () {
  3443. if (this._currentRenderTarget) {
  3444. return this._currentRenderTarget._height;
  3445. }
  3446. return this._renderingCanvas.height;
  3447. };
  3448. Engine.prototype.getRenderingCanvas = function () {
  3449. return this._renderingCanvas;
  3450. };
  3451. Engine.prototype.getRenderingCanvasClientRect = function () {
  3452. return this._renderingCanvas.getBoundingClientRect();
  3453. };
  3454. Engine.prototype.setHardwareScalingLevel = function (level) {
  3455. this._hardwareScalingLevel = level;
  3456. this.resize();
  3457. };
  3458. Engine.prototype.getHardwareScalingLevel = function () {
  3459. return this._hardwareScalingLevel;
  3460. };
  3461. Engine.prototype.getLoadedTexturesCache = function () {
  3462. return this._loadedTexturesCache;
  3463. };
  3464. Engine.prototype.getCaps = function () {
  3465. return this._caps;
  3466. };
  3467. Object.defineProperty(Engine.prototype, "drawCalls", {
  3468. get: function () {
  3469. return this._drawCalls;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. // Methods
  3475. Engine.prototype.resetDrawCalls = function () {
  3476. this._drawCalls = 0;
  3477. };
  3478. Engine.prototype.setDepthFunctionToGreater = function () {
  3479. this._depthCullingState.depthFunc = this._gl.GREATER;
  3480. };
  3481. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3482. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3483. };
  3484. Engine.prototype.setDepthFunctionToLess = function () {
  3485. this._depthCullingState.depthFunc = this._gl.LESS;
  3486. };
  3487. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3488. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3489. };
  3490. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3491. if (!renderFunction) {
  3492. this._activeRenderLoops = [];
  3493. return;
  3494. }
  3495. var index = this._activeRenderLoops.indexOf(renderFunction);
  3496. if (index >= 0) {
  3497. this._activeRenderLoops.splice(index, 1);
  3498. }
  3499. };
  3500. Engine.prototype._renderLoop = function () {
  3501. var _this = this;
  3502. var shouldRender = true;
  3503. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3504. shouldRender = false;
  3505. }
  3506. if (shouldRender) {
  3507. // Start new frame
  3508. this.beginFrame();
  3509. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3510. var renderFunction = this._activeRenderLoops[index];
  3511. renderFunction();
  3512. }
  3513. // Present
  3514. this.endFrame();
  3515. }
  3516. if (this._activeRenderLoops.length > 0) {
  3517. // Register new frame
  3518. BABYLON.Tools.QueueNewFrame(function () {
  3519. _this._renderLoop();
  3520. });
  3521. } else {
  3522. this._renderingQueueLaunched = false;
  3523. }
  3524. };
  3525. Engine.prototype.runRenderLoop = function (renderFunction) {
  3526. var _this = this;
  3527. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3528. return;
  3529. }
  3530. this._activeRenderLoops.push(renderFunction);
  3531. if (!this._renderingQueueLaunched) {
  3532. this._renderingQueueLaunched = true;
  3533. BABYLON.Tools.QueueNewFrame(function () {
  3534. _this._renderLoop();
  3535. });
  3536. }
  3537. };
  3538. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3539. if (this.isFullscreen) {
  3540. BABYLON.Tools.ExitFullscreen();
  3541. } else {
  3542. this._pointerLockRequested = requestPointerLock;
  3543. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3544. }
  3545. };
  3546. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3547. this.applyStates();
  3548. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3549. if (this._depthCullingState.depthMask) {
  3550. this._gl.clearDepth(1.0);
  3551. }
  3552. var mode = 0;
  3553. if (backBuffer)
  3554. mode |= this._gl.COLOR_BUFFER_BIT;
  3555. if (depthStencil && this._depthCullingState.depthMask)
  3556. mode |= this._gl.DEPTH_BUFFER_BIT;
  3557. this._gl.clear(mode);
  3558. };
  3559. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3560. var width = requiredWidth || this._renderingCanvas.width;
  3561. var height = requiredHeight || this._renderingCanvas.height;
  3562. var x = viewport.x || 0;
  3563. var y = viewport.y || 0;
  3564. this._cachedViewport = viewport;
  3565. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3566. };
  3567. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3568. this._cachedViewport = null;
  3569. this._gl.viewport(x, y, width, height);
  3570. };
  3571. Engine.prototype.beginFrame = function () {
  3572. this._measureFps();
  3573. };
  3574. Engine.prototype.endFrame = function () {
  3575. this.flushFramebuffer();
  3576. };
  3577. Engine.prototype.resize = function () {
  3578. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3579. };
  3580. Engine.prototype.setSize = function (width, height) {
  3581. this._renderingCanvas.width = width;
  3582. this._renderingCanvas.height = height;
  3583. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3584. };
  3585. Engine.prototype.bindFramebuffer = function (texture) {
  3586. this._currentRenderTarget = texture;
  3587. var gl = this._gl;
  3588. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3589. this._gl.viewport(0, 0, texture._width, texture._height);
  3590. this.wipeCaches();
  3591. };
  3592. Engine.prototype.unBindFramebuffer = function (texture) {
  3593. this._currentRenderTarget = null;
  3594. if (texture.generateMipMaps) {
  3595. var gl = this._gl;
  3596. gl.bindTexture(gl.TEXTURE_2D, texture);
  3597. gl.generateMipmap(gl.TEXTURE_2D);
  3598. gl.bindTexture(gl.TEXTURE_2D, null);
  3599. }
  3600. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3601. };
  3602. Engine.prototype.flushFramebuffer = function () {
  3603. // this._gl.flush();
  3604. };
  3605. Engine.prototype.restoreDefaultFramebuffer = function () {
  3606. this._currentRenderTarget = null;
  3607. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3608. this.setViewport(this._cachedViewport);
  3609. this.wipeCaches();
  3610. };
  3611. // VBOs
  3612. Engine.prototype._resetVertexBufferBinding = function () {
  3613. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3614. this._cachedVertexBuffers = null;
  3615. };
  3616. Engine.prototype.createVertexBuffer = function (vertices) {
  3617. var vbo = this._gl.createBuffer();
  3618. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3619. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3620. this._resetVertexBufferBinding();
  3621. vbo.references = 1;
  3622. return vbo;
  3623. };
  3624. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3625. var vbo = this._gl.createBuffer();
  3626. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3627. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3628. this._resetVertexBufferBinding();
  3629. vbo.references = 1;
  3630. return vbo;
  3631. };
  3632. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3633. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3634. if (offset === undefined) {
  3635. offset = 0;
  3636. }
  3637. if (vertices instanceof Float32Array) {
  3638. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3639. } else {
  3640. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3641. }
  3642. this._resetVertexBufferBinding();
  3643. };
  3644. Engine.prototype._resetIndexBufferBinding = function () {
  3645. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3646. this._cachedIndexBuffer = null;
  3647. };
  3648. Engine.prototype.createIndexBuffer = function (indices) {
  3649. var vbo = this._gl.createBuffer();
  3650. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3651. // Check for 32 bits indices
  3652. var arrayBuffer;
  3653. var need32Bits = false;
  3654. if (this._caps.uintIndices) {
  3655. for (var index = 0; index < indices.length; index++) {
  3656. if (indices[index] > 65535) {
  3657. need32Bits = true;
  3658. break;
  3659. }
  3660. }
  3661. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3662. } else {
  3663. arrayBuffer = new Uint16Array(indices);
  3664. }
  3665. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3666. this._resetIndexBufferBinding();
  3667. vbo.references = 1;
  3668. vbo.is32Bits = need32Bits;
  3669. return vbo;
  3670. };
  3671. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3672. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3673. this._cachedVertexBuffers = vertexBuffer;
  3674. this._cachedEffectForVertexBuffers = effect;
  3675. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3676. var offset = 0;
  3677. for (var index = 0; index < vertexDeclaration.length; index++) {
  3678. var order = effect.getAttributeLocation(index);
  3679. if (order >= 0) {
  3680. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3681. }
  3682. offset += vertexDeclaration[index] * 4;
  3683. }
  3684. }
  3685. if (this._cachedIndexBuffer !== indexBuffer) {
  3686. this._cachedIndexBuffer = indexBuffer;
  3687. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3688. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3689. }
  3690. };
  3691. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3692. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3693. this._cachedVertexBuffers = vertexBuffers;
  3694. this._cachedEffectForVertexBuffers = effect;
  3695. var attributes = effect.getAttributesNames();
  3696. for (var index = 0; index < attributes.length; index++) {
  3697. var order = effect.getAttributeLocation(index);
  3698. if (order >= 0) {
  3699. var vertexBuffer = vertexBuffers[attributes[index]];
  3700. if (!vertexBuffer) {
  3701. continue;
  3702. }
  3703. var stride = vertexBuffer.getStrideSize();
  3704. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3705. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3706. }
  3707. }
  3708. }
  3709. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3710. this._cachedIndexBuffer = indexBuffer;
  3711. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3712. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3713. }
  3714. };
  3715. Engine.prototype._releaseBuffer = function (buffer) {
  3716. buffer.references--;
  3717. if (buffer.references === 0) {
  3718. this._gl.deleteBuffer(buffer);
  3719. return true;
  3720. }
  3721. return false;
  3722. };
  3723. Engine.prototype.createInstancesBuffer = function (capacity) {
  3724. var buffer = this._gl.createBuffer();
  3725. buffer.capacity = capacity;
  3726. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3727. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3728. return buffer;
  3729. };
  3730. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3731. this._gl.deleteBuffer(buffer);
  3732. };
  3733. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3734. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3735. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3736. for (var index = 0; index < 4; index++) {
  3737. var offsetLocation = offsetLocations[index];
  3738. this._gl.enableVertexAttribArray(offsetLocation);
  3739. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3740. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3741. }
  3742. };
  3743. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3744. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3745. for (var index = 0; index < 4; index++) {
  3746. var offsetLocation = offsetLocations[index];
  3747. this._gl.disableVertexAttribArray(offsetLocation);
  3748. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3749. }
  3750. };
  3751. Engine.prototype.applyStates = function () {
  3752. this._depthCullingState.apply(this._gl);
  3753. this._alphaState.apply(this._gl);
  3754. };
  3755. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3756. // Apply states
  3757. this.applyStates();
  3758. this._drawCalls++;
  3759. // Render
  3760. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3761. if (instancesCount) {
  3762. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3763. return;
  3764. }
  3765. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3766. };
  3767. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3768. // Apply states
  3769. this.applyStates();
  3770. this._drawCalls++;
  3771. if (instancesCount) {
  3772. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3773. return;
  3774. }
  3775. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3776. };
  3777. // Shaders
  3778. Engine.prototype._releaseEffect = function (effect) {
  3779. if (this._compiledEffects[effect._key]) {
  3780. delete this._compiledEffects[effect._key];
  3781. if (effect.getProgram()) {
  3782. this._gl.deleteProgram(effect.getProgram());
  3783. }
  3784. }
  3785. };
  3786. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3787. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3788. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3789. var name = vertex + "+" + fragment + "@" + defines;
  3790. if (this._compiledEffects[name]) {
  3791. return this._compiledEffects[name];
  3792. }
  3793. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3794. effect._key = name;
  3795. this._compiledEffects[name] = effect;
  3796. return effect;
  3797. };
  3798. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3799. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3800. if (typeof samplers === "undefined") { samplers = []; }
  3801. if (typeof defines === "undefined") { defines = ""; }
  3802. return this.createEffect({
  3803. vertex: "particles",
  3804. fragmentElement: fragmentName
  3805. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3806. };
  3807. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3808. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3809. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3810. var shaderProgram = this._gl.createProgram();
  3811. this._gl.attachShader(shaderProgram, vertexShader);
  3812. this._gl.attachShader(shaderProgram, fragmentShader);
  3813. this._gl.linkProgram(shaderProgram);
  3814. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3815. if (!linked) {
  3816. var error = this._gl.getProgramInfoLog(shaderProgram);
  3817. if (error) {
  3818. throw new Error(error);
  3819. }
  3820. }
  3821. this._gl.deleteShader(vertexShader);
  3822. this._gl.deleteShader(fragmentShader);
  3823. return shaderProgram;
  3824. };
  3825. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3826. var results = [];
  3827. for (var index = 0; index < uniformsNames.length; index++) {
  3828. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3829. }
  3830. return results;
  3831. };
  3832. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3833. var results = [];
  3834. for (var index = 0; index < attributesNames.length; index++) {
  3835. try {
  3836. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3837. } catch (e) {
  3838. results.push(-1);
  3839. }
  3840. }
  3841. return results;
  3842. };
  3843. Engine.prototype.enableEffect = function (effect) {
  3844. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3845. if (effect && effect.onBind) {
  3846. effect.onBind(effect);
  3847. }
  3848. return;
  3849. }
  3850. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3851. // Use program
  3852. this._gl.useProgram(effect.getProgram());
  3853. for (var i in this._vertexAttribArrays) {
  3854. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3855. continue;
  3856. }
  3857. this._vertexAttribArrays[i] = false;
  3858. this._gl.disableVertexAttribArray(i);
  3859. }
  3860. var attributesCount = effect.getAttributesCount();
  3861. for (var index = 0; index < attributesCount; index++) {
  3862. // Attributes
  3863. var order = effect.getAttributeLocation(index);
  3864. if (order >= 0) {
  3865. this._vertexAttribArrays[order] = true;
  3866. this._gl.enableVertexAttribArray(order);
  3867. }
  3868. }
  3869. this._currentEffect = effect;
  3870. if (effect.onBind) {
  3871. effect.onBind(effect);
  3872. }
  3873. };
  3874. Engine.prototype.setArray = function (uniform, array) {
  3875. if (!uniform)
  3876. return;
  3877. this._gl.uniform1fv(uniform, array);
  3878. };
  3879. Engine.prototype.setMatrices = function (uniform, matrices) {
  3880. if (!uniform)
  3881. return;
  3882. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3883. };
  3884. Engine.prototype.setMatrix = function (uniform, matrix) {
  3885. if (!uniform)
  3886. return;
  3887. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3888. };
  3889. Engine.prototype.setFloat = function (uniform, value) {
  3890. if (!uniform)
  3891. return;
  3892. this._gl.uniform1f(uniform, value);
  3893. };
  3894. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3895. if (!uniform)
  3896. return;
  3897. this._gl.uniform2f(uniform, x, y);
  3898. };
  3899. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3900. if (!uniform)
  3901. return;
  3902. this._gl.uniform3f(uniform, x, y, z);
  3903. };
  3904. Engine.prototype.setBool = function (uniform, bool) {
  3905. if (!uniform)
  3906. return;
  3907. this._gl.uniform1i(uniform, bool);
  3908. };
  3909. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3910. if (!uniform)
  3911. return;
  3912. this._gl.uniform4f(uniform, x, y, z, w);
  3913. };
  3914. Engine.prototype.setColor3 = function (uniform, color3) {
  3915. if (!uniform)
  3916. return;
  3917. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3918. };
  3919. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3920. if (!uniform)
  3921. return;
  3922. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3923. };
  3924. // States
  3925. Engine.prototype.setState = function (culling, force) {
  3926. // Culling
  3927. if (this._depthCullingState.cull !== culling || force) {
  3928. if (culling) {
  3929. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3930. this._depthCullingState.cull = true;
  3931. } else {
  3932. this._depthCullingState.cull = false;
  3933. }
  3934. }
  3935. };
  3936. Engine.prototype.setDepthBuffer = function (enable) {
  3937. this._depthCullingState.depthTest = enable;
  3938. };
  3939. Engine.prototype.getDepthWrite = function () {
  3940. return this._depthCullingState.depthMask;
  3941. };
  3942. Engine.prototype.setDepthWrite = function (enable) {
  3943. this._depthCullingState.depthMask = enable;
  3944. };
  3945. Engine.prototype.setColorWrite = function (enable) {
  3946. this._gl.colorMask(enable, enable, enable, enable);
  3947. };
  3948. Engine.prototype.setAlphaMode = function (mode) {
  3949. switch (mode) {
  3950. case BABYLON.Engine.ALPHA_DISABLE:
  3951. this.setDepthWrite(true);
  3952. this._alphaState.alphaBlend = false;
  3953. break;
  3954. case BABYLON.Engine.ALPHA_COMBINE:
  3955. this.setDepthWrite(false);
  3956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3957. this._alphaState.alphaBlend = true;
  3958. break;
  3959. case BABYLON.Engine.ALPHA_ADD:
  3960. this.setDepthWrite(false);
  3961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3962. this._alphaState.alphaBlend = true;
  3963. break;
  3964. }
  3965. this._alphaMode = mode;
  3966. };
  3967. Engine.prototype.getAlphaMode = function () {
  3968. return this._alphaMode;
  3969. };
  3970. Engine.prototype.setAlphaTesting = function (enable) {
  3971. this._alphaTest = enable;
  3972. };
  3973. Engine.prototype.getAlphaTesting = function () {
  3974. return this._alphaTest;
  3975. };
  3976. // Textures
  3977. Engine.prototype.wipeCaches = function () {
  3978. this._activeTexturesCache = [];
  3979. this._currentEffect = null;
  3980. this._depthCullingState.reset();
  3981. this._alphaState.reset();
  3982. this._cachedVertexBuffers = null;
  3983. this._cachedIndexBuffer = null;
  3984. this._cachedEffectForVertexBuffers = null;
  3985. };
  3986. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3987. var gl = this._gl;
  3988. gl.bindTexture(gl.TEXTURE_2D, texture);
  3989. var magFilter = gl.NEAREST;
  3990. var minFilter = gl.NEAREST;
  3991. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3992. magFilter = gl.LINEAR;
  3993. minFilter = gl.LINEAR;
  3994. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3995. magFilter = gl.LINEAR;
  3996. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3997. }
  3998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4000. gl.bindTexture(gl.TEXTURE_2D, null);
  4001. texture.samplingMode = samplingMode;
  4002. };
  4003. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4004. var _this = this;
  4005. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4006. if (typeof onLoad === "undefined") { onLoad = null; }
  4007. if (typeof onError === "undefined") { onError = null; }
  4008. if (typeof buffer === "undefined") { buffer = null; }
  4009. var texture = this._gl.createTexture();
  4010. var extension;
  4011. var fromData = false;
  4012. if (url.substr(0, 5) === "data:") {
  4013. fromData = true;
  4014. }
  4015. if (!fromData)
  4016. extension = url.substr(url.length - 4, 4).toLowerCase();
  4017. else {
  4018. var oldUrl = url;
  4019. fromData = oldUrl.split(':');
  4020. url = oldUrl;
  4021. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4022. }
  4023. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4024. var isTGA = (extension === ".tga");
  4025. scene._addPendingData(texture);
  4026. texture.url = url;
  4027. texture.noMipmap = noMipmap;
  4028. texture.references = 1;
  4029. this._loadedTexturesCache.push(texture);
  4030. var onerror = function () {
  4031. scene._removePendingData(texture);
  4032. if (onError) {
  4033. onError();
  4034. }
  4035. };
  4036. if (isTGA) {
  4037. var callback = function (arrayBuffer) {
  4038. var data = new Uint8Array(arrayBuffer);
  4039. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4040. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4041. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4042. if (onLoad) {
  4043. onLoad();
  4044. }
  4045. }, samplingMode);
  4046. };
  4047. if (!(fromData instanceof Array))
  4048. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4049. callback(arrayBuffer);
  4050. }, onerror, scene.database, true);
  4051. else
  4052. callback(buffer);
  4053. } else if (isDDS) {
  4054. callback = function (data) {
  4055. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4056. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  4057. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4058. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4059. if (onLoad) {
  4060. onLoad();
  4061. }
  4062. }, samplingMode);
  4063. };
  4064. if (!(fromData instanceof Array))
  4065. BABYLON.Tools.LoadFile(url, function (data) {
  4066. callback(data);
  4067. }, onerror, scene.database, true);
  4068. else
  4069. callback(buffer);
  4070. } else {
  4071. var onload = function (img) {
  4072. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4073. var isPot = (img.width == potWidth && img.height == potHeight);
  4074. if (!isPot) {
  4075. _this._workingCanvas.width = potWidth;
  4076. _this._workingCanvas.height = potHeight;
  4077. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4078. }
  4079. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4080. if (onLoad) {
  4081. onLoad();
  4082. }
  4083. }, samplingMode);
  4084. };
  4085. if (!(fromData instanceof Array))
  4086. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4087. else
  4088. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4089. }
  4090. return texture;
  4091. };
  4092. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4093. var texture = this._gl.createTexture();
  4094. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4095. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4096. // Format
  4097. var internalFormat = this._gl.RGBA;
  4098. switch (format) {
  4099. case Engine.TEXTUREFORMAT_ALPHA:
  4100. internalFormat = this._gl.ALPHA;
  4101. break;
  4102. case Engine.TEXTUREFORMAT_LUMINANCE:
  4103. internalFormat = this._gl.LUMINANCE;
  4104. break;
  4105. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4106. internalFormat = this._gl.LUMINANCE_ALPHA;
  4107. break;
  4108. case Engine.TEXTUREFORMAT_RGB:
  4109. internalFormat = this._gl.RGB;
  4110. break;
  4111. case Engine.TEXTUREFORMAT_RGBA:
  4112. internalFormat = this._gl.RGBA;
  4113. break;
  4114. }
  4115. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4116. if (generateMipMaps) {
  4117. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4118. }
  4119. // Filters
  4120. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4121. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4122. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4123. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4124. this._activeTexturesCache = [];
  4125. texture._baseWidth = width;
  4126. texture._baseHeight = height;
  4127. texture._width = width;
  4128. texture._height = height;
  4129. texture.isReady = true;
  4130. texture.references = 1;
  4131. texture.samplingMode = samplingMode;
  4132. this._loadedTexturesCache.push(texture);
  4133. return texture;
  4134. };
  4135. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4136. var texture = this._gl.createTexture();
  4137. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4138. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4139. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4140. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4141. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4142. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4143. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4144. this._activeTexturesCache = [];
  4145. texture._baseWidth = width;
  4146. texture._baseHeight = height;
  4147. texture._width = width;
  4148. texture._height = height;
  4149. texture.isReady = false;
  4150. texture.generateMipMaps = generateMipMaps;
  4151. texture.references = 1;
  4152. texture.samplingMode = samplingMode;
  4153. this._loadedTexturesCache.push(texture);
  4154. return texture;
  4155. };
  4156. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4157. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4158. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4159. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4160. if (texture.generateMipMaps) {
  4161. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4162. }
  4163. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4164. this._activeTexturesCache = [];
  4165. texture.isReady = true;
  4166. };
  4167. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4168. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4169. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4170. // Scale the video if it is a NPOT using the current working canvas
  4171. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4172. if (!texture._workingCanvas) {
  4173. texture._workingCanvas = document.createElement("canvas");
  4174. texture._workingContext = texture._workingCanvas.getContext("2d");
  4175. texture._workingCanvas.width = texture._width;
  4176. texture._workingCanvas.height = texture._height;
  4177. }
  4178. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4179. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4180. } else {
  4181. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4182. }
  4183. if (texture.generateMipMaps) {
  4184. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4185. }
  4186. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4187. this._activeTexturesCache = [];
  4188. texture.isReady = true;
  4189. };
  4190. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4191. // old version had a "generateMipMaps" arg instead of options.
  4192. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4193. // in the same way, generateDepthBuffer is defaulted to true
  4194. var generateMipMaps = false;
  4195. var generateDepthBuffer = true;
  4196. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4197. if (options !== undefined) {
  4198. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4199. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4200. if (options.samplingMode !== undefined) {
  4201. samplingMode = options.samplingMode;
  4202. }
  4203. }
  4204. var gl = this._gl;
  4205. var texture = gl.createTexture();
  4206. gl.bindTexture(gl.TEXTURE_2D, texture);
  4207. var width = size.width || size;
  4208. var height = size.height || size;
  4209. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4214. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4215. var depthBuffer;
  4216. // Create the depth buffer
  4217. if (generateDepthBuffer) {
  4218. depthBuffer = gl.createRenderbuffer();
  4219. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4220. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4221. }
  4222. // Create the framebuffer
  4223. var framebuffer = gl.createFramebuffer();
  4224. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4225. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4226. if (generateDepthBuffer) {
  4227. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4228. }
  4229. // Unbind
  4230. gl.bindTexture(gl.TEXTURE_2D, null);
  4231. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4232. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4233. texture._framebuffer = framebuffer;
  4234. if (generateDepthBuffer) {
  4235. texture._depthBuffer = depthBuffer;
  4236. }
  4237. texture._width = width;
  4238. texture._height = height;
  4239. texture.isReady = true;
  4240. texture.generateMipMaps = generateMipMaps;
  4241. texture.references = 1;
  4242. texture.samplingMode = samplingMode;
  4243. this._activeTexturesCache = [];
  4244. this._loadedTexturesCache.push(texture);
  4245. return texture;
  4246. };
  4247. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4248. var _this = this;
  4249. var gl = this._gl;
  4250. var texture = gl.createTexture();
  4251. texture.isCube = true;
  4252. texture.url = rootUrl;
  4253. texture.references = 1;
  4254. this._loadedTexturesCache.push(texture);
  4255. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4256. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4257. if (isDDS) {
  4258. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4259. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4260. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4261. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4262. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4263. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4264. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4265. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4266. }
  4267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4271. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4272. _this._activeTexturesCache = [];
  4273. texture._width = info.width;
  4274. texture._height = info.height;
  4275. texture.isReady = true;
  4276. }, null, null, true);
  4277. } else {
  4278. cascadeLoad(rootUrl, scene, function (imgs) {
  4279. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4280. var height = width;
  4281. _this._workingCanvas.width = width;
  4282. _this._workingCanvas.height = height;
  4283. var faces = [
  4284. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4285. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4286. ];
  4287. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4288. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4289. for (var index = 0; index < faces.length; index++) {
  4290. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4291. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4292. }
  4293. if (!noMipmap) {
  4294. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4295. }
  4296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4300. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4301. _this._activeTexturesCache = [];
  4302. texture._width = width;
  4303. texture._height = height;
  4304. texture.isReady = true;
  4305. }, extensions);
  4306. }
  4307. return texture;
  4308. };
  4309. Engine.prototype._releaseTexture = function (texture) {
  4310. var gl = this._gl;
  4311. if (texture._framebuffer) {
  4312. gl.deleteFramebuffer(texture._framebuffer);
  4313. }
  4314. if (texture._depthBuffer) {
  4315. gl.deleteRenderbuffer(texture._depthBuffer);
  4316. }
  4317. gl.deleteTexture(texture);
  4318. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4319. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4320. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4321. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4322. this._activeTexturesCache[channel] = null;
  4323. }
  4324. var index = this._loadedTexturesCache.indexOf(texture);
  4325. if (index !== -1) {
  4326. this._loadedTexturesCache.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype.bindSamplers = function (effect) {
  4330. this._gl.useProgram(effect.getProgram());
  4331. var samplers = effect.getSamplers();
  4332. for (var index = 0; index < samplers.length; index++) {
  4333. var uniform = effect.getUniform(samplers[index]);
  4334. this._gl.uniform1i(uniform, index);
  4335. }
  4336. this._currentEffect = null;
  4337. };
  4338. Engine.prototype._bindTexture = function (channel, texture) {
  4339. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4340. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4341. this._activeTexturesCache[channel] = null;
  4342. };
  4343. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4344. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4345. };
  4346. Engine.prototype.setTexture = function (channel, texture) {
  4347. if (channel < 0) {
  4348. return;
  4349. }
  4350. // Not ready?
  4351. if (!texture || !texture.isReady()) {
  4352. if (this._activeTexturesCache[channel] != null) {
  4353. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4354. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4355. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4356. this._activeTexturesCache[channel] = null;
  4357. }
  4358. return;
  4359. }
  4360. // Video
  4361. if (texture instanceof BABYLON.VideoTexture) {
  4362. if (texture.update()) {
  4363. this._activeTexturesCache[channel] = null;
  4364. }
  4365. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4366. texture.delayLoad();
  4367. return;
  4368. }
  4369. if (this._activeTexturesCache[channel] == texture) {
  4370. return;
  4371. }
  4372. this._activeTexturesCache[channel] = texture;
  4373. var internalTexture = texture.getInternalTexture();
  4374. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4375. if (internalTexture.isCube) {
  4376. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4377. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4378. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4379. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4380. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4381. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4383. }
  4384. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4385. } else {
  4386. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4387. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4388. internalTexture._cachedWrapU = texture.wrapU;
  4389. switch (texture.wrapU) {
  4390. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4391. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4392. break;
  4393. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4394. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4395. break;
  4396. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4398. break;
  4399. }
  4400. }
  4401. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4402. internalTexture._cachedWrapV = texture.wrapV;
  4403. switch (texture.wrapV) {
  4404. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4406. break;
  4407. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4408. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4409. break;
  4410. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4411. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4412. break;
  4413. }
  4414. }
  4415. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4416. }
  4417. };
  4418. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4419. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4420. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4421. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4422. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4423. }
  4424. };
  4425. Engine.prototype.readPixels = function (x, y, width, height) {
  4426. var data = new Uint8Array(height * width * 4);
  4427. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4428. return data;
  4429. };
  4430. // Dispose
  4431. Engine.prototype.dispose = function () {
  4432. this.hideLoadingUI();
  4433. this.stopRenderLoop();
  4434. while (this.scenes.length) {
  4435. this.scenes[0].dispose();
  4436. }
  4437. for (var name in this._compiledEffects) {
  4438. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4439. }
  4440. for (var i in this._vertexAttribArrays) {
  4441. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4442. continue;
  4443. }
  4444. this._gl.disableVertexAttribArray(i);
  4445. }
  4446. // Events
  4447. window.removeEventListener("blur", this._onBlur);
  4448. window.removeEventListener("focus", this._onFocus);
  4449. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4450. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4451. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4452. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4453. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4454. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4455. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4456. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4457. };
  4458. // Loading screen
  4459. Engine.prototype.displayLoadingUI = function () {
  4460. var _this = this;
  4461. this._loadingDiv = document.createElement("div");
  4462. this._loadingDiv.style.opacity = "0";
  4463. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4464. // Loading text
  4465. this._loadingTextDiv = document.createElement("div");
  4466. this._loadingTextDiv.style.position = "absolute";
  4467. this._loadingTextDiv.style.left = "0";
  4468. this._loadingTextDiv.style.top = "50%";
  4469. this._loadingTextDiv.style.marginTop = "80px";
  4470. this._loadingTextDiv.style.width = "100%";
  4471. this._loadingTextDiv.style.height = "20px";
  4472. this._loadingTextDiv.style.fontFamily = "Arial";
  4473. this._loadingTextDiv.style.fontSize = "14px";
  4474. this._loadingTextDiv.style.color = "white";
  4475. this._loadingTextDiv.style.textAlign = "center";
  4476. this._loadingTextDiv.innerHTML = "Loading";
  4477. this._loadingDiv.appendChild(this._loadingTextDiv);
  4478. // Loading img
  4479. var imgBack = new Image();
  4480. 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==";
  4481. imgBack.style.position = "absolute";
  4482. imgBack.style.left = "50%";
  4483. imgBack.style.top = "50%";
  4484. imgBack.style.marginLeft = "-50px";
  4485. imgBack.style.marginTop = "-50px";
  4486. imgBack.style.transition = "transform 1.0s ease";
  4487. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4488. var deg = 360;
  4489. var onTransitionEnd = function () {
  4490. deg += 360;
  4491. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4492. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4493. };
  4494. imgBack.addEventListener("transitionend", onTransitionEnd);
  4495. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4496. this._loadingDiv.appendChild(imgBack);
  4497. // front image
  4498. var imgFront = new Image();
  4499. 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=";
  4500. imgFront.style.position = "absolute";
  4501. imgFront.style.left = "50%";
  4502. imgFront.style.top = "50%";
  4503. imgFront.style.marginLeft = "-50px";
  4504. imgFront.style.marginTop = "-50px";
  4505. this._loadingDiv.appendChild(imgFront);
  4506. // Resize
  4507. this._resizeLoadingUI = function () {
  4508. var canvasRect = _this.getRenderingCanvasClientRect();
  4509. _this._loadingDiv.style.position = "absolute";
  4510. _this._loadingDiv.style.left = canvasRect.left + "px";
  4511. _this._loadingDiv.style.top = canvasRect.top + "px";
  4512. _this._loadingDiv.style.width = canvasRect.width + "px";
  4513. _this._loadingDiv.style.height = canvasRect.height + "px";
  4514. };
  4515. this._resizeLoadingUI();
  4516. window.addEventListener("resize", this._resizeLoadingUI);
  4517. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4518. document.body.appendChild(this._loadingDiv);
  4519. setTimeout(function () {
  4520. _this._loadingDiv.style.opacity = "1";
  4521. imgBack.style.transform = "rotateZ(360deg)";
  4522. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4523. }, 0);
  4524. };
  4525. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4526. set: function (text) {
  4527. if (!this._loadingDiv) {
  4528. return;
  4529. }
  4530. this._loadingTextDiv.innerHTML = text;
  4531. },
  4532. enumerable: true,
  4533. configurable: true
  4534. });
  4535. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4536. get: function () {
  4537. return this._loadingDivBackgroundColor;
  4538. },
  4539. set: function (color) {
  4540. this._loadingDivBackgroundColor = color;
  4541. if (!this._loadingDiv) {
  4542. return;
  4543. }
  4544. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4545. },
  4546. enumerable: true,
  4547. configurable: true
  4548. });
  4549. Engine.prototype.hideLoadingUI = function () {
  4550. var _this = this;
  4551. if (!this._loadingDiv) {
  4552. return;
  4553. }
  4554. var onTransitionEnd = function () {
  4555. if (!_this._loadingDiv) {
  4556. return;
  4557. }
  4558. document.body.removeChild(_this._loadingDiv);
  4559. window.removeEventListener("resize", _this._resizeLoadingUI);
  4560. _this._loadingDiv = null;
  4561. };
  4562. this._loadingDiv.style.opacity = "0";
  4563. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4564. };
  4565. // FPS
  4566. Engine.prototype.getFps = function () {
  4567. return this.fps;
  4568. };
  4569. Engine.prototype.getDeltaTime = function () {
  4570. return this.deltaTime;
  4571. };
  4572. Engine.prototype._measureFps = function () {
  4573. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4574. var length = this.previousFramesDuration.length;
  4575. if (length >= 2) {
  4576. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4577. }
  4578. if (length >= this.fpsRange) {
  4579. if (length > this.fpsRange) {
  4580. this.previousFramesDuration.splice(0, 1);
  4581. length = this.previousFramesDuration.length;
  4582. }
  4583. var sum = 0;
  4584. for (var id = 0; id < length - 1; id++) {
  4585. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4586. }
  4587. this.fps = 1000.0 / (sum / (length - 1));
  4588. }
  4589. };
  4590. // Statics
  4591. Engine.isSupported = function () {
  4592. try {
  4593. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4594. if (navigator.isCocoonJS) {
  4595. return true;
  4596. }
  4597. var tempcanvas = document.createElement("canvas");
  4598. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4599. return gl != null && !!window.WebGLRenderingContext;
  4600. } catch (e) {
  4601. return false;
  4602. }
  4603. };
  4604. Engine._ALPHA_DISABLE = 0;
  4605. Engine._ALPHA_ADD = 1;
  4606. Engine._ALPHA_COMBINE = 2;
  4607. Engine._DELAYLOADSTATE_NONE = 0;
  4608. Engine._DELAYLOADSTATE_LOADED = 1;
  4609. Engine._DELAYLOADSTATE_LOADING = 2;
  4610. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4611. Engine._TEXTUREFORMAT_ALPHA = 0;
  4612. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4613. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4614. Engine._TEXTUREFORMAT_RGB = 4;
  4615. Engine._TEXTUREFORMAT_RGBA = 4;
  4616. Engine.Epsilon = 0.001;
  4617. Engine.CollisionsEpsilon = 0.001;
  4618. Engine.ShadersRepository = "Babylon/Shaders/";
  4619. return Engine;
  4620. })();
  4621. BABYLON.Engine = Engine;
  4622. })(BABYLON || (BABYLON = {}));
  4623. //# sourceMappingURL=babylon.engine.js.map
  4624. var BABYLON;
  4625. (function (BABYLON) {
  4626. var Node = (function () {
  4627. function Node(name, scene) {
  4628. this.state = "";
  4629. this.animations = new Array();
  4630. this._childrenFlag = -1;
  4631. this._isEnabled = true;
  4632. this._isReady = true;
  4633. this._currentRenderId = -1;
  4634. this.name = name;
  4635. this.id = name;
  4636. this._scene = scene;
  4637. this._initCache();
  4638. }
  4639. Node.prototype.getScene = function () {
  4640. return this._scene;
  4641. };
  4642. Node.prototype.getEngine = function () {
  4643. return this._scene.getEngine();
  4644. };
  4645. // override it in derived class
  4646. Node.prototype.getWorldMatrix = function () {
  4647. return BABYLON.Matrix.Identity();
  4648. };
  4649. // override it in derived class if you add new variables to the cache
  4650. // and call the parent class method
  4651. Node.prototype._initCache = function () {
  4652. this._cache = {};
  4653. this._cache.parent = undefined;
  4654. };
  4655. Node.prototype.updateCache = function (force) {
  4656. if (!force && this.isSynchronized())
  4657. return;
  4658. this._cache.parent = this.parent;
  4659. this._updateCache();
  4660. };
  4661. // override it in derived class if you add new variables to the cache
  4662. // and call the parent class method if !ignoreParentClass
  4663. Node.prototype._updateCache = function (ignoreParentClass) {
  4664. };
  4665. // override it in derived class if you add new variables to the cache
  4666. Node.prototype._isSynchronized = function () {
  4667. return true;
  4668. };
  4669. Node.prototype.isSynchronizedWithParent = function () {
  4670. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4671. };
  4672. Node.prototype.isSynchronized = function (updateCache) {
  4673. var check = this.hasNewParent();
  4674. check = check || !this.isSynchronizedWithParent();
  4675. check = check || !this._isSynchronized();
  4676. if (updateCache)
  4677. this.updateCache(true);
  4678. return !check;
  4679. };
  4680. Node.prototype.hasNewParent = function (update) {
  4681. if (this._cache.parent === this.parent)
  4682. return false;
  4683. if (update)
  4684. this._cache.parent = this.parent;
  4685. return true;
  4686. };
  4687. Node.prototype.isReady = function () {
  4688. return this._isReady;
  4689. };
  4690. Node.prototype.isEnabled = function () {
  4691. if (!this._isEnabled) {
  4692. return false;
  4693. }
  4694. if (this.parent) {
  4695. return this.parent.isEnabled();
  4696. }
  4697. return true;
  4698. };
  4699. Node.prototype.setEnabled = function (value) {
  4700. this._isEnabled = value;
  4701. };
  4702. Node.prototype.isDescendantOf = function (ancestor) {
  4703. if (this.parent) {
  4704. if (this.parent === ancestor) {
  4705. return true;
  4706. }
  4707. return this.parent.isDescendantOf(ancestor);
  4708. }
  4709. return false;
  4710. };
  4711. Node.prototype._getDescendants = function (list, results) {
  4712. for (var index = 0; index < list.length; index++) {
  4713. var item = list[index];
  4714. if (item.isDescendantOf(this)) {
  4715. results.push(item);
  4716. }
  4717. }
  4718. };
  4719. Node.prototype.getDescendants = function () {
  4720. var results = [];
  4721. this._getDescendants(this._scene.meshes, results);
  4722. this._getDescendants(this._scene.lights, results);
  4723. this._getDescendants(this._scene.cameras, results);
  4724. return results;
  4725. };
  4726. Node.prototype._setReady = function (state) {
  4727. if (state == this._isReady) {
  4728. return;
  4729. }
  4730. if (!state) {
  4731. this._isReady = false;
  4732. return;
  4733. }
  4734. this._isReady = true;
  4735. if (this.onReady) {
  4736. this.onReady(this);
  4737. }
  4738. };
  4739. return Node;
  4740. })();
  4741. BABYLON.Node = Node;
  4742. })(BABYLON || (BABYLON = {}));
  4743. //# sourceMappingURL=babylon.node.js.map
  4744. var BABYLON;
  4745. (function (BABYLON) {
  4746. var BoundingSphere = (function () {
  4747. function BoundingSphere(minimum, maximum) {
  4748. this.minimum = minimum;
  4749. this.maximum = maximum;
  4750. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4751. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4752. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4753. this.radius = distance * 0.5;
  4754. this.centerWorld = BABYLON.Vector3.Zero();
  4755. this._update(BABYLON.Matrix.Identity());
  4756. }
  4757. // Methods
  4758. BoundingSphere.prototype._update = function (world) {
  4759. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4760. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4761. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4762. };
  4763. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4764. for (var i = 0; i < 6; i++) {
  4765. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4766. return false;
  4767. }
  4768. return true;
  4769. };
  4770. BoundingSphere.prototype.intersectsPoint = function (point) {
  4771. var x = this.centerWorld.x - point.x;
  4772. var y = this.centerWorld.y - point.y;
  4773. var z = this.centerWorld.z - point.z;
  4774. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4775. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4776. return false;
  4777. return true;
  4778. };
  4779. // Statics
  4780. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4781. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4782. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4783. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4784. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4785. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4786. return false;
  4787. return true;
  4788. };
  4789. return BoundingSphere;
  4790. })();
  4791. BABYLON.BoundingSphere = BoundingSphere;
  4792. })(BABYLON || (BABYLON = {}));
  4793. //# sourceMappingURL=babylon.boundingSphere.js.map
  4794. var BABYLON;
  4795. (function (BABYLON) {
  4796. var BoundingBox = (function () {
  4797. function BoundingBox(minimum, maximum) {
  4798. this.minimum = minimum;
  4799. this.maximum = maximum;
  4800. this.vectors = new Array();
  4801. this.vectorsWorld = new Array();
  4802. // Bounding vectors
  4803. this.vectors.push(this.minimum.clone());
  4804. this.vectors.push(this.maximum.clone());
  4805. this.vectors.push(this.minimum.clone());
  4806. this.vectors[2].x = this.maximum.x;
  4807. this.vectors.push(this.minimum.clone());
  4808. this.vectors[3].y = this.maximum.y;
  4809. this.vectors.push(this.minimum.clone());
  4810. this.vectors[4].z = this.maximum.z;
  4811. this.vectors.push(this.maximum.clone());
  4812. this.vectors[5].z = this.minimum.z;
  4813. this.vectors.push(this.maximum.clone());
  4814. this.vectors[6].x = this.minimum.x;
  4815. this.vectors.push(this.maximum.clone());
  4816. this.vectors[7].y = this.minimum.y;
  4817. // OBB
  4818. this.center = this.maximum.add(this.minimum).scale(0.5);
  4819. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4820. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4821. for (var index = 0; index < this.vectors.length; index++) {
  4822. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4823. }
  4824. this.minimumWorld = BABYLON.Vector3.Zero();
  4825. this.maximumWorld = BABYLON.Vector3.Zero();
  4826. this._update(BABYLON.Matrix.Identity());
  4827. }
  4828. // Methods
  4829. BoundingBox.prototype.getWorldMatrix = function () {
  4830. return this._worldMatrix;
  4831. };
  4832. BoundingBox.prototype._update = function (world) {
  4833. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4834. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4835. for (var index = 0; index < this.vectors.length; index++) {
  4836. var v = this.vectorsWorld[index];
  4837. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4838. if (v.x < this.minimumWorld.x)
  4839. this.minimumWorld.x = v.x;
  4840. if (v.y < this.minimumWorld.y)
  4841. this.minimumWorld.y = v.y;
  4842. if (v.z < this.minimumWorld.z)
  4843. this.minimumWorld.z = v.z;
  4844. if (v.x > this.maximumWorld.x)
  4845. this.maximumWorld.x = v.x;
  4846. if (v.y > this.maximumWorld.y)
  4847. this.maximumWorld.y = v.y;
  4848. if (v.z > this.maximumWorld.z)
  4849. this.maximumWorld.z = v.z;
  4850. }
  4851. // OBB
  4852. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4853. this.center.scaleInPlace(0.5);
  4854. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4855. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4856. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4857. this._worldMatrix = world;
  4858. };
  4859. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4860. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4861. };
  4862. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4863. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4864. };
  4865. BoundingBox.prototype.intersectsPoint = function (point) {
  4866. var delta = BABYLON.Engine.Epsilon;
  4867. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4868. return false;
  4869. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4870. return false;
  4871. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4872. return false;
  4873. return true;
  4874. };
  4875. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4876. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4877. };
  4878. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4879. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4880. return false;
  4881. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4882. return false;
  4883. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4884. return false;
  4885. return true;
  4886. };
  4887. // Statics
  4888. BoundingBox.Intersects = function (box0, box1) {
  4889. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4890. return false;
  4891. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4892. return false;
  4893. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4894. return false;
  4895. return true;
  4896. };
  4897. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4898. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4899. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4900. return (num <= (sphereRadius * sphereRadius));
  4901. };
  4902. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4903. for (var p = 0; p < 6; p++) {
  4904. for (var i = 0; i < 8; i++) {
  4905. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4906. return false;
  4907. }
  4908. }
  4909. }
  4910. return true;
  4911. };
  4912. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4913. for (var p = 0; p < 6; p++) {
  4914. var inCount = 8;
  4915. for (var i = 0; i < 8; i++) {
  4916. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4917. --inCount;
  4918. } else {
  4919. break;
  4920. }
  4921. }
  4922. if (inCount == 0)
  4923. return false;
  4924. }
  4925. return true;
  4926. };
  4927. return BoundingBox;
  4928. })();
  4929. BABYLON.BoundingBox = BoundingBox;
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.boundingBox.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var computeBoxExtents = function (axis, box) {
  4935. var p = BABYLON.Vector3.Dot(box.center, axis);
  4936. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4937. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4938. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4939. var r = r0 + r1 + r2;
  4940. return {
  4941. min: p - r,
  4942. max: p + r
  4943. };
  4944. };
  4945. var extentsOverlap = function (min0, max0, min1, max1) {
  4946. return !(min0 > max1 || min1 > max0);
  4947. };
  4948. var axisOverlap = function (axis, box0, box1) {
  4949. var result0 = computeBoxExtents(axis, box0);
  4950. var result1 = computeBoxExtents(axis, box1);
  4951. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4952. };
  4953. var BoundingInfo = (function () {
  4954. function BoundingInfo(minimum, maximum) {
  4955. this.minimum = minimum;
  4956. this.maximum = maximum;
  4957. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4958. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4959. }
  4960. // Methods
  4961. BoundingInfo.prototype._update = function (world) {
  4962. this.boundingBox._update(world);
  4963. this.boundingSphere._update(world);
  4964. };
  4965. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4966. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4967. return false;
  4968. return this.boundingBox.isInFrustum(frustumPlanes);
  4969. };
  4970. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4971. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4972. };
  4973. BoundingInfo.prototype._checkCollision = function (collider) {
  4974. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4975. };
  4976. BoundingInfo.prototype.intersectsPoint = function (point) {
  4977. if (!this.boundingSphere.centerWorld) {
  4978. return false;
  4979. }
  4980. if (!this.boundingSphere.intersectsPoint(point)) {
  4981. return false;
  4982. }
  4983. if (!this.boundingBox.intersectsPoint(point)) {
  4984. return false;
  4985. }
  4986. return true;
  4987. };
  4988. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4989. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4990. return false;
  4991. }
  4992. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4993. return false;
  4994. }
  4995. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4996. return false;
  4997. }
  4998. if (!precise) {
  4999. return true;
  5000. }
  5001. var box0 = this.boundingBox;
  5002. var box1 = boundingInfo.boundingBox;
  5003. if (!axisOverlap(box0.directions[0], box0, box1))
  5004. return false;
  5005. if (!axisOverlap(box0.directions[1], box0, box1))
  5006. return false;
  5007. if (!axisOverlap(box0.directions[2], box0, box1))
  5008. return false;
  5009. if (!axisOverlap(box1.directions[0], box0, box1))
  5010. return false;
  5011. if (!axisOverlap(box1.directions[1], box0, box1))
  5012. return false;
  5013. if (!axisOverlap(box1.directions[2], box0, box1))
  5014. return false;
  5015. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5016. return false;
  5017. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5018. return false;
  5019. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5020. return false;
  5021. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5022. return false;
  5023. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5024. return false;
  5025. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5026. return false;
  5027. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5028. return false;
  5029. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5030. return false;
  5031. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5032. return false;
  5033. return true;
  5034. };
  5035. return BoundingInfo;
  5036. })();
  5037. BABYLON.BoundingInfo = BoundingInfo;
  5038. })(BABYLON || (BABYLON = {}));
  5039. //# sourceMappingURL=babylon.boundingInfo.js.map
  5040. var BABYLON;
  5041. (function (BABYLON) {
  5042. var Light = (function (_super) {
  5043. __extends(Light, _super);
  5044. function Light(name, scene) {
  5045. _super.call(this, name, scene);
  5046. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5047. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5048. this.intensity = 1.0;
  5049. this.range = Number.MAX_VALUE;
  5050. this.includedOnlyMeshes = new Array();
  5051. this.excludedMeshes = new Array();
  5052. this._excludedMeshesIds = new Array();
  5053. this._includedOnlyMeshesIds = new Array();
  5054. scene.lights.push(this);
  5055. }
  5056. Light.prototype.getShadowGenerator = function () {
  5057. return this._shadowGenerator;
  5058. };
  5059. Light.prototype.getAbsolutePosition = function () {
  5060. return BABYLON.Vector3.Zero();
  5061. };
  5062. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5063. };
  5064. Light.prototype._getWorldMatrix = function () {
  5065. return BABYLON.Matrix.Identity();
  5066. };
  5067. Light.prototype.canAffectMesh = function (mesh) {
  5068. if (!mesh) {
  5069. return true;
  5070. }
  5071. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5072. return false;
  5073. }
  5074. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5075. return false;
  5076. }
  5077. return true;
  5078. };
  5079. Light.prototype.getWorldMatrix = function () {
  5080. this._currentRenderId = this.getScene().getRenderId();
  5081. var worldMatrix = this._getWorldMatrix();
  5082. if (this.parent && this.parent.getWorldMatrix) {
  5083. if (!this._parentedWorldMatrix) {
  5084. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5085. }
  5086. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5087. return this._parentedWorldMatrix;
  5088. }
  5089. return worldMatrix;
  5090. };
  5091. Light.prototype.dispose = function () {
  5092. if (this._shadowGenerator) {
  5093. this._shadowGenerator.dispose();
  5094. this._shadowGenerator = null;
  5095. }
  5096. // Remove from scene
  5097. var index = this.getScene().lights.indexOf(this);
  5098. this.getScene().lights.splice(index, 1);
  5099. };
  5100. return Light;
  5101. })(BABYLON.Node);
  5102. BABYLON.Light = Light;
  5103. })(BABYLON || (BABYLON = {}));
  5104. //# sourceMappingURL=babylon.light.js.map
  5105. var BABYLON;
  5106. (function (BABYLON) {
  5107. var PointLight = (function (_super) {
  5108. __extends(PointLight, _super);
  5109. function PointLight(name, position, scene) {
  5110. _super.call(this, name, scene);
  5111. this.position = position;
  5112. }
  5113. PointLight.prototype.getAbsolutePosition = function () {
  5114. return this._transformedPosition ? this._transformedPosition : this.position;
  5115. };
  5116. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5117. if (this.parent && this.parent.getWorldMatrix) {
  5118. if (!this._transformedPosition) {
  5119. this._transformedPosition = BABYLON.Vector3.Zero();
  5120. }
  5121. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5122. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5123. return;
  5124. }
  5125. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5126. };
  5127. PointLight.prototype.getShadowGenerator = function () {
  5128. return null;
  5129. };
  5130. PointLight.prototype._getWorldMatrix = function () {
  5131. if (!this._worldMatrix) {
  5132. this._worldMatrix = BABYLON.Matrix.Identity();
  5133. }
  5134. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5135. return this._worldMatrix;
  5136. };
  5137. return PointLight;
  5138. })(BABYLON.Light);
  5139. BABYLON.PointLight = PointLight;
  5140. })(BABYLON || (BABYLON = {}));
  5141. //# sourceMappingURL=babylon.pointLight.js.map
  5142. var BABYLON;
  5143. (function (BABYLON) {
  5144. var SpotLight = (function (_super) {
  5145. __extends(SpotLight, _super);
  5146. function SpotLight(name, position, direction, angle, exponent, scene) {
  5147. _super.call(this, name, scene);
  5148. this.position = position;
  5149. this.direction = direction;
  5150. this.angle = angle;
  5151. this.exponent = exponent;
  5152. }
  5153. SpotLight.prototype.getAbsolutePosition = function () {
  5154. return this._transformedPosition ? this._transformedPosition : this.position;
  5155. };
  5156. SpotLight.prototype.setDirectionToTarget = function (target) {
  5157. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5158. return this.direction;
  5159. };
  5160. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5161. var normalizeDirection;
  5162. if (this.parent && this.parent.getWorldMatrix) {
  5163. if (!this._transformedDirection) {
  5164. this._transformedDirection = BABYLON.Vector3.Zero();
  5165. }
  5166. if (!this._transformedPosition) {
  5167. this._transformedPosition = BABYLON.Vector3.Zero();
  5168. }
  5169. var parentWorldMatrix = this.parent.getWorldMatrix();
  5170. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5171. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5172. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5173. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5174. } else {
  5175. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5176. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5177. }
  5178. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5179. };
  5180. SpotLight.prototype._getWorldMatrix = function () {
  5181. if (!this._worldMatrix) {
  5182. this._worldMatrix = BABYLON.Matrix.Identity();
  5183. }
  5184. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5185. return this._worldMatrix;
  5186. };
  5187. return SpotLight;
  5188. })(BABYLON.Light);
  5189. BABYLON.SpotLight = SpotLight;
  5190. })(BABYLON || (BABYLON = {}));
  5191. //# sourceMappingURL=babylon.spotLight.js.map
  5192. var BABYLON;
  5193. (function (BABYLON) {
  5194. var DirectionalLight = (function (_super) {
  5195. __extends(DirectionalLight, _super);
  5196. function DirectionalLight(name, direction, scene) {
  5197. _super.call(this, name, scene);
  5198. this.direction = direction;
  5199. this.position = direction.scale(-1);
  5200. }
  5201. DirectionalLight.prototype.getAbsolutePosition = function () {
  5202. return this._transformedPosition ? this._transformedPosition : this.position;
  5203. };
  5204. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5205. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5206. return this.direction;
  5207. };
  5208. DirectionalLight.prototype._computeTransformedPosition = function () {
  5209. if (this.parent && this.parent.getWorldMatrix) {
  5210. if (!this._transformedPosition) {
  5211. this._transformedPosition = BABYLON.Vector3.Zero();
  5212. }
  5213. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5214. return true;
  5215. }
  5216. return false;
  5217. };
  5218. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5219. if (this.parent && this.parent.getWorldMatrix) {
  5220. if (!this._transformedDirection) {
  5221. this._transformedDirection = BABYLON.Vector3.Zero();
  5222. }
  5223. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5224. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5225. return;
  5226. }
  5227. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5228. };
  5229. DirectionalLight.prototype._getWorldMatrix = function () {
  5230. if (!this._worldMatrix) {
  5231. this._worldMatrix = BABYLON.Matrix.Identity();
  5232. }
  5233. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5234. return this._worldMatrix;
  5235. };
  5236. return DirectionalLight;
  5237. })(BABYLON.Light);
  5238. BABYLON.DirectionalLight = DirectionalLight;
  5239. })(BABYLON || (BABYLON = {}));
  5240. //# sourceMappingURL=babylon.directionalLight.js.map
  5241. var BABYLON;
  5242. (function (BABYLON) {
  5243. var ShadowGenerator = (function () {
  5244. function ShadowGenerator(mapSize, light) {
  5245. var _this = this;
  5246. // Members
  5247. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5248. this._darkness = 0;
  5249. this._transparencyShadow = false;
  5250. this._viewMatrix = BABYLON.Matrix.Zero();
  5251. this._projectionMatrix = BABYLON.Matrix.Zero();
  5252. this._transformMatrix = BABYLON.Matrix.Zero();
  5253. this._worldViewProjection = BABYLON.Matrix.Zero();
  5254. this._light = light;
  5255. this._scene = light.getScene();
  5256. light._shadowGenerator = this;
  5257. // Render target
  5258. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5259. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5260. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5261. this._shadowMap.renderParticles = false;
  5262. // Custom render function
  5263. var renderSubMesh = function (subMesh) {
  5264. var mesh = subMesh.getRenderingMesh();
  5265. var scene = _this._scene;
  5266. var engine = scene.getEngine();
  5267. // Culling
  5268. engine.setState(subMesh.getMaterial().backFaceCulling);
  5269. // Managing instances
  5270. var batch = mesh._getInstancesRenderList(subMesh._id);
  5271. if (batch.mustReturn) {
  5272. return;
  5273. }
  5274. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5275. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5276. engine.enableEffect(_this._effect);
  5277. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5278. var material = subMesh.getMaterial();
  5279. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5280. // Alpha test
  5281. if (material && material.needAlphaTesting()) {
  5282. var alphaTexture = material.getAlphaTestTexture();
  5283. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5284. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5285. }
  5286. // Bones
  5287. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5288. if (useBones) {
  5289. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5290. }
  5291. if (hardwareInstancedRendering) {
  5292. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5293. } else {
  5294. if (batch.renderSelf[subMesh._id]) {
  5295. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5296. // Draw
  5297. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5298. }
  5299. if (batch.visibleInstances[subMesh._id]) {
  5300. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5301. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5302. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5303. // Draw
  5304. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5305. }
  5306. }
  5307. }
  5308. } else {
  5309. // Need to reset refresh rate of the shadowMap
  5310. _this._shadowMap.resetRefreshCounter();
  5311. }
  5312. };
  5313. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5314. var index;
  5315. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5316. renderSubMesh(opaqueSubMeshes.data[index]);
  5317. }
  5318. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5319. renderSubMesh(alphaTestSubMeshes.data[index]);
  5320. }
  5321. if (_this._transparencyShadow) {
  5322. for (index = 0; index < transparentSubMeshes.length; index++) {
  5323. renderSubMesh(transparentSubMeshes.data[index]);
  5324. }
  5325. }
  5326. };
  5327. }
  5328. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5329. // Static
  5330. get: function () {
  5331. return ShadowGenerator._FILTER_NONE;
  5332. },
  5333. enumerable: true,
  5334. configurable: true
  5335. });
  5336. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5337. get: function () {
  5338. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5339. },
  5340. enumerable: true,
  5341. configurable: true
  5342. });
  5343. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5344. get: function () {
  5345. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5346. },
  5347. enumerable: true,
  5348. configurable: true
  5349. });
  5350. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5351. get: function () {
  5352. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5353. },
  5354. set: function (value) {
  5355. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5356. },
  5357. enumerable: true,
  5358. configurable: true
  5359. });
  5360. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5361. get: function () {
  5362. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5363. },
  5364. set: function (value) {
  5365. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5366. },
  5367. enumerable: true,
  5368. configurable: true
  5369. });
  5370. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5371. var defines = [];
  5372. if (this.useVarianceShadowMap) {
  5373. defines.push("#define VSM");
  5374. }
  5375. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5376. var mesh = subMesh.getMesh();
  5377. var scene = mesh.getScene();
  5378. var material = subMesh.getMaterial();
  5379. // Alpha test
  5380. if (material && material.needAlphaTesting()) {
  5381. defines.push("#define ALPHATEST");
  5382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5383. attribs.push(BABYLON.VertexBuffer.UVKind);
  5384. defines.push("#define UV1");
  5385. }
  5386. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5387. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5388. defines.push("#define UV2");
  5389. }
  5390. }
  5391. // Bones
  5392. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5395. defines.push("#define BONES");
  5396. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5397. }
  5398. // Instances
  5399. if (useInstances) {
  5400. defines.push("#define INSTANCES");
  5401. attribs.push("world0");
  5402. attribs.push("world1");
  5403. attribs.push("world2");
  5404. attribs.push("world3");
  5405. }
  5406. // Get correct effect
  5407. var join = defines.join("\n");
  5408. if (this._cachedDefines != join) {
  5409. this._cachedDefines = join;
  5410. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5411. }
  5412. return this._effect.isReady();
  5413. };
  5414. ShadowGenerator.prototype.getShadowMap = function () {
  5415. return this._shadowMap;
  5416. };
  5417. ShadowGenerator.prototype.getLight = function () {
  5418. return this._light;
  5419. };
  5420. // Methods
  5421. ShadowGenerator.prototype.getTransformMatrix = function () {
  5422. var lightPosition = this._light.position;
  5423. var lightDirection = this._light.direction;
  5424. if (this._light._computeTransformedPosition()) {
  5425. lightPosition = this._light._transformedPosition;
  5426. }
  5427. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5428. this._cachedPosition = lightPosition.clone();
  5429. this._cachedDirection = lightDirection.clone();
  5430. var activeCamera = this._scene.activeCamera;
  5431. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5432. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5433. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5434. }
  5435. return this._transformMatrix;
  5436. };
  5437. ShadowGenerator.prototype.getDarkness = function () {
  5438. return this._darkness;
  5439. };
  5440. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5441. if (darkness >= 1.0)
  5442. this._darkness = 1.0;
  5443. else if (darkness <= 0.0)
  5444. this._darkness = 0.0;
  5445. else
  5446. this._darkness = darkness;
  5447. };
  5448. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5449. this._transparencyShadow = hasShadow;
  5450. };
  5451. ShadowGenerator.prototype.dispose = function () {
  5452. this._shadowMap.dispose();
  5453. };
  5454. ShadowGenerator._FILTER_NONE = 0;
  5455. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5456. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5457. return ShadowGenerator;
  5458. })();
  5459. BABYLON.ShadowGenerator = ShadowGenerator;
  5460. })(BABYLON || (BABYLON = {}));
  5461. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5462. var BABYLON;
  5463. (function (BABYLON) {
  5464. var HemisphericLight = (function (_super) {
  5465. __extends(HemisphericLight, _super);
  5466. function HemisphericLight(name, direction, scene) {
  5467. _super.call(this, name, scene);
  5468. this.direction = direction;
  5469. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5470. }
  5471. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5472. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5473. return this.direction;
  5474. };
  5475. HemisphericLight.prototype.getShadowGenerator = function () {
  5476. return null;
  5477. };
  5478. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5479. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5480. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5481. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5482. };
  5483. HemisphericLight.prototype._getWorldMatrix = function () {
  5484. if (!this._worldMatrix) {
  5485. this._worldMatrix = BABYLON.Matrix.Identity();
  5486. }
  5487. return this._worldMatrix;
  5488. };
  5489. return HemisphericLight;
  5490. })(BABYLON.Light);
  5491. BABYLON.HemisphericLight = HemisphericLight;
  5492. })(BABYLON || (BABYLON = {}));
  5493. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5494. var BABYLON;
  5495. (function (BABYLON) {
  5496. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5497. if (boxMin.x > sphereCenter.x + sphereRadius)
  5498. return false;
  5499. if (sphereCenter.x - sphereRadius > boxMax.x)
  5500. return false;
  5501. if (boxMin.y > sphereCenter.y + sphereRadius)
  5502. return false;
  5503. if (sphereCenter.y - sphereRadius > boxMax.y)
  5504. return false;
  5505. if (boxMin.z > sphereCenter.z + sphereRadius)
  5506. return false;
  5507. if (sphereCenter.z - sphereRadius > boxMax.z)
  5508. return false;
  5509. return true;
  5510. };
  5511. var getLowestRoot = function (a, b, c, maxR) {
  5512. var determinant = b * b - 4.0 * a * c;
  5513. var result = { root: 0, found: false };
  5514. if (determinant < 0)
  5515. return result;
  5516. var sqrtD = Math.sqrt(determinant);
  5517. var r1 = (-b - sqrtD) / (2.0 * a);
  5518. var r2 = (-b + sqrtD) / (2.0 * a);
  5519. if (r1 > r2) {
  5520. var temp = r2;
  5521. r2 = r1;
  5522. r1 = temp;
  5523. }
  5524. if (r1 > 0 && r1 < maxR) {
  5525. result.root = r1;
  5526. result.found = true;
  5527. return result;
  5528. }
  5529. if (r2 > 0 && r2 < maxR) {
  5530. result.root = r2;
  5531. result.found = true;
  5532. return result;
  5533. }
  5534. return result;
  5535. };
  5536. var Collider = (function () {
  5537. function Collider() {
  5538. this.radius = new BABYLON.Vector3(1, 1, 1);
  5539. this.retry = 0;
  5540. this.basePointWorld = BABYLON.Vector3.Zero();
  5541. this.velocityWorld = BABYLON.Vector3.Zero();
  5542. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5543. this._collisionPoint = BABYLON.Vector3.Zero();
  5544. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5545. this._tempVector = BABYLON.Vector3.Zero();
  5546. this._tempVector2 = BABYLON.Vector3.Zero();
  5547. this._tempVector3 = BABYLON.Vector3.Zero();
  5548. this._tempVector4 = BABYLON.Vector3.Zero();
  5549. this._edge = BABYLON.Vector3.Zero();
  5550. this._baseToVertex = BABYLON.Vector3.Zero();
  5551. this._destinationPoint = BABYLON.Vector3.Zero();
  5552. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5553. this._displacementVector = BABYLON.Vector3.Zero();
  5554. }
  5555. // Methods
  5556. Collider.prototype._initialize = function (source, dir, e) {
  5557. this.velocity = dir;
  5558. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5559. this.basePoint = source;
  5560. source.multiplyToRef(this.radius, this.basePointWorld);
  5561. dir.multiplyToRef(this.radius, this.velocityWorld);
  5562. this.velocityWorldLength = this.velocityWorld.length();
  5563. this.epsilon = e;
  5564. this.collisionFound = false;
  5565. };
  5566. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5567. pa.subtractToRef(point, this._tempVector);
  5568. pb.subtractToRef(point, this._tempVector2);
  5569. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5570. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5571. if (d < 0)
  5572. return false;
  5573. pc.subtractToRef(point, this._tempVector3);
  5574. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5575. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5576. if (d < 0)
  5577. return false;
  5578. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5579. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5580. return d >= 0;
  5581. };
  5582. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5583. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5584. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5585. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5586. return false;
  5587. }
  5588. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5589. return false;
  5590. return true;
  5591. };
  5592. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5593. var t0;
  5594. var embeddedInPlane = false;
  5595. if (!subMesh._trianglePlanes) {
  5596. subMesh._trianglePlanes = [];
  5597. }
  5598. if (!subMesh._trianglePlanes[faceIndex]) {
  5599. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5600. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5601. }
  5602. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5603. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5604. return;
  5605. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5606. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5607. if (normalDotVelocity == 0) {
  5608. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5609. return;
  5610. embeddedInPlane = true;
  5611. t0 = 0;
  5612. } else {
  5613. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5614. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5615. if (t0 > t1) {
  5616. var temp = t1;
  5617. t1 = t0;
  5618. t0 = temp;
  5619. }
  5620. if (t0 > 1.0 || t1 < 0.0)
  5621. return;
  5622. if (t0 < 0)
  5623. t0 = 0;
  5624. if (t0 > 1.0)
  5625. t0 = 1.0;
  5626. }
  5627. this._collisionPoint.copyFromFloats(0, 0, 0);
  5628. var found = false;
  5629. var t = 1.0;
  5630. if (!embeddedInPlane) {
  5631. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5632. this.velocity.scaleToRef(t0, this._tempVector);
  5633. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5634. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5635. found = true;
  5636. t = t0;
  5637. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5638. }
  5639. }
  5640. if (!found) {
  5641. var velocitySquaredLength = this.velocity.lengthSquared();
  5642. var a = velocitySquaredLength;
  5643. this.basePoint.subtractToRef(p1, this._tempVector);
  5644. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5645. var c = this._tempVector.lengthSquared() - 1.0;
  5646. var lowestRoot = getLowestRoot(a, b, c, t);
  5647. if (lowestRoot.found) {
  5648. t = lowestRoot.root;
  5649. found = true;
  5650. this._collisionPoint.copyFrom(p1);
  5651. }
  5652. this.basePoint.subtractToRef(p2, this._tempVector);
  5653. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5654. c = this._tempVector.lengthSquared() - 1.0;
  5655. lowestRoot = getLowestRoot(a, b, c, t);
  5656. if (lowestRoot.found) {
  5657. t = lowestRoot.root;
  5658. found = true;
  5659. this._collisionPoint.copyFrom(p2);
  5660. }
  5661. this.basePoint.subtractToRef(p3, this._tempVector);
  5662. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5663. c = this._tempVector.lengthSquared() - 1.0;
  5664. lowestRoot = getLowestRoot(a, b, c, t);
  5665. if (lowestRoot.found) {
  5666. t = lowestRoot.root;
  5667. found = true;
  5668. this._collisionPoint.copyFrom(p3);
  5669. }
  5670. p2.subtractToRef(p1, this._edge);
  5671. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5672. var edgeSquaredLength = this._edge.lengthSquared();
  5673. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5674. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5675. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5676. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5677. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5678. lowestRoot = getLowestRoot(a, b, c, t);
  5679. if (lowestRoot.found) {
  5680. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5681. if (f >= 0.0 && f <= 1.0) {
  5682. t = lowestRoot.root;
  5683. found = true;
  5684. this._edge.scaleInPlace(f);
  5685. p1.addToRef(this._edge, this._collisionPoint);
  5686. }
  5687. }
  5688. p3.subtractToRef(p2, this._edge);
  5689. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5690. edgeSquaredLength = this._edge.lengthSquared();
  5691. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5692. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5693. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5694. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5695. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5696. lowestRoot = getLowestRoot(a, b, c, t);
  5697. if (lowestRoot.found) {
  5698. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5699. if (f >= 0.0 && f <= 1.0) {
  5700. t = lowestRoot.root;
  5701. found = true;
  5702. this._edge.scaleInPlace(f);
  5703. p2.addToRef(this._edge, this._collisionPoint);
  5704. }
  5705. }
  5706. p1.subtractToRef(p3, this._edge);
  5707. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5708. edgeSquaredLength = this._edge.lengthSquared();
  5709. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5710. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5711. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5712. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5713. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5714. lowestRoot = getLowestRoot(a, b, c, t);
  5715. if (lowestRoot.found) {
  5716. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5717. if (f >= 0.0 && f <= 1.0) {
  5718. t = lowestRoot.root;
  5719. found = true;
  5720. this._edge.scaleInPlace(f);
  5721. p3.addToRef(this._edge, this._collisionPoint);
  5722. }
  5723. }
  5724. }
  5725. if (found) {
  5726. var distToCollision = t * this.velocity.length();
  5727. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5728. if (!this.intersectionPoint) {
  5729. this.intersectionPoint = this._collisionPoint.clone();
  5730. } else {
  5731. this.intersectionPoint.copyFrom(this._collisionPoint);
  5732. }
  5733. this.nearestDistance = distToCollision;
  5734. this.collisionFound = true;
  5735. this.collidedMesh = subMesh.getMesh();
  5736. }
  5737. }
  5738. };
  5739. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5740. for (var i = indexStart; i < indexEnd; i += 3) {
  5741. var p1 = pts[indices[i] - decal];
  5742. var p2 = pts[indices[i + 1] - decal];
  5743. var p3 = pts[indices[i + 2] - decal];
  5744. this._testTriangle(i, subMesh, p3, p2, p1);
  5745. }
  5746. };
  5747. Collider.prototype._getResponse = function (pos, vel) {
  5748. pos.addToRef(vel, this._destinationPoint);
  5749. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5750. this.basePoint.addToRef(vel, pos);
  5751. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5752. this._slidePlaneNormal.normalize();
  5753. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5754. pos.addInPlace(this._displacementVector);
  5755. this.intersectionPoint.addInPlace(this._displacementVector);
  5756. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5757. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5758. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5759. };
  5760. return Collider;
  5761. })();
  5762. BABYLON.Collider = Collider;
  5763. })(BABYLON || (BABYLON = {}));
  5764. //# sourceMappingURL=babylon.collider.js.map
  5765. var BABYLON;
  5766. (function (BABYLON) {
  5767. var Camera = (function (_super) {
  5768. __extends(Camera, _super);
  5769. function Camera(name, position, scene) {
  5770. _super.call(this, name, scene);
  5771. this.position = position;
  5772. // Members
  5773. this.upVector = BABYLON.Vector3.Up();
  5774. this.orthoLeft = null;
  5775. this.orthoRight = null;
  5776. this.orthoBottom = null;
  5777. this.orthoTop = null;
  5778. this.fov = 0.8;
  5779. this.minZ = 1.0;
  5780. this.maxZ = 10000.0;
  5781. this.inertia = 0.9;
  5782. this.mode = Camera.PERSPECTIVE_CAMERA;
  5783. this.isIntermediate = false;
  5784. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5785. this.subCameras = [];
  5786. this.layerMask = 0xFFFFFFFF;
  5787. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5788. this._projectionMatrix = new BABYLON.Matrix();
  5789. this._postProcesses = new Array();
  5790. this._postProcessesTakenIndices = [];
  5791. scene.cameras.push(this);
  5792. if (!scene.activeCamera) {
  5793. scene.activeCamera = this;
  5794. }
  5795. }
  5796. //Cache
  5797. Camera.prototype._initCache = function () {
  5798. _super.prototype._initCache.call(this);
  5799. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5800. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5801. this._cache.mode = undefined;
  5802. this._cache.minZ = undefined;
  5803. this._cache.maxZ = undefined;
  5804. this._cache.fov = undefined;
  5805. this._cache.aspectRatio = undefined;
  5806. this._cache.orthoLeft = undefined;
  5807. this._cache.orthoRight = undefined;
  5808. this._cache.orthoBottom = undefined;
  5809. this._cache.orthoTop = undefined;
  5810. this._cache.renderWidth = undefined;
  5811. this._cache.renderHeight = undefined;
  5812. };
  5813. Camera.prototype._updateCache = function (ignoreParentClass) {
  5814. if (!ignoreParentClass) {
  5815. _super.prototype._updateCache.call(this);
  5816. }
  5817. var engine = this.getEngine();
  5818. this._cache.position.copyFrom(this.position);
  5819. this._cache.upVector.copyFrom(this.upVector);
  5820. this._cache.mode = this.mode;
  5821. this._cache.minZ = this.minZ;
  5822. this._cache.maxZ = this.maxZ;
  5823. this._cache.fov = this.fov;
  5824. this._cache.aspectRatio = engine.getAspectRatio(this);
  5825. this._cache.orthoLeft = this.orthoLeft;
  5826. this._cache.orthoRight = this.orthoRight;
  5827. this._cache.orthoBottom = this.orthoBottom;
  5828. this._cache.orthoTop = this.orthoTop;
  5829. this._cache.renderWidth = engine.getRenderWidth();
  5830. this._cache.renderHeight = engine.getRenderHeight();
  5831. };
  5832. Camera.prototype._updateFromScene = function () {
  5833. this.updateCache();
  5834. this._update();
  5835. };
  5836. // Synchronized
  5837. Camera.prototype._isSynchronized = function () {
  5838. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5839. };
  5840. Camera.prototype._isSynchronizedViewMatrix = function () {
  5841. if (!_super.prototype._isSynchronized.call(this))
  5842. return false;
  5843. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5844. };
  5845. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5846. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5847. if (!check) {
  5848. return false;
  5849. }
  5850. var engine = this.getEngine();
  5851. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5852. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5853. } else {
  5854. 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();
  5855. }
  5856. return check;
  5857. };
  5858. // Controls
  5859. Camera.prototype.attachControl = function (element) {
  5860. };
  5861. Camera.prototype.detachControl = function (element) {
  5862. };
  5863. Camera.prototype._update = function () {
  5864. };
  5865. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5866. if (typeof insertAt === "undefined") { insertAt = null; }
  5867. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5868. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5869. return 0;
  5870. }
  5871. if (insertAt == null || insertAt < 0) {
  5872. this._postProcesses.push(postProcess);
  5873. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5874. return this._postProcesses.length - 1;
  5875. }
  5876. var add = 0;
  5877. if (this._postProcesses[insertAt]) {
  5878. var start = this._postProcesses.length - 1;
  5879. for (var i = start; i >= insertAt + 1; --i) {
  5880. this._postProcesses[i + 1] = this._postProcesses[i];
  5881. }
  5882. add = 1;
  5883. }
  5884. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5885. if (this._postProcessesTakenIndices[i] < insertAt) {
  5886. continue;
  5887. }
  5888. start = this._postProcessesTakenIndices.length - 1;
  5889. for (var j = start; j >= i; --j) {
  5890. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5891. }
  5892. this._postProcessesTakenIndices[i] = insertAt;
  5893. break;
  5894. }
  5895. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5896. this._postProcessesTakenIndices.push(insertAt);
  5897. }
  5898. var result = insertAt + add;
  5899. this._postProcesses[result] = postProcess;
  5900. return result;
  5901. };
  5902. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5903. if (typeof atIndices === "undefined") { atIndices = null; }
  5904. var result = [];
  5905. if (!atIndices) {
  5906. var length = this._postProcesses.length;
  5907. for (var i = 0; i < length; i++) {
  5908. if (this._postProcesses[i] !== postProcess) {
  5909. continue;
  5910. }
  5911. delete this._postProcesses[i];
  5912. var index = this._postProcessesTakenIndices.indexOf(i);
  5913. this._postProcessesTakenIndices.splice(index, 1);
  5914. }
  5915. } else {
  5916. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5917. for (i = 0; i < atIndices.length; i++) {
  5918. var foundPostProcess = this._postProcesses[atIndices[i]];
  5919. if (foundPostProcess !== postProcess) {
  5920. result.push(i);
  5921. continue;
  5922. }
  5923. delete this._postProcesses[atIndices[i]];
  5924. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5925. this._postProcessesTakenIndices.splice(index, 1);
  5926. }
  5927. }
  5928. return result;
  5929. };
  5930. Camera.prototype.getWorldMatrix = function () {
  5931. if (!this._worldMatrix) {
  5932. this._worldMatrix = BABYLON.Matrix.Identity();
  5933. }
  5934. var viewMatrix = this.getViewMatrix();
  5935. viewMatrix.invertToRef(this._worldMatrix);
  5936. return this._worldMatrix;
  5937. };
  5938. Camera.prototype._getViewMatrix = function () {
  5939. return BABYLON.Matrix.Identity();
  5940. };
  5941. Camera.prototype.getViewMatrix = function () {
  5942. this._computedViewMatrix = this._computeViewMatrix();
  5943. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5944. return this._computedViewMatrix;
  5945. }
  5946. if (!this._worldMatrix) {
  5947. this._worldMatrix = BABYLON.Matrix.Identity();
  5948. }
  5949. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5950. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5951. this._computedViewMatrix.invert();
  5952. this._currentRenderId = this.getScene().getRenderId();
  5953. return this._computedViewMatrix;
  5954. };
  5955. Camera.prototype._computeViewMatrix = function (force) {
  5956. if (!force && this._isSynchronizedViewMatrix()) {
  5957. return this._computedViewMatrix;
  5958. }
  5959. this._computedViewMatrix = this._getViewMatrix();
  5960. if (!this.parent || !this.parent.getWorldMatrix) {
  5961. this._currentRenderId = this.getScene().getRenderId();
  5962. }
  5963. return this._computedViewMatrix;
  5964. };
  5965. Camera.prototype.getProjectionMatrix = function (force) {
  5966. if (!force && this._isSynchronizedProjectionMatrix()) {
  5967. return this._projectionMatrix;
  5968. }
  5969. var engine = this.getEngine();
  5970. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5971. if (this.minZ <= 0) {
  5972. this.minZ = 0.1;
  5973. }
  5974. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5975. return this._projectionMatrix;
  5976. }
  5977. var halfWidth = engine.getRenderWidth() / 2.0;
  5978. var halfHeight = engine.getRenderHeight() / 2.0;
  5979. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5980. return this._projectionMatrix;
  5981. };
  5982. Camera.prototype.dispose = function () {
  5983. // Remove from scene
  5984. var index = this.getScene().cameras.indexOf(this);
  5985. this.getScene().cameras.splice(index, 1);
  5986. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5987. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5988. }
  5989. };
  5990. Camera.PERSPECTIVE_CAMERA = 0;
  5991. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5992. return Camera;
  5993. })(BABYLON.Node);
  5994. BABYLON.Camera = Camera;
  5995. })(BABYLON || (BABYLON = {}));
  5996. //# sourceMappingURL=babylon.camera.js.map
  5997. var BABYLON;
  5998. (function (BABYLON) {
  5999. var TargetCamera = (function (_super) {
  6000. __extends(TargetCamera, _super);
  6001. function TargetCamera(name, position, scene) {
  6002. _super.call(this, name, position, scene);
  6003. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6004. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6005. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6006. this.speed = 2.0;
  6007. this.noRotationConstraint = false;
  6008. this.lockedTarget = null;
  6009. this._currentTarget = BABYLON.Vector3.Zero();
  6010. this._viewMatrix = BABYLON.Matrix.Zero();
  6011. this._camMatrix = BABYLON.Matrix.Zero();
  6012. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6013. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6014. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6015. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6016. this._lookAtTemp = BABYLON.Matrix.Zero();
  6017. this._tempMatrix = BABYLON.Matrix.Zero();
  6018. }
  6019. TargetCamera.prototype._getLockedTargetPosition = function () {
  6020. if (!this.lockedTarget) {
  6021. return null;
  6022. }
  6023. return this.lockedTarget.position || this.lockedTarget;
  6024. };
  6025. // Cache
  6026. TargetCamera.prototype._initCache = function () {
  6027. _super.prototype._initCache.call(this);
  6028. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6029. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6030. };
  6031. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6032. if (!ignoreParentClass) {
  6033. _super.prototype._updateCache.call(this);
  6034. }
  6035. var lockedTargetPosition = this._getLockedTargetPosition();
  6036. if (!lockedTargetPosition) {
  6037. this._cache.lockedTarget = null;
  6038. } else {
  6039. if (!this._cache.lockedTarget) {
  6040. this._cache.lockedTarget = lockedTargetPosition.clone();
  6041. } else {
  6042. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6043. }
  6044. }
  6045. this._cache.rotation.copyFrom(this.rotation);
  6046. };
  6047. // Synchronized
  6048. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6049. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6050. return false;
  6051. }
  6052. var lockedTargetPosition = this._getLockedTargetPosition();
  6053. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6054. };
  6055. // Methods
  6056. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6057. var engine = this.getEngine();
  6058. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6059. };
  6060. // Target
  6061. TargetCamera.prototype.setTarget = function (target) {
  6062. this.upVector.normalize();
  6063. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6064. this._camMatrix.invert();
  6065. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6066. var vDir = target.subtract(this.position);
  6067. if (vDir.x >= 0.0) {
  6068. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6069. } else {
  6070. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6071. }
  6072. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6073. if (isNaN(this.rotation.x)) {
  6074. this.rotation.x = 0;
  6075. }
  6076. if (isNaN(this.rotation.y)) {
  6077. this.rotation.y = 0;
  6078. }
  6079. if (isNaN(this.rotation.z)) {
  6080. this.rotation.z = 0;
  6081. }
  6082. };
  6083. TargetCamera.prototype.getTarget = function () {
  6084. return this._currentTarget;
  6085. };
  6086. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6087. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6088. };
  6089. TargetCamera.prototype._updatePosition = function () {
  6090. this.position.addInPlace(this.cameraDirection);
  6091. };
  6092. TargetCamera.prototype._update = function () {
  6093. var needToMove = this._decideIfNeedsToMove();
  6094. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6095. // Move
  6096. if (needToMove) {
  6097. this._updatePosition();
  6098. }
  6099. // Rotate
  6100. if (needToRotate) {
  6101. this.rotation.x += this.cameraRotation.x;
  6102. this.rotation.y += this.cameraRotation.y;
  6103. if (!this.noRotationConstraint) {
  6104. var limit = (Math.PI / 2) * 0.95;
  6105. if (this.rotation.x > limit)
  6106. this.rotation.x = limit;
  6107. if (this.rotation.x < -limit)
  6108. this.rotation.x = -limit;
  6109. }
  6110. }
  6111. // Inertia
  6112. if (needToMove) {
  6113. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6114. this.cameraDirection.x = 0;
  6115. }
  6116. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6117. this.cameraDirection.y = 0;
  6118. }
  6119. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6120. this.cameraDirection.z = 0;
  6121. }
  6122. this.cameraDirection.scaleInPlace(this.inertia);
  6123. }
  6124. if (needToRotate) {
  6125. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6126. this.cameraRotation.x = 0;
  6127. }
  6128. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6129. this.cameraRotation.y = 0;
  6130. }
  6131. this.cameraRotation.scaleInPlace(this.inertia);
  6132. }
  6133. };
  6134. TargetCamera.prototype._getViewMatrix = function () {
  6135. if (!this.lockedTarget) {
  6136. // Compute
  6137. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6138. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6139. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6140. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6141. this._lookAtTemp.invert();
  6142. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6143. } else {
  6144. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6145. }
  6146. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6147. // Computing target and final matrix
  6148. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6149. } else {
  6150. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6151. }
  6152. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6153. return this._viewMatrix;
  6154. };
  6155. return TargetCamera;
  6156. })(BABYLON.Camera);
  6157. BABYLON.TargetCamera = TargetCamera;
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=babylon.targetCamera.js.map
  6160. var BABYLON;
  6161. (function (BABYLON) {
  6162. var FollowCamera = (function (_super) {
  6163. __extends(FollowCamera, _super);
  6164. function FollowCamera(name, position, scene) {
  6165. _super.call(this, name, position, scene);
  6166. this.radius = 12;
  6167. this.rotationOffset = 0;
  6168. this.heightOffset = 4;
  6169. this.cameraAcceleration = 0.05;
  6170. this.maxCameraSpeed = 20;
  6171. }
  6172. FollowCamera.prototype.getRadians = function (degrees) {
  6173. return degrees * Math.PI / 180;
  6174. };
  6175. FollowCamera.prototype.follow = function (cameraTarget) {
  6176. if (!cameraTarget)
  6177. return;
  6178. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6179. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6180. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6181. var dx = targetX - this.position.x;
  6182. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6183. var dz = (targetZ) - this.position.z;
  6184. var vx = dx * this.cameraAcceleration * 2;
  6185. var vy = dy * this.cameraAcceleration;
  6186. var vz = dz * this.cameraAcceleration * 2;
  6187. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6188. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6189. }
  6190. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6191. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6192. }
  6193. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6194. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6195. }
  6196. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6197. this.setTarget(cameraTarget.position);
  6198. };
  6199. FollowCamera.prototype._update = function () {
  6200. _super.prototype._update.call(this);
  6201. this.follow(this.target);
  6202. };
  6203. return FollowCamera;
  6204. })(BABYLON.TargetCamera);
  6205. BABYLON.FollowCamera = FollowCamera;
  6206. })(BABYLON || (BABYLON = {}));
  6207. //# sourceMappingURL=babylon.followCamera.js.map
  6208. var BABYLON;
  6209. (function (BABYLON) {
  6210. var FreeCamera = (function (_super) {
  6211. __extends(FreeCamera, _super);
  6212. function FreeCamera(name, position, scene) {
  6213. _super.call(this, name, position, scene);
  6214. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6215. this.keysUp = [38];
  6216. this.keysDown = [40];
  6217. this.keysLeft = [37];
  6218. this.keysRight = [39];
  6219. this.checkCollisions = false;
  6220. this.applyGravity = false;
  6221. this.angularSensibility = 2000.0;
  6222. this._keys = [];
  6223. this._collider = new BABYLON.Collider();
  6224. this._needMoveForGravity = true;
  6225. this._oldPosition = BABYLON.Vector3.Zero();
  6226. this._diffPosition = BABYLON.Vector3.Zero();
  6227. this._newPosition = BABYLON.Vector3.Zero();
  6228. }
  6229. // Controls
  6230. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6231. var _this = this;
  6232. var previousPosition;
  6233. var engine = this.getEngine();
  6234. if (this._attachedElement) {
  6235. return;
  6236. }
  6237. this._attachedElement = element;
  6238. if (this._onMouseDown === undefined) {
  6239. this._onMouseDown = function (evt) {
  6240. previousPosition = {
  6241. x: evt.clientX,
  6242. y: evt.clientY
  6243. };
  6244. if (!noPreventDefault) {
  6245. evt.preventDefault();
  6246. }
  6247. };
  6248. this._onMouseUp = function (evt) {
  6249. previousPosition = null;
  6250. if (!noPreventDefault) {
  6251. evt.preventDefault();
  6252. }
  6253. };
  6254. this._onMouseOut = function (evt) {
  6255. previousPosition = null;
  6256. _this._keys = [];
  6257. if (!noPreventDefault) {
  6258. evt.preventDefault();
  6259. }
  6260. };
  6261. this._onMouseMove = function (evt) {
  6262. if (!previousPosition && !engine.isPointerLock) {
  6263. return;
  6264. }
  6265. var offsetX;
  6266. var offsetY;
  6267. if (!engine.isPointerLock) {
  6268. offsetX = evt.clientX - previousPosition.x;
  6269. offsetY = evt.clientY - previousPosition.y;
  6270. } else {
  6271. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6272. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6273. }
  6274. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6275. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6276. previousPosition = {
  6277. x: evt.clientX,
  6278. y: evt.clientY
  6279. };
  6280. if (!noPreventDefault) {
  6281. evt.preventDefault();
  6282. }
  6283. };
  6284. this._onKeyDown = function (evt) {
  6285. 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) {
  6286. var index = _this._keys.indexOf(evt.keyCode);
  6287. if (index === -1) {
  6288. _this._keys.push(evt.keyCode);
  6289. }
  6290. if (!noPreventDefault) {
  6291. evt.preventDefault();
  6292. }
  6293. }
  6294. };
  6295. this._onKeyUp = function (evt) {
  6296. 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) {
  6297. var index = _this._keys.indexOf(evt.keyCode);
  6298. if (index >= 0) {
  6299. _this._keys.splice(index, 1);
  6300. }
  6301. if (!noPreventDefault) {
  6302. evt.preventDefault();
  6303. }
  6304. }
  6305. };
  6306. this._onLostFocus = function () {
  6307. _this._keys = [];
  6308. };
  6309. this._reset = function () {
  6310. _this._keys = [];
  6311. previousPosition = null;
  6312. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6313. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6314. };
  6315. }
  6316. element.addEventListener("mousedown", this._onMouseDown, false);
  6317. element.addEventListener("mouseup", this._onMouseUp, false);
  6318. element.addEventListener("mouseout", this._onMouseOut, false);
  6319. element.addEventListener("mousemove", this._onMouseMove, false);
  6320. BABYLON.Tools.RegisterTopRootEvents([
  6321. { name: "keydown", handler: this._onKeyDown },
  6322. { name: "keyup", handler: this._onKeyUp },
  6323. { name: "blur", handler: this._onLostFocus }
  6324. ]);
  6325. };
  6326. FreeCamera.prototype.detachControl = function (element) {
  6327. if (this._attachedElement != element) {
  6328. return;
  6329. }
  6330. element.removeEventListener("mousedown", this._onMouseDown);
  6331. element.removeEventListener("mouseup", this._onMouseUp);
  6332. element.removeEventListener("mouseout", this._onMouseOut);
  6333. element.removeEventListener("mousemove", this._onMouseMove);
  6334. BABYLON.Tools.UnregisterTopRootEvents([
  6335. { name: "keydown", handler: this._onKeyDown },
  6336. { name: "keyup", handler: this._onKeyUp },
  6337. { name: "blur", handler: this._onLostFocus }
  6338. ]);
  6339. this._attachedElement = null;
  6340. if (this._reset) {
  6341. this._reset();
  6342. }
  6343. };
  6344. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6345. var globalPosition;
  6346. if (this.parent) {
  6347. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6348. } else {
  6349. globalPosition = this.position;
  6350. }
  6351. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6352. this._collider.radius = this.ellipsoid;
  6353. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6354. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6355. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6356. this.position.addInPlace(this._diffPosition);
  6357. if (this.onCollide) {
  6358. this.onCollide(this._collider.collidedMesh);
  6359. }
  6360. }
  6361. };
  6362. FreeCamera.prototype._checkInputs = function () {
  6363. if (!this._localDirection) {
  6364. this._localDirection = BABYLON.Vector3.Zero();
  6365. this._transformedDirection = BABYLON.Vector3.Zero();
  6366. }
  6367. for (var index = 0; index < this._keys.length; index++) {
  6368. var keyCode = this._keys[index];
  6369. var speed = this._computeLocalCameraSpeed();
  6370. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6371. this._localDirection.copyFromFloats(-speed, 0, 0);
  6372. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6373. this._localDirection.copyFromFloats(0, 0, speed);
  6374. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6375. this._localDirection.copyFromFloats(speed, 0, 0);
  6376. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6377. this._localDirection.copyFromFloats(0, 0, -speed);
  6378. }
  6379. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6380. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6381. this.cameraDirection.addInPlace(this._transformedDirection);
  6382. }
  6383. };
  6384. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6385. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6386. };
  6387. FreeCamera.prototype._updatePosition = function () {
  6388. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6389. this._collideWithWorld(this.cameraDirection);
  6390. if (this.applyGravity) {
  6391. var oldPosition = this.position;
  6392. this._collideWithWorld(this.getScene().gravity);
  6393. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6394. }
  6395. } else {
  6396. this.position.addInPlace(this.cameraDirection);
  6397. }
  6398. };
  6399. FreeCamera.prototype._update = function () {
  6400. this._checkInputs();
  6401. _super.prototype._update.call(this);
  6402. };
  6403. return FreeCamera;
  6404. })(BABYLON.TargetCamera);
  6405. BABYLON.FreeCamera = FreeCamera;
  6406. })(BABYLON || (BABYLON = {}));
  6407. //# sourceMappingURL=babylon.freeCamera.js.map
  6408. var BABYLON;
  6409. (function (BABYLON) {
  6410. // We're mainly based on the logic defined into the FreeCamera code
  6411. var TouchCamera = (function (_super) {
  6412. __extends(TouchCamera, _super);
  6413. function TouchCamera(name, position, scene) {
  6414. _super.call(this, name, position, scene);
  6415. this._offsetX = null;
  6416. this._offsetY = null;
  6417. this._pointerCount = 0;
  6418. this._pointerPressed = [];
  6419. this.angularSensibility = 200000.0;
  6420. this.moveSensibility = 500.0;
  6421. }
  6422. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6423. var _this = this;
  6424. var previousPosition;
  6425. if (this._attachedCanvas) {
  6426. return;
  6427. }
  6428. this._attachedCanvas = canvas;
  6429. if (this._onPointerDown === undefined) {
  6430. this._onPointerDown = function (evt) {
  6431. if (!noPreventDefault) {
  6432. evt.preventDefault();
  6433. }
  6434. _this._pointerPressed.push(evt.pointerId);
  6435. if (_this._pointerPressed.length !== 1) {
  6436. return;
  6437. }
  6438. previousPosition = {
  6439. x: evt.clientX,
  6440. y: evt.clientY
  6441. };
  6442. };
  6443. this._onPointerUp = function (evt) {
  6444. if (!noPreventDefault) {
  6445. evt.preventDefault();
  6446. }
  6447. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6448. if (index === -1) {
  6449. return;
  6450. }
  6451. _this._pointerPressed.splice(index, 1);
  6452. if (index != 0) {
  6453. return;
  6454. }
  6455. previousPosition = null;
  6456. _this._offsetX = null;
  6457. _this._offsetY = null;
  6458. };
  6459. this._onPointerMove = function (evt) {
  6460. if (!noPreventDefault) {
  6461. evt.preventDefault();
  6462. }
  6463. if (!previousPosition) {
  6464. return;
  6465. }
  6466. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6467. if (index != 0) {
  6468. return;
  6469. }
  6470. _this._offsetX = evt.clientX - previousPosition.x;
  6471. _this._offsetY = -(evt.clientY - previousPosition.y);
  6472. };
  6473. this._onLostFocus = function () {
  6474. _this._offsetX = null;
  6475. _this._offsetY = null;
  6476. };
  6477. }
  6478. canvas.addEventListener("pointerdown", this._onPointerDown);
  6479. canvas.addEventListener("pointerup", this._onPointerUp);
  6480. canvas.addEventListener("pointerout", this._onPointerUp);
  6481. canvas.addEventListener("pointermove", this._onPointerMove);
  6482. BABYLON.Tools.RegisterTopRootEvents([
  6483. { name: "blur", handler: this._onLostFocus }
  6484. ]);
  6485. };
  6486. TouchCamera.prototype.detachControl = function (canvas) {
  6487. if (this._attachedCanvas != canvas) {
  6488. return;
  6489. }
  6490. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6491. canvas.removeEventListener("pointerup", this._onPointerUp);
  6492. canvas.removeEventListener("pointerout", this._onPointerUp);
  6493. canvas.removeEventListener("pointermove", this._onPointerMove);
  6494. BABYLON.Tools.UnregisterTopRootEvents([
  6495. { name: "blur", handler: this._onLostFocus }
  6496. ]);
  6497. this._attachedCanvas = null;
  6498. };
  6499. TouchCamera.prototype._checkInputs = function () {
  6500. if (!this._offsetX) {
  6501. return;
  6502. }
  6503. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6504. if (this._pointerPressed.length > 1) {
  6505. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6506. } else {
  6507. var speed = this._computeLocalCameraSpeed();
  6508. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6509. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6510. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6511. }
  6512. };
  6513. return TouchCamera;
  6514. })(BABYLON.FreeCamera);
  6515. BABYLON.TouchCamera = TouchCamera;
  6516. })(BABYLON || (BABYLON = {}));
  6517. //# sourceMappingURL=babylon.touchCamera.js.map
  6518. var BABYLON;
  6519. (function (BABYLON) {
  6520. // We're mainly based on the logic defined into the FreeCamera code
  6521. var DeviceOrientationCamera = (function (_super) {
  6522. __extends(DeviceOrientationCamera, _super);
  6523. function DeviceOrientationCamera(name, position, scene) {
  6524. var _this = this;
  6525. _super.call(this, name, position, scene);
  6526. this._offsetX = null;
  6527. this._offsetY = null;
  6528. this._orientationGamma = 0;
  6529. this._orientationBeta = 0;
  6530. this._initialOrientationGamma = 0;
  6531. this._initialOrientationBeta = 0;
  6532. this.angularSensibility = 10000.0;
  6533. this.moveSensibility = 50.0;
  6534. window.addEventListener("resize", function () {
  6535. _this._initialOrientationGamma = null;
  6536. }, false);
  6537. }
  6538. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6539. var _this = this;
  6540. if (this._attachedCanvas) {
  6541. return;
  6542. }
  6543. this._attachedCanvas = canvas;
  6544. if (!this._orientationChanged) {
  6545. this._orientationChanged = function (evt) {
  6546. if (!_this._initialOrientationGamma) {
  6547. _this._initialOrientationGamma = evt.gamma;
  6548. _this._initialOrientationBeta = evt.beta;
  6549. }
  6550. _this._orientationGamma = evt.gamma;
  6551. _this._orientationBeta = evt.beta;
  6552. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6553. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6554. };
  6555. }
  6556. window.addEventListener("deviceorientation", this._orientationChanged);
  6557. };
  6558. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6559. if (this._attachedCanvas != canvas) {
  6560. return;
  6561. }
  6562. window.removeEventListener("deviceorientation", this._orientationChanged);
  6563. this._attachedCanvas = null;
  6564. this._orientationGamma = 0;
  6565. this._orientationBeta = 0;
  6566. this._initialOrientationGamma = 0;
  6567. this._initialOrientationBeta = 0;
  6568. };
  6569. DeviceOrientationCamera.prototype._checkInputs = function () {
  6570. if (!this._offsetX) {
  6571. return;
  6572. }
  6573. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6574. var speed = this._computeLocalCameraSpeed();
  6575. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6576. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6577. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6578. };
  6579. return DeviceOrientationCamera;
  6580. })(BABYLON.FreeCamera);
  6581. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6582. })(BABYLON || (BABYLON = {}));
  6583. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6584. var BABYLON;
  6585. (function (BABYLON) {
  6586. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6587. var ArcRotateCamera = (function (_super) {
  6588. __extends(ArcRotateCamera, _super);
  6589. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6590. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6591. this.alpha = alpha;
  6592. this.beta = beta;
  6593. this.radius = radius;
  6594. this.target = target;
  6595. this.inertialAlphaOffset = 0;
  6596. this.inertialBetaOffset = 0;
  6597. this.inertialRadiusOffset = 0;
  6598. this.lowerAlphaLimit = null;
  6599. this.upperAlphaLimit = null;
  6600. this.lowerBetaLimit = 0.01;
  6601. this.upperBetaLimit = Math.PI;
  6602. this.lowerRadiusLimit = null;
  6603. this.upperRadiusLimit = null;
  6604. this.angularSensibility = 1000.0;
  6605. this.wheelPrecision = 3.0;
  6606. this.keysUp = [38];
  6607. this.keysDown = [40];
  6608. this.keysLeft = [37];
  6609. this.keysRight = [39];
  6610. this.zoomOnFactor = 1;
  6611. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6612. this._keys = [];
  6613. this._viewMatrix = new BABYLON.Matrix();
  6614. this.checkCollisions = false;
  6615. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6616. this._collider = new BABYLON.Collider();
  6617. this._previousPosition = BABYLON.Vector3.Zero();
  6618. this._collisionVelocity = BABYLON.Vector3.Zero();
  6619. this._newPosition = BABYLON.Vector3.Zero();
  6620. // Pinch
  6621. // value for pinch step scaling
  6622. // set to 20 by default
  6623. this.pinchPrecision = 20;
  6624. this.getViewMatrix();
  6625. }
  6626. ArcRotateCamera.prototype._getTargetPosition = function () {
  6627. return this.target.position || this.target;
  6628. };
  6629. // Cache
  6630. ArcRotateCamera.prototype._initCache = function () {
  6631. _super.prototype._initCache.call(this);
  6632. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6633. this._cache.alpha = undefined;
  6634. this._cache.beta = undefined;
  6635. this._cache.radius = undefined;
  6636. this._cache.targetScreenOffset = undefined;
  6637. };
  6638. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6639. if (!ignoreParentClass) {
  6640. _super.prototype._updateCache.call(this);
  6641. }
  6642. this._cache.target.copyFrom(this._getTargetPosition());
  6643. this._cache.alpha = this.alpha;
  6644. this._cache.beta = this.beta;
  6645. this._cache.radius = this.radius;
  6646. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6647. };
  6648. // Synchronized
  6649. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6650. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6651. return false;
  6652. 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);
  6653. };
  6654. // Methods
  6655. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6656. var _this = this;
  6657. var previousPosition;
  6658. var pointerId;
  6659. // to know if pinch started
  6660. var pinchStarted = false;
  6661. // two pinch point on X
  6662. // that will use for find if user action is pinch open or pinch close
  6663. var pinchPointX1, pinchPointX2;
  6664. if (this._attachedElement) {
  6665. return;
  6666. }
  6667. this._attachedElement = element;
  6668. var engine = this.getEngine();
  6669. if (this._onPointerDown === undefined) {
  6670. this._onPointerDown = function (evt) {
  6671. if (pointerId) {
  6672. return;
  6673. }
  6674. pointerId = evt.pointerId;
  6675. previousPosition = {
  6676. x: evt.clientX,
  6677. y: evt.clientY
  6678. };
  6679. if (!noPreventDefault) {
  6680. evt.preventDefault();
  6681. }
  6682. };
  6683. this._onPointerUp = function (evt) {
  6684. previousPosition = null;
  6685. pointerId = null;
  6686. if (!noPreventDefault) {
  6687. evt.preventDefault();
  6688. }
  6689. };
  6690. this._onPointerMove = function (evt) {
  6691. if (!previousPosition) {
  6692. return;
  6693. }
  6694. if (pointerId !== evt.pointerId) {
  6695. return;
  6696. }
  6697. // return pinch is started
  6698. if (pinchStarted) {
  6699. return;
  6700. }
  6701. var offsetX = evt.clientX - previousPosition.x;
  6702. var offsetY = evt.clientY - previousPosition.y;
  6703. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6704. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6705. previousPosition = {
  6706. x: evt.clientX,
  6707. y: evt.clientY
  6708. };
  6709. if (!noPreventDefault) {
  6710. evt.preventDefault();
  6711. }
  6712. };
  6713. this._onMouseMove = function (evt) {
  6714. if (!engine.isPointerLock) {
  6715. return;
  6716. }
  6717. // return pinch is started
  6718. if (pinchStarted) {
  6719. return;
  6720. }
  6721. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6722. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6723. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6724. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6725. if (!noPreventDefault) {
  6726. evt.preventDefault();
  6727. }
  6728. };
  6729. this._wheel = function (event) {
  6730. var delta = 0;
  6731. if (event.wheelDelta) {
  6732. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6733. } else if (event.detail) {
  6734. delta = -event.detail / _this.wheelPrecision;
  6735. }
  6736. if (delta)
  6737. _this.inertialRadiusOffset += delta;
  6738. if (event.preventDefault) {
  6739. if (!noPreventDefault) {
  6740. event.preventDefault();
  6741. }
  6742. }
  6743. };
  6744. this._onKeyDown = function (evt) {
  6745. 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) {
  6746. var index = _this._keys.indexOf(evt.keyCode);
  6747. if (index === -1) {
  6748. _this._keys.push(evt.keyCode);
  6749. }
  6750. if (evt.preventDefault) {
  6751. if (!noPreventDefault) {
  6752. evt.preventDefault();
  6753. }
  6754. }
  6755. }
  6756. };
  6757. this._onKeyUp = function (evt) {
  6758. 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) {
  6759. var index = _this._keys.indexOf(evt.keyCode);
  6760. if (index >= 0) {
  6761. _this._keys.splice(index, 1);
  6762. }
  6763. if (evt.preventDefault) {
  6764. if (!noPreventDefault) {
  6765. evt.preventDefault();
  6766. }
  6767. }
  6768. }
  6769. };
  6770. this._onLostFocus = function () {
  6771. _this._keys = [];
  6772. pointerId = null;
  6773. };
  6774. this._onGestureStart = function (e) {
  6775. if (window.MSGesture === undefined) {
  6776. return;
  6777. }
  6778. if (!_this._MSGestureHandler) {
  6779. _this._MSGestureHandler = new MSGesture();
  6780. _this._MSGestureHandler.target = element;
  6781. }
  6782. _this._MSGestureHandler.addPointer(e.pointerId);
  6783. };
  6784. this._onGesture = function (e) {
  6785. _this.radius *= e.scale;
  6786. if (e.preventDefault) {
  6787. if (!noPreventDefault) {
  6788. e.stopPropagation();
  6789. e.preventDefault();
  6790. }
  6791. }
  6792. };
  6793. this._reset = function () {
  6794. _this._keys = [];
  6795. _this.inertialAlphaOffset = 0;
  6796. _this.inertialBetaOffset = 0;
  6797. _this.inertialRadiusOffset = 0;
  6798. previousPosition = null;
  6799. pointerId = null;
  6800. };
  6801. this._touchStart = function (event) {
  6802. if (event.touches.length == 2) {
  6803. //-- start pinch if two fingers on the screen
  6804. pinchStarted = true;
  6805. _this._pinchStart(event);
  6806. }
  6807. };
  6808. this._touchMove = function (event) {
  6809. if (pinchStarted) {
  6810. //-- make scaling
  6811. _this._pinchMove(event);
  6812. }
  6813. };
  6814. this._touchEnd = function (event) {
  6815. if (pinchStarted) {
  6816. //-- end of pinch
  6817. _this._pinchEnd(event);
  6818. }
  6819. };
  6820. this._pinchStart = function (event) {
  6821. // save origin touch point
  6822. pinchPointX1 = event.touches[0].clientX;
  6823. pinchPointX2 = event.touches[1].clientX;
  6824. // block the camera
  6825. // if not it rotate around target during pinch
  6826. pinchStarted = true;
  6827. };
  6828. this._pinchMove = function (event) {
  6829. // variable for new camera's radius
  6830. var delta = 0;
  6831. // variables to know if pinch open or pinch close
  6832. var direction = 1;
  6833. var distanceXOrigine, distanceXNow;
  6834. if (event.touches.length != 2)
  6835. return;
  6836. // calculate absolute distances of the two fingers
  6837. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6838. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6839. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6840. if (distanceXNow < distanceXOrigine) {
  6841. direction = -1;
  6842. }
  6843. // calculate new radius
  6844. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6845. // set new radius
  6846. _this.inertialRadiusOffset += delta;
  6847. // save origin touch point
  6848. pinchPointX1 = event.touches[0].clientX;
  6849. pinchPointX2 = event.touches[1].clientX;
  6850. };
  6851. this._pinchEnd = function (event) {
  6852. // cancel pinch and deblock camera rotation
  6853. pinchStarted = false;
  6854. };
  6855. }
  6856. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6857. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6858. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6859. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6860. element.addEventListener("mousemove", this._onMouseMove, false);
  6861. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6862. element.addEventListener("MSGestureChange", this._onGesture, false);
  6863. element.addEventListener('mousewheel', this._wheel, false);
  6864. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6865. // pinch
  6866. element.addEventListener('touchstart', this._touchStart, false);
  6867. element.addEventListener('touchmove', this._touchMove, false);
  6868. element.addEventListener('touchend', this._touchEnd, false);
  6869. BABYLON.Tools.RegisterTopRootEvents([
  6870. { name: "keydown", handler: this._onKeyDown },
  6871. { name: "keyup", handler: this._onKeyUp },
  6872. { name: "blur", handler: this._onLostFocus }
  6873. ]);
  6874. };
  6875. ArcRotateCamera.prototype.detachControl = function (element) {
  6876. if (this._attachedElement != element) {
  6877. return;
  6878. }
  6879. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6880. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6881. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6882. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6883. element.removeEventListener("mousemove", this._onMouseMove);
  6884. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6885. element.removeEventListener("MSGestureChange", this._onGesture);
  6886. element.removeEventListener('mousewheel', this._wheel);
  6887. element.removeEventListener('DOMMouseScroll', this._wheel);
  6888. // pinch
  6889. element.removeEventListener('touchstart', this._touchStart);
  6890. element.removeEventListener('touchmove', this._touchMove);
  6891. element.removeEventListener('touchend', this._touchEnd);
  6892. BABYLON.Tools.UnregisterTopRootEvents([
  6893. { name: "keydown", handler: this._onKeyDown },
  6894. { name: "keyup", handler: this._onKeyUp },
  6895. { name: "blur", handler: this._onLostFocus }
  6896. ]);
  6897. this._MSGestureHandler = null;
  6898. this._attachedElement = null;
  6899. if (this._reset) {
  6900. this._reset();
  6901. }
  6902. };
  6903. ArcRotateCamera.prototype._update = function () {
  6904. for (var index = 0; index < this._keys.length; index++) {
  6905. var keyCode = this._keys[index];
  6906. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6907. this.inertialAlphaOffset -= 0.01;
  6908. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6909. this.inertialBetaOffset -= 0.01;
  6910. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6911. this.inertialAlphaOffset += 0.01;
  6912. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6913. this.inertialBetaOffset += 0.01;
  6914. }
  6915. }
  6916. // Inertia
  6917. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6918. this.alpha += this.inertialAlphaOffset;
  6919. this.beta += this.inertialBetaOffset;
  6920. this.radius -= this.inertialRadiusOffset;
  6921. this.inertialAlphaOffset *= this.inertia;
  6922. this.inertialBetaOffset *= this.inertia;
  6923. this.inertialRadiusOffset *= this.inertia;
  6924. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6925. this.inertialAlphaOffset = 0;
  6926. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6927. this.inertialBetaOffset = 0;
  6928. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6929. this.inertialRadiusOffset = 0;
  6930. }
  6931. // Limits
  6932. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6933. this.alpha = this.lowerAlphaLimit;
  6934. }
  6935. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6936. this.alpha = this.upperAlphaLimit;
  6937. }
  6938. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6939. this.beta = this.lowerBetaLimit;
  6940. }
  6941. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6942. this.beta = this.upperBetaLimit;
  6943. }
  6944. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6945. this.radius = this.lowerRadiusLimit;
  6946. }
  6947. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6948. this.radius = this.upperRadiusLimit;
  6949. }
  6950. };
  6951. ArcRotateCamera.prototype.setPosition = function (position) {
  6952. var radiusv3 = position.subtract(this._getTargetPosition());
  6953. this.radius = radiusv3.length();
  6954. // Alpha
  6955. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6956. if (radiusv3.z < 0) {
  6957. this.alpha = 2 * Math.PI - this.alpha;
  6958. }
  6959. // Beta
  6960. this.beta = Math.acos(radiusv3.y / this.radius);
  6961. };
  6962. ArcRotateCamera.prototype._getViewMatrix = function () {
  6963. // Compute
  6964. var cosa = Math.cos(this.alpha);
  6965. var sina = Math.sin(this.alpha);
  6966. var cosb = Math.cos(this.beta);
  6967. var sinb = Math.sin(this.beta);
  6968. var target = this._getTargetPosition();
  6969. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6970. if (this.checkCollisions) {
  6971. this._collider.radius = this.collisionRadius;
  6972. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6973. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6974. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6975. this.position.copyFrom(this._previousPosition);
  6976. this.alpha = this._previousAlpha;
  6977. this.beta = this._previousBeta;
  6978. this.radius = this._previousRadius;
  6979. if (this.onCollide) {
  6980. this.onCollide(this._collider.collidedMesh);
  6981. }
  6982. }
  6983. }
  6984. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6985. this._previousAlpha = this.alpha;
  6986. this._previousBeta = this.beta;
  6987. this._previousRadius = this.radius;
  6988. this._previousPosition.copyFrom(this.position);
  6989. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6990. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6991. return this._viewMatrix;
  6992. };
  6993. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6994. meshes = meshes || this.getScene().meshes;
  6995. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6996. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6997. this.radius = distance * this.zoomOnFactor;
  6998. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6999. };
  7000. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7001. var meshesOrMinMaxVector;
  7002. var distance;
  7003. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7004. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7005. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7006. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7007. } else {
  7008. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7009. distance = meshesOrMinMaxVectorAndDistance.distance;
  7010. }
  7011. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7012. this.maxZ = distance * 2;
  7013. };
  7014. return ArcRotateCamera;
  7015. })(BABYLON.Camera);
  7016. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7017. })(BABYLON || (BABYLON = {}));
  7018. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7019. var BABYLON;
  7020. (function (BABYLON) {
  7021. var Scene = (function () {
  7022. // Constructor
  7023. function Scene(engine) {
  7024. // Members
  7025. this.autoClear = true;
  7026. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7027. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7028. this.forceWireframe = false;
  7029. this.forcePointsCloud = false;
  7030. this.forceShowBoundingBoxes = false;
  7031. this.animationsEnabled = true;
  7032. this.cameraToUseForPointers = null;
  7033. // Fog
  7034. this.fogEnabled = true;
  7035. this.fogMode = Scene.FOGMODE_NONE;
  7036. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7037. this.fogDensity = 0.1;
  7038. this.fogStart = 0;
  7039. this.fogEnd = 1000.0;
  7040. // Lights
  7041. this.shadowsEnabled = true;
  7042. this.lightsEnabled = true;
  7043. this.lights = new Array();
  7044. // Cameras
  7045. this.cameras = new Array();
  7046. this.activeCameras = new Array();
  7047. // Meshes
  7048. this.meshes = new Array();
  7049. // Geometries
  7050. this._geometries = new Array();
  7051. this.materials = new Array();
  7052. this.multiMaterials = new Array();
  7053. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7054. // Textures
  7055. this.texturesEnabled = true;
  7056. this.textures = new Array();
  7057. // Particles
  7058. this.particlesEnabled = true;
  7059. this.particleSystems = new Array();
  7060. // Sprites
  7061. this.spriteManagers = new Array();
  7062. // Layers
  7063. this.layers = new Array();
  7064. // Skeletons
  7065. this.skeletonsEnabled = true;
  7066. this.skeletons = new Array();
  7067. // Lens flares
  7068. this.lensFlaresEnabled = true;
  7069. this.lensFlareSystems = new Array();
  7070. // Collisions
  7071. this.collisionsEnabled = true;
  7072. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7073. // Postprocesses
  7074. this.postProcessesEnabled = true;
  7075. // Customs render targets
  7076. this.renderTargetsEnabled = true;
  7077. this.customRenderTargets = new Array();
  7078. // Imported meshes
  7079. this.importedMeshesFiles = new Array();
  7080. this._actionManagers = new Array();
  7081. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7082. // Procedural textures
  7083. this.proceduralTexturesEnabled = true;
  7084. this._proceduralTextures = new Array();
  7085. this.soundTracks = new Array();
  7086. this._totalVertices = 0;
  7087. this._activeVertices = 0;
  7088. this._activeParticles = 0;
  7089. this._lastFrameDuration = 0;
  7090. this._evaluateActiveMeshesDuration = 0;
  7091. this._renderTargetsDuration = 0;
  7092. this._particlesDuration = 0;
  7093. this._renderDuration = 0;
  7094. this._spritesDuration = 0;
  7095. this._animationRatio = 0;
  7096. this._renderId = 0;
  7097. this._executeWhenReadyTimeoutId = -1;
  7098. this._toBeDisposed = new BABYLON.SmartArray(256);
  7099. this._onReadyCallbacks = new Array();
  7100. this._pendingData = [];
  7101. this._onBeforeRenderCallbacks = new Array();
  7102. this._onAfterRenderCallbacks = new Array();
  7103. this._activeMeshes = new BABYLON.SmartArray(256);
  7104. this._processedMaterials = new BABYLON.SmartArray(256);
  7105. this._renderTargets = new BABYLON.SmartArray(256);
  7106. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7107. this._activeSkeletons = new BABYLON.SmartArray(32);
  7108. this._activeBones = 0;
  7109. this._activeAnimatables = new Array();
  7110. this._transformMatrix = BABYLON.Matrix.Zero();
  7111. this._scaledPosition = BABYLON.Vector3.Zero();
  7112. this._scaledVelocity = BABYLON.Vector3.Zero();
  7113. this._engine = engine;
  7114. engine.scenes.push(this);
  7115. this._renderingManager = new BABYLON.RenderingManager(this);
  7116. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7117. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7118. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7119. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7120. this.attachControl();
  7121. this._debugLayer = new BABYLON.DebugLayer(this);
  7122. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7123. }
  7124. Object.defineProperty(Scene.prototype, "debugLayer", {
  7125. // Properties
  7126. get: function () {
  7127. return this._debugLayer;
  7128. },
  7129. enumerable: true,
  7130. configurable: true
  7131. });
  7132. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7133. get: function () {
  7134. return this._meshUnderPointer;
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. Object.defineProperty(Scene.prototype, "pointerX", {
  7140. get: function () {
  7141. return this._pointerX;
  7142. },
  7143. enumerable: true,
  7144. configurable: true
  7145. });
  7146. Object.defineProperty(Scene.prototype, "pointerY", {
  7147. get: function () {
  7148. return this._pointerY;
  7149. },
  7150. enumerable: true,
  7151. configurable: true
  7152. });
  7153. Scene.prototype.getCachedMaterial = function () {
  7154. return this._cachedMaterial;
  7155. };
  7156. Scene.prototype.getBoundingBoxRenderer = function () {
  7157. return this._boundingBoxRenderer;
  7158. };
  7159. Scene.prototype.getOutlineRenderer = function () {
  7160. return this._outlineRenderer;
  7161. };
  7162. Scene.prototype.getEngine = function () {
  7163. return this._engine;
  7164. };
  7165. Scene.prototype.getTotalVertices = function () {
  7166. return this._totalVertices;
  7167. };
  7168. Scene.prototype.getActiveVertices = function () {
  7169. return this._activeVertices;
  7170. };
  7171. Scene.prototype.getActiveParticles = function () {
  7172. return this._activeParticles;
  7173. };
  7174. Scene.prototype.getActiveBones = function () {
  7175. return this._activeBones;
  7176. };
  7177. // Stats
  7178. Scene.prototype.getLastFrameDuration = function () {
  7179. return this._lastFrameDuration;
  7180. };
  7181. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7182. return this._evaluateActiveMeshesDuration;
  7183. };
  7184. Scene.prototype.getActiveMeshes = function () {
  7185. return this._activeMeshes;
  7186. };
  7187. Scene.prototype.getRenderTargetsDuration = function () {
  7188. return this._renderTargetsDuration;
  7189. };
  7190. Scene.prototype.getRenderDuration = function () {
  7191. return this._renderDuration;
  7192. };
  7193. Scene.prototype.getParticlesDuration = function () {
  7194. return this._particlesDuration;
  7195. };
  7196. Scene.prototype.getSpritesDuration = function () {
  7197. return this._spritesDuration;
  7198. };
  7199. Scene.prototype.getAnimationRatio = function () {
  7200. return this._animationRatio;
  7201. };
  7202. Scene.prototype.getRenderId = function () {
  7203. return this._renderId;
  7204. };
  7205. Scene.prototype._updatePointerPosition = function (evt) {
  7206. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7207. this._pointerX = evt.clientX - canvasRect.left;
  7208. this._pointerY = evt.clientY - canvasRect.top;
  7209. if (this.cameraToUseForPointers) {
  7210. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7211. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7212. }
  7213. };
  7214. // Pointers handling
  7215. Scene.prototype.attachControl = function () {
  7216. var _this = this;
  7217. this._onPointerMove = function (evt) {
  7218. var canvas = _this._engine.getRenderingCanvas();
  7219. _this._updatePointerPosition(evt);
  7220. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7221. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7222. }, false, _this.cameraToUseForPointers);
  7223. if (pickResult.hit) {
  7224. _this._meshUnderPointer = pickResult.pickedMesh;
  7225. _this.setPointerOverMesh(pickResult.pickedMesh);
  7226. canvas.style.cursor = "pointer";
  7227. } else {
  7228. _this.setPointerOverMesh(null);
  7229. canvas.style.cursor = "";
  7230. _this._meshUnderPointer = null;
  7231. }
  7232. };
  7233. this._onPointerDown = function (evt) {
  7234. var predicate = null;
  7235. if (!_this.onPointerDown) {
  7236. predicate = function (mesh) {
  7237. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7238. };
  7239. }
  7240. _this._updatePointerPosition(evt);
  7241. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7242. if (pickResult.hit) {
  7243. if (pickResult.pickedMesh.actionManager) {
  7244. switch (evt.button) {
  7245. case 0:
  7246. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7247. break;
  7248. case 1:
  7249. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7250. break;
  7251. case 2:
  7252. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7253. break;
  7254. }
  7255. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7256. }
  7257. }
  7258. if (_this.onPointerDown) {
  7259. _this.onPointerDown(evt, pickResult);
  7260. }
  7261. };
  7262. this._onKeyDown = function (evt) {
  7263. if (_this.actionManager) {
  7264. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7265. }
  7266. };
  7267. this._onKeyUp = function (evt) {
  7268. if (_this.actionManager) {
  7269. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7270. }
  7271. };
  7272. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7273. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7274. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7275. window.addEventListener("keydown", this._onKeyDown, false);
  7276. window.addEventListener("keyup", this._onKeyUp, false);
  7277. };
  7278. Scene.prototype.detachControl = function () {
  7279. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7280. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7281. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7282. window.removeEventListener("keydown", this._onKeyDown);
  7283. window.removeEventListener("keyup", this._onKeyUp);
  7284. };
  7285. // Ready
  7286. Scene.prototype.isReady = function () {
  7287. if (this._pendingData.length > 0) {
  7288. return false;
  7289. }
  7290. for (var index = 0; index < this._geometries.length; index++) {
  7291. var geometry = this._geometries[index];
  7292. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7293. return false;
  7294. }
  7295. }
  7296. for (index = 0; index < this.meshes.length; index++) {
  7297. var mesh = this.meshes[index];
  7298. if (!mesh.isReady()) {
  7299. return false;
  7300. }
  7301. var mat = mesh.material;
  7302. if (mat) {
  7303. if (!mat.isReady(mesh)) {
  7304. return false;
  7305. }
  7306. }
  7307. }
  7308. return true;
  7309. };
  7310. Scene.prototype.resetCachedMaterial = function () {
  7311. this._cachedMaterial = null;
  7312. };
  7313. Scene.prototype.registerBeforeRender = function (func) {
  7314. this._onBeforeRenderCallbacks.push(func);
  7315. };
  7316. Scene.prototype.unregisterBeforeRender = function (func) {
  7317. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7318. if (index > -1) {
  7319. this._onBeforeRenderCallbacks.splice(index, 1);
  7320. }
  7321. };
  7322. Scene.prototype.registerAfterRender = function (func) {
  7323. this._onAfterRenderCallbacks.push(func);
  7324. };
  7325. Scene.prototype.unregisterAfterRender = function (func) {
  7326. var index = this._onAfterRenderCallbacks.indexOf(func);
  7327. if (index > -1) {
  7328. this._onAfterRenderCallbacks.splice(index, 1);
  7329. }
  7330. };
  7331. Scene.prototype._addPendingData = function (data) {
  7332. this._pendingData.push(data);
  7333. };
  7334. Scene.prototype._removePendingData = function (data) {
  7335. var index = this._pendingData.indexOf(data);
  7336. if (index !== -1) {
  7337. this._pendingData.splice(index, 1);
  7338. }
  7339. };
  7340. Scene.prototype.getWaitingItemsCount = function () {
  7341. return this._pendingData.length;
  7342. };
  7343. Scene.prototype.executeWhenReady = function (func) {
  7344. var _this = this;
  7345. this._onReadyCallbacks.push(func);
  7346. if (this._executeWhenReadyTimeoutId !== -1) {
  7347. return;
  7348. }
  7349. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7350. _this._checkIsReady();
  7351. }, 150);
  7352. };
  7353. Scene.prototype._checkIsReady = function () {
  7354. var _this = this;
  7355. if (this.isReady()) {
  7356. this._onReadyCallbacks.forEach(function (func) {
  7357. func();
  7358. });
  7359. this._onReadyCallbacks = [];
  7360. this._executeWhenReadyTimeoutId = -1;
  7361. return;
  7362. }
  7363. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7364. _this._checkIsReady();
  7365. }, 150);
  7366. };
  7367. // Animations
  7368. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7369. if (speedRatio === undefined) {
  7370. speedRatio = 1.0;
  7371. }
  7372. this.stopAnimation(target);
  7373. if (!animatable) {
  7374. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7375. }
  7376. // Local animations
  7377. if (target.animations) {
  7378. animatable.appendAnimations(target, target.animations);
  7379. }
  7380. // Children animations
  7381. if (target.getAnimatables) {
  7382. var animatables = target.getAnimatables();
  7383. for (var index = 0; index < animatables.length; index++) {
  7384. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7385. }
  7386. }
  7387. return animatable;
  7388. };
  7389. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7390. if (speedRatio === undefined) {
  7391. speedRatio = 1.0;
  7392. }
  7393. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7394. return animatable;
  7395. };
  7396. Scene.prototype.getAnimatableByTarget = function (target) {
  7397. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7398. if (this._activeAnimatables[index].target === target) {
  7399. return this._activeAnimatables[index];
  7400. }
  7401. }
  7402. return null;
  7403. };
  7404. Scene.prototype.stopAnimation = function (target) {
  7405. var animatable = this.getAnimatableByTarget(target);
  7406. if (animatable) {
  7407. animatable.stop();
  7408. }
  7409. };
  7410. Scene.prototype._animate = function () {
  7411. if (!this.animationsEnabled) {
  7412. return;
  7413. }
  7414. if (!this._animationStartDate) {
  7415. this._animationStartDate = BABYLON.Tools.Now;
  7416. }
  7417. // Getting time
  7418. var now = BABYLON.Tools.Now;
  7419. var delay = now - this._animationStartDate;
  7420. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7421. if (!this._activeAnimatables[index]._animate(delay)) {
  7422. this._activeAnimatables.splice(index, 1);
  7423. index--;
  7424. }
  7425. }
  7426. };
  7427. // Matrix
  7428. Scene.prototype.getViewMatrix = function () {
  7429. return this._viewMatrix;
  7430. };
  7431. Scene.prototype.getProjectionMatrix = function () {
  7432. return this._projectionMatrix;
  7433. };
  7434. Scene.prototype.getTransformMatrix = function () {
  7435. return this._transformMatrix;
  7436. };
  7437. Scene.prototype.setTransformMatrix = function (view, projection) {
  7438. this._viewMatrix = view;
  7439. this._projectionMatrix = projection;
  7440. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7441. };
  7442. // Methods
  7443. Scene.prototype.setActiveCameraByID = function (id) {
  7444. var camera = this.getCameraByID(id);
  7445. if (camera) {
  7446. this.activeCamera = camera;
  7447. return camera;
  7448. }
  7449. return null;
  7450. };
  7451. Scene.prototype.setActiveCameraByName = function (name) {
  7452. var camera = this.getCameraByName(name);
  7453. if (camera) {
  7454. this.activeCamera = camera;
  7455. return camera;
  7456. }
  7457. return null;
  7458. };
  7459. Scene.prototype.getMaterialByID = function (id) {
  7460. for (var index = 0; index < this.materials.length; index++) {
  7461. if (this.materials[index].id === id) {
  7462. return this.materials[index];
  7463. }
  7464. }
  7465. return null;
  7466. };
  7467. Scene.prototype.getMaterialByName = function (name) {
  7468. for (var index = 0; index < this.materials.length; index++) {
  7469. if (this.materials[index].name === name) {
  7470. return this.materials[index];
  7471. }
  7472. }
  7473. return null;
  7474. };
  7475. Scene.prototype.getCameraByID = function (id) {
  7476. for (var index = 0; index < this.cameras.length; index++) {
  7477. if (this.cameras[index].id === id) {
  7478. return this.cameras[index];
  7479. }
  7480. }
  7481. return null;
  7482. };
  7483. Scene.prototype.getCameraByName = function (name) {
  7484. for (var index = 0; index < this.cameras.length; index++) {
  7485. if (this.cameras[index].name === name) {
  7486. return this.cameras[index];
  7487. }
  7488. }
  7489. return null;
  7490. };
  7491. Scene.prototype.getLightByName = function (name) {
  7492. for (var index = 0; index < this.lights.length; index++) {
  7493. if (this.lights[index].name === name) {
  7494. return this.lights[index];
  7495. }
  7496. }
  7497. return null;
  7498. };
  7499. Scene.prototype.getLightByID = function (id) {
  7500. for (var index = 0; index < this.lights.length; index++) {
  7501. if (this.lights[index].id === id) {
  7502. return this.lights[index];
  7503. }
  7504. }
  7505. return null;
  7506. };
  7507. Scene.prototype.getGeometryByID = function (id) {
  7508. for (var index = 0; index < this._geometries.length; index++) {
  7509. if (this._geometries[index].id === id) {
  7510. return this._geometries[index];
  7511. }
  7512. }
  7513. return null;
  7514. };
  7515. Scene.prototype.pushGeometry = function (geometry, force) {
  7516. if (!force && this.getGeometryByID(geometry.id)) {
  7517. return false;
  7518. }
  7519. this._geometries.push(geometry);
  7520. return true;
  7521. };
  7522. Scene.prototype.getGeometries = function () {
  7523. return this._geometries;
  7524. };
  7525. Scene.prototype.getMeshByID = function (id) {
  7526. for (var index = 0; index < this.meshes.length; index++) {
  7527. if (this.meshes[index].id === id) {
  7528. return this.meshes[index];
  7529. }
  7530. }
  7531. return null;
  7532. };
  7533. Scene.prototype.getLastMeshByID = function (id) {
  7534. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7535. if (this.meshes[index].id === id) {
  7536. return this.meshes[index];
  7537. }
  7538. }
  7539. return null;
  7540. };
  7541. Scene.prototype.getLastEntryByID = function (id) {
  7542. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7543. if (this.meshes[index].id === id) {
  7544. return this.meshes[index];
  7545. }
  7546. }
  7547. for (index = this.cameras.length - 1; index >= 0; index--) {
  7548. if (this.cameras[index].id === id) {
  7549. return this.cameras[index];
  7550. }
  7551. }
  7552. for (index = this.lights.length - 1; index >= 0; index--) {
  7553. if (this.lights[index].id === id) {
  7554. return this.lights[index];
  7555. }
  7556. }
  7557. return null;
  7558. };
  7559. Scene.prototype.getMeshByName = function (name) {
  7560. for (var index = 0; index < this.meshes.length; index++) {
  7561. if (this.meshes[index].name === name) {
  7562. return this.meshes[index];
  7563. }
  7564. }
  7565. return null;
  7566. };
  7567. Scene.prototype.getLastSkeletonByID = function (id) {
  7568. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7569. if (this.skeletons[index].id === id) {
  7570. return this.skeletons[index];
  7571. }
  7572. }
  7573. return null;
  7574. };
  7575. Scene.prototype.getSkeletonById = function (id) {
  7576. for (var index = 0; index < this.skeletons.length; index++) {
  7577. if (this.skeletons[index].id === id) {
  7578. return this.skeletons[index];
  7579. }
  7580. }
  7581. return null;
  7582. };
  7583. Scene.prototype.getSkeletonByName = function (name) {
  7584. for (var index = 0; index < this.skeletons.length; index++) {
  7585. if (this.skeletons[index].name === name) {
  7586. return this.skeletons[index];
  7587. }
  7588. }
  7589. return null;
  7590. };
  7591. Scene.prototype.isActiveMesh = function (mesh) {
  7592. return (this._activeMeshes.indexOf(mesh) !== -1);
  7593. };
  7594. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7595. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7596. var material = subMesh.getMaterial();
  7597. if (mesh.showSubMeshesBoundingBox) {
  7598. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7599. }
  7600. if (material) {
  7601. // Render targets
  7602. if (material.getRenderTargetTextures) {
  7603. if (this._processedMaterials.indexOf(material) === -1) {
  7604. this._processedMaterials.push(material);
  7605. this._renderTargets.concat(material.getRenderTargetTextures());
  7606. }
  7607. }
  7608. // Dispatch
  7609. this._activeVertices += subMesh.indexCount;
  7610. this._renderingManager.dispatch(subMesh);
  7611. }
  7612. }
  7613. };
  7614. Scene.prototype._evaluateActiveMeshes = function () {
  7615. this._activeMeshes.reset();
  7616. this._renderingManager.reset();
  7617. this._processedMaterials.reset();
  7618. this._activeParticleSystems.reset();
  7619. this._activeSkeletons.reset();
  7620. this._boundingBoxRenderer.reset();
  7621. if (!this._frustumPlanes) {
  7622. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7623. } else {
  7624. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7625. }
  7626. // Meshes
  7627. var meshes;
  7628. var len;
  7629. if (this._selectionOctree) {
  7630. var selection = this._selectionOctree.select(this._frustumPlanes);
  7631. meshes = selection.data;
  7632. len = selection.length;
  7633. } else {
  7634. len = this.meshes.length;
  7635. meshes = this.meshes;
  7636. }
  7637. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7638. var mesh = meshes[meshIndex];
  7639. if (mesh.isBlocked) {
  7640. continue;
  7641. }
  7642. this._totalVertices += mesh.getTotalVertices();
  7643. if (!mesh.isReady()) {
  7644. continue;
  7645. }
  7646. mesh.computeWorldMatrix();
  7647. // Intersections
  7648. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7649. this._meshesForIntersections.pushNoDuplicate(mesh);
  7650. }
  7651. // Switch to current LOD
  7652. var meshLOD = mesh.getLOD(this.activeCamera);
  7653. if (!meshLOD) {
  7654. continue;
  7655. }
  7656. mesh._preActivate();
  7657. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7658. this._activeMeshes.push(mesh);
  7659. mesh._activate(this._renderId);
  7660. this._activeMesh(meshLOD);
  7661. }
  7662. }
  7663. // Particle systems
  7664. var beforeParticlesDate = BABYLON.Tools.Now;
  7665. if (this.particlesEnabled) {
  7666. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7667. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7668. var particleSystem = this.particleSystems[particleIndex];
  7669. if (!particleSystem.isStarted()) {
  7670. continue;
  7671. }
  7672. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7673. this._activeParticleSystems.push(particleSystem);
  7674. particleSystem.animate();
  7675. }
  7676. }
  7677. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7678. }
  7679. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7680. };
  7681. Scene.prototype._activeMesh = function (mesh) {
  7682. if (mesh.skeleton && this.skeletonsEnabled) {
  7683. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7684. }
  7685. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7686. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7687. }
  7688. if (mesh && mesh.subMeshes) {
  7689. // Submeshes Octrees
  7690. var len;
  7691. var subMeshes;
  7692. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7693. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7694. len = intersections.length;
  7695. subMeshes = intersections.data;
  7696. } else {
  7697. subMeshes = mesh.subMeshes;
  7698. len = subMeshes.length;
  7699. }
  7700. for (var subIndex = 0; subIndex < len; subIndex++) {
  7701. var subMesh = subMeshes[subIndex];
  7702. this._evaluateSubMesh(subMesh, mesh);
  7703. }
  7704. }
  7705. };
  7706. Scene.prototype.updateTransformMatrix = function (force) {
  7707. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7708. };
  7709. Scene.prototype._renderForCamera = function (camera) {
  7710. var engine = this._engine;
  7711. this.activeCamera = camera;
  7712. if (!this.activeCamera)
  7713. throw new Error("Active camera not set");
  7714. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7715. // Viewport
  7716. engine.setViewport(this.activeCamera.viewport);
  7717. // Camera
  7718. this._renderId++;
  7719. this.updateTransformMatrix();
  7720. if (this.beforeCameraRender) {
  7721. this.beforeCameraRender(this.activeCamera);
  7722. }
  7723. // Meshes
  7724. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7725. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7726. this._evaluateActiveMeshes();
  7727. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7728. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7729. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7730. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7731. skeleton.prepare();
  7732. this._activeBones += skeleton.bones.length;
  7733. }
  7734. // Render targets
  7735. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7736. if (this.renderTargetsEnabled) {
  7737. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7738. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7739. var renderTarget = this._renderTargets.data[renderIndex];
  7740. if (renderTarget._shouldRender()) {
  7741. this._renderId++;
  7742. renderTarget.render();
  7743. }
  7744. }
  7745. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7746. this._renderId++;
  7747. }
  7748. if (this._renderTargets.length > 0) {
  7749. engine.restoreDefaultFramebuffer();
  7750. }
  7751. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7752. // Prepare Frame
  7753. this.postProcessManager._prepareFrame();
  7754. var beforeRenderDate = BABYLON.Tools.Now;
  7755. // Backgrounds
  7756. if (this.layers.length) {
  7757. engine.setDepthBuffer(false);
  7758. var layerIndex;
  7759. var layer;
  7760. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7761. layer = this.layers[layerIndex];
  7762. if (layer.isBackground) {
  7763. layer.render();
  7764. }
  7765. }
  7766. engine.setDepthBuffer(true);
  7767. }
  7768. // Render
  7769. BABYLON.Tools.StartPerformanceCounter("Main render");
  7770. this._renderingManager.render(null, null, true, true);
  7771. BABYLON.Tools.EndPerformanceCounter("Main render");
  7772. // Bounding boxes
  7773. this._boundingBoxRenderer.render();
  7774. // Lens flares
  7775. if (this.lensFlaresEnabled) {
  7776. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7777. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7778. this.lensFlareSystems[lensFlareSystemIndex].render();
  7779. }
  7780. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7781. }
  7782. // Foregrounds
  7783. if (this.layers.length) {
  7784. engine.setDepthBuffer(false);
  7785. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7786. layer = this.layers[layerIndex];
  7787. if (!layer.isBackground) {
  7788. layer.render();
  7789. }
  7790. }
  7791. engine.setDepthBuffer(true);
  7792. }
  7793. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7794. // Finalize frame
  7795. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7796. // Update camera
  7797. this.activeCamera._updateFromScene();
  7798. // Reset some special arrays
  7799. this._renderTargets.reset();
  7800. if (this.afterCameraRender) {
  7801. this.afterCameraRender(this.activeCamera);
  7802. }
  7803. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7804. };
  7805. Scene.prototype._processSubCameras = function (camera) {
  7806. if (camera.subCameras.length === 0) {
  7807. this._renderForCamera(camera);
  7808. return;
  7809. }
  7810. for (var index = 0; index < camera.subCameras.length; index++) {
  7811. this._renderForCamera(camera.subCameras[index]);
  7812. }
  7813. this.activeCamera = camera;
  7814. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7815. // Update camera
  7816. this.activeCamera._updateFromScene();
  7817. };
  7818. Scene.prototype._checkIntersections = function () {
  7819. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7820. var sourceMesh = this._meshesForIntersections.data[index];
  7821. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7822. var action = sourceMesh.actionManager.actions[actionIndex];
  7823. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7824. var otherMesh = action.getTriggerParameter();
  7825. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7826. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7827. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7828. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7829. sourceMesh._intersectionsInProgress.push(otherMesh);
  7830. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7831. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7832. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7833. if (indexOfOther > -1) {
  7834. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7835. }
  7836. }
  7837. }
  7838. }
  7839. }
  7840. };
  7841. Scene.prototype.render = function () {
  7842. var startDate = BABYLON.Tools.Now;
  7843. this._particlesDuration = 0;
  7844. this._spritesDuration = 0;
  7845. this._activeParticles = 0;
  7846. this._renderDuration = 0;
  7847. this._renderTargetsDuration = 0;
  7848. this._evaluateActiveMeshesDuration = 0;
  7849. this._totalVertices = 0;
  7850. this._activeVertices = 0;
  7851. this._activeBones = 0;
  7852. this.getEngine().resetDrawCalls();
  7853. this._meshesForIntersections.reset();
  7854. this.resetCachedMaterial();
  7855. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7856. // Actions
  7857. if (this.actionManager) {
  7858. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7859. }
  7860. // Before render
  7861. if (this.beforeRender) {
  7862. this.beforeRender();
  7863. }
  7864. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7865. this._onBeforeRenderCallbacks[callbackIndex]();
  7866. }
  7867. // Animations
  7868. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7869. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7870. this._animate();
  7871. // Physics
  7872. if (this._physicsEngine) {
  7873. BABYLON.Tools.StartPerformanceCounter("Physics");
  7874. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7875. BABYLON.Tools.EndPerformanceCounter("Physics");
  7876. }
  7877. // Customs render targets
  7878. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7879. var engine = this.getEngine();
  7880. if (this.renderTargetsEnabled) {
  7881. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7882. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7883. var renderTarget = this.customRenderTargets[customIndex];
  7884. if (renderTarget._shouldRender()) {
  7885. this._renderId++;
  7886. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7887. if (!this.activeCamera)
  7888. throw new Error("Active camera not set");
  7889. // Viewport
  7890. engine.setViewport(this.activeCamera.viewport);
  7891. // Camera
  7892. this.updateTransformMatrix();
  7893. renderTarget.render();
  7894. }
  7895. }
  7896. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7897. this._renderId++;
  7898. }
  7899. if (this.customRenderTargets.length > 0) {
  7900. engine.restoreDefaultFramebuffer();
  7901. }
  7902. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7903. // Procedural textures
  7904. if (this.proceduralTexturesEnabled) {
  7905. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7906. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7907. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7908. if (proceduralTexture._shouldRender()) {
  7909. proceduralTexture.render();
  7910. }
  7911. }
  7912. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7913. }
  7914. // Clear
  7915. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7916. // Shadows
  7917. if (this.shadowsEnabled) {
  7918. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7919. var light = this.lights[lightIndex];
  7920. var shadowGenerator = light.getShadowGenerator();
  7921. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7922. this._renderTargets.push(shadowGenerator.getShadowMap());
  7923. }
  7924. }
  7925. }
  7926. // RenderPipeline
  7927. this.postProcessRenderPipelineManager.update();
  7928. // Multi-cameras?
  7929. if (this.activeCameras.length > 0) {
  7930. var currentRenderId = this._renderId;
  7931. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7932. this._renderId = currentRenderId;
  7933. this._processSubCameras(this.activeCameras[cameraIndex]);
  7934. }
  7935. } else {
  7936. if (!this.activeCamera) {
  7937. throw new Error("No camera defined");
  7938. }
  7939. this._processSubCameras(this.activeCamera);
  7940. }
  7941. // Intersection checks
  7942. this._checkIntersections();
  7943. // Update the audio listener attached to the camera
  7944. this._updateAudioParameters();
  7945. // After render
  7946. if (this.afterRender) {
  7947. this.afterRender();
  7948. }
  7949. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7950. this._onAfterRenderCallbacks[callbackIndex]();
  7951. }
  7952. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7953. this._toBeDisposed.data[index].dispose();
  7954. this._toBeDisposed[index] = null;
  7955. }
  7956. this._toBeDisposed.reset();
  7957. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7958. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7959. };
  7960. Scene.prototype._updateAudioParameters = function () {
  7961. var listeningCamera;
  7962. var audioEngine = this._engine.getAudioEngine();
  7963. if (this.activeCameras.length > 0) {
  7964. listeningCamera = this.activeCameras[0];
  7965. } else {
  7966. listeningCamera = this.activeCamera;
  7967. }
  7968. if (listeningCamera && audioEngine.canUseWebAudio) {
  7969. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7970. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7971. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7972. cameraDirection.normalize();
  7973. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7974. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7975. var sound = this.mainSoundTrack.soundCollection[i];
  7976. if (sound.useCustomAttenuation) {
  7977. sound.updateDistanceFromListener();
  7978. }
  7979. }
  7980. for (var i = 0; i < this.soundTracks.length; i++) {
  7981. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7982. var sound = this.soundTracks[i].soundCollection[j];
  7983. if (sound.useCustomAttenuation) {
  7984. sound.updateDistanceFromListener();
  7985. }
  7986. }
  7987. }
  7988. }
  7989. };
  7990. Scene.prototype.dispose = function () {
  7991. this.beforeRender = null;
  7992. this.afterRender = null;
  7993. this.skeletons = [];
  7994. this._boundingBoxRenderer.dispose();
  7995. // Debug layer
  7996. this.debugLayer.hide();
  7997. // Events
  7998. if (this.onDispose) {
  7999. this.onDispose();
  8000. }
  8001. this._onBeforeRenderCallbacks = [];
  8002. this._onAfterRenderCallbacks = [];
  8003. this.detachControl();
  8004. // Detach cameras
  8005. var canvas = this._engine.getRenderingCanvas();
  8006. var index;
  8007. for (index = 0; index < this.cameras.length; index++) {
  8008. this.cameras[index].detachControl(canvas);
  8009. }
  8010. while (this.lights.length) {
  8011. this.lights[0].dispose();
  8012. }
  8013. while (this.meshes.length) {
  8014. this.meshes[0].dispose(true);
  8015. }
  8016. while (this.cameras.length) {
  8017. this.cameras[0].dispose();
  8018. }
  8019. while (this.materials.length) {
  8020. this.materials[0].dispose();
  8021. }
  8022. while (this.particleSystems.length) {
  8023. this.particleSystems[0].dispose();
  8024. }
  8025. while (this.spriteManagers.length) {
  8026. this.spriteManagers[0].dispose();
  8027. }
  8028. while (this.layers.length) {
  8029. this.layers[0].dispose();
  8030. }
  8031. while (this.textures.length) {
  8032. this.textures[0].dispose();
  8033. }
  8034. // Post-processes
  8035. this.postProcessManager.dispose();
  8036. // Physics
  8037. if (this._physicsEngine) {
  8038. this.disablePhysicsEngine();
  8039. }
  8040. // Remove from engine
  8041. index = this._engine.scenes.indexOf(this);
  8042. if (index > -1) {
  8043. this._engine.scenes.splice(index, 1);
  8044. }
  8045. this._engine.wipeCaches();
  8046. };
  8047. // Collisions
  8048. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8049. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8050. position.divideToRef(collider.radius, this._scaledPosition);
  8051. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8052. collider.retry = 0;
  8053. collider.initialVelocity = this._scaledVelocity;
  8054. collider.initialPosition = this._scaledPosition;
  8055. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8056. finalPosition.multiplyInPlace(collider.radius);
  8057. };
  8058. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8059. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8060. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8061. if (collider.retry >= maximumRetry) {
  8062. finalPosition.copyFrom(position);
  8063. return;
  8064. }
  8065. collider._initialize(position, velocity, closeDistance);
  8066. for (var index = 0; index < this.meshes.length; index++) {
  8067. var mesh = this.meshes[index];
  8068. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8069. mesh._checkCollision(collider);
  8070. }
  8071. }
  8072. if (!collider.collisionFound) {
  8073. position.addToRef(velocity, finalPosition);
  8074. return;
  8075. }
  8076. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8077. collider._getResponse(position, velocity);
  8078. }
  8079. if (velocity.length() <= closeDistance) {
  8080. finalPosition.copyFrom(position);
  8081. return;
  8082. }
  8083. collider.retry++;
  8084. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8085. };
  8086. // Octrees
  8087. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8088. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8089. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8090. if (!this._selectionOctree) {
  8091. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8092. }
  8093. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8094. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8095. for (var index = 0; index < this.meshes.length; index++) {
  8096. var mesh = this.meshes[index];
  8097. mesh.computeWorldMatrix(true);
  8098. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8099. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8100. BABYLON.Tools.CheckExtends(minBox, min, max);
  8101. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8102. }
  8103. // Update octree
  8104. this._selectionOctree.update(min, max, this.meshes);
  8105. return this._selectionOctree;
  8106. };
  8107. // Picking
  8108. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8109. var engine = this._engine;
  8110. if (!camera) {
  8111. if (!this.activeCamera)
  8112. throw new Error("Active camera not set");
  8113. camera = this.activeCamera;
  8114. }
  8115. var cameraViewport = camera.viewport;
  8116. var viewport = cameraViewport.toGlobal(engine);
  8117. // Moving coordinates to local viewport world
  8118. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8119. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8120. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8121. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8122. };
  8123. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8124. var pickingInfo = null;
  8125. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8126. var mesh = this.meshes[meshIndex];
  8127. if (predicate) {
  8128. if (!predicate(mesh)) {
  8129. continue;
  8130. }
  8131. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8132. continue;
  8133. }
  8134. var world = mesh.getWorldMatrix();
  8135. var ray = rayFunction(world);
  8136. var result = mesh.intersects(ray, fastCheck);
  8137. if (!result || !result.hit)
  8138. continue;
  8139. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8140. continue;
  8141. pickingInfo = result;
  8142. if (fastCheck) {
  8143. break;
  8144. }
  8145. }
  8146. return pickingInfo || new BABYLON.PickingInfo();
  8147. };
  8148. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8149. var _this = this;
  8150. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8151. /// <param name="x">X position on screen</param>
  8152. /// <param name="y">Y position on screen</param>
  8153. /// <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>
  8154. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8155. /// <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>
  8156. return this._internalPick(function (world) {
  8157. return _this.createPickingRay(x, y, world, camera);
  8158. }, predicate, fastCheck);
  8159. };
  8160. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8161. var _this = this;
  8162. return this._internalPick(function (world) {
  8163. if (!_this._pickWithRayInverseMatrix) {
  8164. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8165. }
  8166. world.invertToRef(_this._pickWithRayInverseMatrix);
  8167. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8168. }, predicate, fastCheck);
  8169. };
  8170. Scene.prototype.setPointerOverMesh = function (mesh) {
  8171. if (this._pointerOverMesh === mesh) {
  8172. return;
  8173. }
  8174. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8175. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8176. }
  8177. this._pointerOverMesh = mesh;
  8178. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8179. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8180. }
  8181. };
  8182. Scene.prototype.getPointerOverMesh = function () {
  8183. return this._pointerOverMesh;
  8184. };
  8185. // Physics
  8186. Scene.prototype.getPhysicsEngine = function () {
  8187. return this._physicsEngine;
  8188. };
  8189. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8190. if (this._physicsEngine) {
  8191. return true;
  8192. }
  8193. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8194. if (!this._physicsEngine.isSupported()) {
  8195. this._physicsEngine = null;
  8196. return false;
  8197. }
  8198. this._physicsEngine._initialize(gravity);
  8199. return true;
  8200. };
  8201. Scene.prototype.disablePhysicsEngine = function () {
  8202. if (!this._physicsEngine) {
  8203. return;
  8204. }
  8205. this._physicsEngine.dispose();
  8206. this._physicsEngine = undefined;
  8207. };
  8208. Scene.prototype.isPhysicsEnabled = function () {
  8209. return this._physicsEngine !== undefined;
  8210. };
  8211. Scene.prototype.setGravity = function (gravity) {
  8212. if (!this._physicsEngine) {
  8213. return;
  8214. }
  8215. this._physicsEngine._setGravity(gravity);
  8216. };
  8217. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8218. if (parts.parts) {
  8219. options = parts;
  8220. parts = parts.parts;
  8221. }
  8222. if (!this._physicsEngine) {
  8223. return null;
  8224. }
  8225. for (var index = 0; index < parts.length; index++) {
  8226. var mesh = parts[index].mesh;
  8227. mesh._physicImpostor = parts[index].impostor;
  8228. mesh._physicsMass = options.mass / parts.length;
  8229. mesh._physicsFriction = options.friction;
  8230. mesh._physicRestitution = options.restitution;
  8231. }
  8232. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8233. };
  8234. //ANY
  8235. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8236. for (var index = 0; index < compound.parts.length; index++) {
  8237. var mesh = compound.parts[index].mesh;
  8238. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8239. this._physicsEngine._unregisterMesh(mesh);
  8240. }
  8241. };
  8242. // Tags
  8243. Scene.prototype._getByTags = function (list, tagsQuery) {
  8244. if (tagsQuery === undefined) {
  8245. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8246. return list;
  8247. }
  8248. var listByTags = [];
  8249. for (var i in list) {
  8250. var item = list[i];
  8251. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8252. listByTags.push(item);
  8253. }
  8254. }
  8255. return listByTags;
  8256. };
  8257. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8258. return this._getByTags(this.meshes, tagsQuery);
  8259. };
  8260. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8261. return this._getByTags(this.cameras, tagsQuery);
  8262. };
  8263. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8264. return this._getByTags(this.lights, tagsQuery);
  8265. };
  8266. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8267. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8268. };
  8269. Scene.FOGMODE_NONE = 0;
  8270. Scene.FOGMODE_EXP = 1;
  8271. Scene.FOGMODE_EXP2 = 2;
  8272. Scene.FOGMODE_LINEAR = 3;
  8273. Scene.MinDeltaTime = 1.0;
  8274. Scene.MaxDeltaTime = 1000.0;
  8275. return Scene;
  8276. })();
  8277. BABYLON.Scene = Scene;
  8278. })(BABYLON || (BABYLON = {}));
  8279. //# sourceMappingURL=babylon.scene.js.map
  8280. var BABYLON;
  8281. (function (BABYLON) {
  8282. var VertexBuffer = (function () {
  8283. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8284. if (engine instanceof BABYLON.Mesh) {
  8285. this._engine = engine.getScene().getEngine();
  8286. } else {
  8287. this._engine = engine;
  8288. }
  8289. this._updatable = updatable;
  8290. this._data = data;
  8291. if (!postponeInternalCreation) {
  8292. this.create();
  8293. }
  8294. this._kind = kind;
  8295. if (stride) {
  8296. this._strideSize = stride;
  8297. return;
  8298. }
  8299. switch (kind) {
  8300. case VertexBuffer.PositionKind:
  8301. this._strideSize = 3;
  8302. break;
  8303. case VertexBuffer.NormalKind:
  8304. this._strideSize = 3;
  8305. break;
  8306. case VertexBuffer.UVKind:
  8307. this._strideSize = 2;
  8308. break;
  8309. case VertexBuffer.UV2Kind:
  8310. this._strideSize = 2;
  8311. break;
  8312. case VertexBuffer.ColorKind:
  8313. this._strideSize = 4;
  8314. break;
  8315. case VertexBuffer.MatricesIndicesKind:
  8316. this._strideSize = 4;
  8317. break;
  8318. case VertexBuffer.MatricesWeightsKind:
  8319. this._strideSize = 4;
  8320. break;
  8321. }
  8322. }
  8323. // Properties
  8324. VertexBuffer.prototype.isUpdatable = function () {
  8325. return this._updatable;
  8326. };
  8327. VertexBuffer.prototype.getData = function () {
  8328. return this._data;
  8329. };
  8330. VertexBuffer.prototype.getBuffer = function () {
  8331. return this._buffer;
  8332. };
  8333. VertexBuffer.prototype.getStrideSize = function () {
  8334. return this._strideSize;
  8335. };
  8336. // Methods
  8337. VertexBuffer.prototype.create = function (data) {
  8338. if (!data && this._buffer) {
  8339. return;
  8340. }
  8341. data = data || this._data;
  8342. if (!this._buffer) {
  8343. if (this._updatable) {
  8344. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8345. } else {
  8346. this._buffer = this._engine.createVertexBuffer(data);
  8347. }
  8348. }
  8349. if (this._updatable) {
  8350. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8351. this._data = data;
  8352. }
  8353. };
  8354. VertexBuffer.prototype.update = function (data) {
  8355. this.create(data);
  8356. };
  8357. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8358. if (!this._buffer) {
  8359. return;
  8360. }
  8361. if (this._updatable) {
  8362. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8363. this._data = null;
  8364. }
  8365. };
  8366. VertexBuffer.prototype.dispose = function () {
  8367. if (!this._buffer) {
  8368. return;
  8369. }
  8370. if (this._engine._releaseBuffer(this._buffer)) {
  8371. this._buffer = null;
  8372. }
  8373. };
  8374. Object.defineProperty(VertexBuffer, "PositionKind", {
  8375. get: function () {
  8376. return VertexBuffer._PositionKind;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(VertexBuffer, "NormalKind", {
  8382. get: function () {
  8383. return VertexBuffer._NormalKind;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(VertexBuffer, "UVKind", {
  8389. get: function () {
  8390. return VertexBuffer._UVKind;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8396. get: function () {
  8397. return VertexBuffer._UV2Kind;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(VertexBuffer, "ColorKind", {
  8403. get: function () {
  8404. return VertexBuffer._ColorKind;
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8410. get: function () {
  8411. return VertexBuffer._MatricesIndicesKind;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8417. get: function () {
  8418. return VertexBuffer._MatricesWeightsKind;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. VertexBuffer._PositionKind = "position";
  8424. VertexBuffer._NormalKind = "normal";
  8425. VertexBuffer._UVKind = "uv";
  8426. VertexBuffer._UV2Kind = "uv2";
  8427. VertexBuffer._ColorKind = "color";
  8428. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8429. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8430. return VertexBuffer;
  8431. })();
  8432. BABYLON.VertexBuffer = VertexBuffer;
  8433. })(BABYLON || (BABYLON = {}));
  8434. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8435. var BABYLON;
  8436. (function (BABYLON) {
  8437. var AbstractMesh = (function (_super) {
  8438. __extends(AbstractMesh, _super);
  8439. function AbstractMesh(name, scene) {
  8440. _super.call(this, name, scene);
  8441. // Properties
  8442. this.position = new BABYLON.Vector3(0, 0, 0);
  8443. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8444. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8445. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8446. this.visibility = 1.0;
  8447. this.alphaIndex = Number.MAX_VALUE;
  8448. this.infiniteDistance = false;
  8449. this.isVisible = true;
  8450. this.isPickable = true;
  8451. this.showBoundingBox = false;
  8452. this.showSubMeshesBoundingBox = false;
  8453. this.onDispose = null;
  8454. this.checkCollisions = false;
  8455. this.isBlocker = false;
  8456. this.renderingGroupId = 0;
  8457. this.receiveShadows = false;
  8458. this.renderOutline = false;
  8459. this.outlineColor = BABYLON.Color3.Red();
  8460. this.outlineWidth = 0.02;
  8461. this.renderOverlay = false;
  8462. this.overlayColor = BABYLON.Color3.Red();
  8463. this.overlayAlpha = 0.5;
  8464. this.hasVertexAlpha = false;
  8465. this.useVertexColors = true;
  8466. this.applyFog = true;
  8467. this.useOctreeForRenderingSelection = true;
  8468. this.useOctreeForPicking = true;
  8469. this.useOctreeForCollisions = true;
  8470. this.layerMask = 0xFFFFFFFF;
  8471. // Physics
  8472. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8473. // Collisions
  8474. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8475. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8476. this._collider = new BABYLON.Collider();
  8477. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8478. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8479. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8480. // Cache
  8481. this._localScaling = BABYLON.Matrix.Zero();
  8482. this._localRotation = BABYLON.Matrix.Zero();
  8483. this._localTranslation = BABYLON.Matrix.Zero();
  8484. this._localBillboard = BABYLON.Matrix.Zero();
  8485. this._localPivotScaling = BABYLON.Matrix.Zero();
  8486. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8487. this._localWorld = BABYLON.Matrix.Zero();
  8488. this._worldMatrix = BABYLON.Matrix.Zero();
  8489. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8490. this._absolutePosition = BABYLON.Vector3.Zero();
  8491. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8492. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8493. this._isDirty = false;
  8494. this._pivotMatrix = BABYLON.Matrix.Identity();
  8495. this._isDisposed = false;
  8496. this._renderId = 0;
  8497. this._intersectionsInProgress = new Array();
  8498. this._onAfterWorldMatrixUpdate = new Array();
  8499. scene.meshes.push(this);
  8500. }
  8501. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8502. get: function () {
  8503. return AbstractMesh._BILLBOARDMODE_NONE;
  8504. },
  8505. enumerable: true,
  8506. configurable: true
  8507. });
  8508. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8509. get: function () {
  8510. return AbstractMesh._BILLBOARDMODE_X;
  8511. },
  8512. enumerable: true,
  8513. configurable: true
  8514. });
  8515. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8516. get: function () {
  8517. return AbstractMesh._BILLBOARDMODE_Y;
  8518. },
  8519. enumerable: true,
  8520. configurable: true
  8521. });
  8522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8523. get: function () {
  8524. return AbstractMesh._BILLBOARDMODE_Z;
  8525. },
  8526. enumerable: true,
  8527. configurable: true
  8528. });
  8529. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8530. get: function () {
  8531. return AbstractMesh._BILLBOARDMODE_ALL;
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8537. // Methods
  8538. get: function () {
  8539. return false;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. AbstractMesh.prototype.getLOD = function (camera) {
  8545. return this;
  8546. };
  8547. AbstractMesh.prototype.getTotalVertices = function () {
  8548. return 0;
  8549. };
  8550. AbstractMesh.prototype.getIndices = function () {
  8551. return null;
  8552. };
  8553. AbstractMesh.prototype.getVerticesData = function (kind) {
  8554. return null;
  8555. };
  8556. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8557. return false;
  8558. };
  8559. AbstractMesh.prototype.getBoundingInfo = function () {
  8560. if (this._masterMesh) {
  8561. return this._masterMesh.getBoundingInfo();
  8562. }
  8563. if (!this._boundingInfo) {
  8564. this._updateBoundingInfo();
  8565. }
  8566. return this._boundingInfo;
  8567. };
  8568. AbstractMesh.prototype._preActivate = function () {
  8569. };
  8570. AbstractMesh.prototype._activate = function (renderId) {
  8571. this._renderId = renderId;
  8572. };
  8573. AbstractMesh.prototype.getWorldMatrix = function () {
  8574. if (this._masterMesh) {
  8575. return this._masterMesh.getWorldMatrix();
  8576. }
  8577. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8578. this.computeWorldMatrix();
  8579. }
  8580. return this._worldMatrix;
  8581. };
  8582. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8583. get: function () {
  8584. return this._worldMatrix;
  8585. },
  8586. enumerable: true,
  8587. configurable: true
  8588. });
  8589. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8590. get: function () {
  8591. return this._absolutePosition;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8597. if (!this.rotationQuaternion) {
  8598. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8599. this.rotation = BABYLON.Vector3.Zero();
  8600. }
  8601. if (!space || space == 0 /* LOCAL */) {
  8602. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8603. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8604. } else {
  8605. if (this.parent) {
  8606. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8607. invertParentWorldMatrix.invert();
  8608. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8609. }
  8610. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8611. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8612. }
  8613. };
  8614. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8615. var displacementVector = axis.scale(distance);
  8616. if (!space || space == 0 /* LOCAL */) {
  8617. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8618. this.setPositionWithLocalVector(tempV3);
  8619. } else {
  8620. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8621. }
  8622. };
  8623. AbstractMesh.prototype.getAbsolutePosition = function () {
  8624. this.computeWorldMatrix();
  8625. return this._absolutePosition;
  8626. };
  8627. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8628. if (!absolutePosition) {
  8629. return;
  8630. }
  8631. var absolutePositionX;
  8632. var absolutePositionY;
  8633. var absolutePositionZ;
  8634. if (absolutePosition.x === undefined) {
  8635. if (arguments.length < 3) {
  8636. return;
  8637. }
  8638. absolutePositionX = arguments[0];
  8639. absolutePositionY = arguments[1];
  8640. absolutePositionZ = arguments[2];
  8641. } else {
  8642. absolutePositionX = absolutePosition.x;
  8643. absolutePositionY = absolutePosition.y;
  8644. absolutePositionZ = absolutePosition.z;
  8645. }
  8646. if (this.parent) {
  8647. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8648. invertParentWorldMatrix.invert();
  8649. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8650. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8651. } else {
  8652. this.position.x = absolutePositionX;
  8653. this.position.y = absolutePositionY;
  8654. this.position.z = absolutePositionZ;
  8655. }
  8656. };
  8657. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8658. this._pivotMatrix = matrix;
  8659. this._cache.pivotMatrixUpdated = true;
  8660. };
  8661. AbstractMesh.prototype.getPivotMatrix = function () {
  8662. return this._pivotMatrix;
  8663. };
  8664. AbstractMesh.prototype._isSynchronized = function () {
  8665. if (this._isDirty) {
  8666. return false;
  8667. }
  8668. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8669. return false;
  8670. if (this._cache.pivotMatrixUpdated) {
  8671. return false;
  8672. }
  8673. if (this.infiniteDistance) {
  8674. return false;
  8675. }
  8676. if (!this._cache.position.equals(this.position))
  8677. return false;
  8678. if (this.rotationQuaternion) {
  8679. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8680. return false;
  8681. } else {
  8682. if (!this._cache.rotation.equals(this.rotation))
  8683. return false;
  8684. }
  8685. if (!this._cache.scaling.equals(this.scaling))
  8686. return false;
  8687. return true;
  8688. };
  8689. AbstractMesh.prototype._initCache = function () {
  8690. _super.prototype._initCache.call(this);
  8691. this._cache.localMatrixUpdated = false;
  8692. this._cache.position = BABYLON.Vector3.Zero();
  8693. this._cache.scaling = BABYLON.Vector3.Zero();
  8694. this._cache.rotation = BABYLON.Vector3.Zero();
  8695. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8696. };
  8697. AbstractMesh.prototype.markAsDirty = function (property) {
  8698. if (property === "rotation") {
  8699. this.rotationQuaternion = null;
  8700. }
  8701. this._currentRenderId = Number.MAX_VALUE;
  8702. this._isDirty = true;
  8703. };
  8704. AbstractMesh.prototype._updateBoundingInfo = function () {
  8705. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8706. this._boundingInfo._update(this.worldMatrixFromCache);
  8707. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8708. };
  8709. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8710. if (!this.subMeshes) {
  8711. return;
  8712. }
  8713. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8714. var subMesh = this.subMeshes[subIndex];
  8715. subMesh.updateBoundingInfo(matrix);
  8716. }
  8717. };
  8718. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8719. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8720. return this._worldMatrix;
  8721. }
  8722. this._cache.position.copyFrom(this.position);
  8723. this._cache.scaling.copyFrom(this.scaling);
  8724. this._cache.pivotMatrixUpdated = false;
  8725. this._currentRenderId = this.getScene().getRenderId();
  8726. this._isDirty = false;
  8727. // Scaling
  8728. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8729. // Rotation
  8730. if (this.rotationQuaternion) {
  8731. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8732. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8733. } else {
  8734. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8735. this._cache.rotation.copyFrom(this.rotation);
  8736. }
  8737. // Translation
  8738. if (this.infiniteDistance && !this.parent) {
  8739. var camera = this.getScene().activeCamera;
  8740. var cameraWorldMatrix = camera.getWorldMatrix();
  8741. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8742. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8743. } else {
  8744. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8745. }
  8746. // Composing transformations
  8747. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8748. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8749. // Billboarding
  8750. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8751. var localPosition = this.position.clone();
  8752. var zero = this.getScene().activeCamera.position.clone();
  8753. if (this.parent && this.parent.position) {
  8754. localPosition.addInPlace(this.parent.position);
  8755. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8756. }
  8757. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8758. zero = this.getScene().activeCamera.position;
  8759. } else {
  8760. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8761. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8762. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8763. zero.y = localPosition.y + 0.001;
  8764. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8765. zero.z = localPosition.z + 0.001;
  8766. }
  8767. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8768. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8769. this._localBillboard.invert();
  8770. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8771. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8772. }
  8773. // Local world
  8774. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8775. // Parent
  8776. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8777. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8778. } else {
  8779. this._worldMatrix.copyFrom(this._localWorld);
  8780. }
  8781. // Bounding info
  8782. this._updateBoundingInfo();
  8783. // Absolute position
  8784. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8785. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8786. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8787. }
  8788. return this._worldMatrix;
  8789. };
  8790. /**
  8791. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8792. * @param func: callback function to add
  8793. */
  8794. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8795. this._onAfterWorldMatrixUpdate.push(func);
  8796. };
  8797. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8798. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8799. if (index > -1) {
  8800. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8801. }
  8802. };
  8803. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8804. this.computeWorldMatrix();
  8805. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8806. };
  8807. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8808. this.computeWorldMatrix();
  8809. var invLocalWorldMatrix = this._localWorld.clone();
  8810. invLocalWorldMatrix.invert();
  8811. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8812. };
  8813. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8814. this.computeWorldMatrix();
  8815. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8816. };
  8817. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8818. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8819. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8820. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8821. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8822. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8823. /// <returns>Mesh oriented towards targetMesh</returns>
  8824. yawCor = yawCor || 0; // default to zero if undefined
  8825. pitchCor = pitchCor || 0;
  8826. rollCor = rollCor || 0;
  8827. var dv = targetPoint.subtract(this.position);
  8828. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8829. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8830. var pitch = Math.atan2(dv.y, len);
  8831. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8832. };
  8833. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8834. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8835. return false;
  8836. }
  8837. return true;
  8838. };
  8839. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8840. if (!camera) {
  8841. camera = this.getScene().activeCamera;
  8842. }
  8843. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8844. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8845. return false;
  8846. }
  8847. return true;
  8848. };
  8849. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8850. if (!this._boundingInfo || !mesh._boundingInfo) {
  8851. return false;
  8852. }
  8853. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8854. };
  8855. AbstractMesh.prototype.intersectsPoint = function (point) {
  8856. if (!this._boundingInfo) {
  8857. return false;
  8858. }
  8859. return this._boundingInfo.intersectsPoint(point);
  8860. };
  8861. // Physics
  8862. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8863. var physicsEngine = this.getScene().getPhysicsEngine();
  8864. if (!physicsEngine) {
  8865. return;
  8866. }
  8867. if (impostor.impostor) {
  8868. // Old API
  8869. options = impostor;
  8870. impostor = impostor.impostor;
  8871. }
  8872. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8873. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8874. physicsEngine._unregisterMesh(this);
  8875. return;
  8876. }
  8877. options.mass = options.mass || 0;
  8878. options.friction = options.friction || 0.2;
  8879. options.restitution = options.restitution || 0.2;
  8880. this._physicImpostor = impostor;
  8881. this._physicsMass = options.mass;
  8882. this._physicsFriction = options.friction;
  8883. this._physicRestitution = options.restitution;
  8884. return physicsEngine._registerMesh(this, impostor, options);
  8885. };
  8886. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8887. if (!this._physicImpostor) {
  8888. return BABYLON.PhysicsEngine.NoImpostor;
  8889. }
  8890. return this._physicImpostor;
  8891. };
  8892. AbstractMesh.prototype.getPhysicsMass = function () {
  8893. if (!this._physicsMass) {
  8894. return 0;
  8895. }
  8896. return this._physicsMass;
  8897. };
  8898. AbstractMesh.prototype.getPhysicsFriction = function () {
  8899. if (!this._physicsFriction) {
  8900. return 0;
  8901. }
  8902. return this._physicsFriction;
  8903. };
  8904. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8905. if (!this._physicRestitution) {
  8906. return 0;
  8907. }
  8908. return this._physicRestitution;
  8909. };
  8910. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8911. if (!camera) {
  8912. camera = this.getScene().activeCamera;
  8913. }
  8914. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8915. };
  8916. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8917. if (!camera) {
  8918. camera = this.getScene().activeCamera;
  8919. }
  8920. return this.absolutePosition.subtract(camera.position).length();
  8921. };
  8922. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8923. if (!this._physicImpostor) {
  8924. return;
  8925. }
  8926. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8927. };
  8928. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8929. if (!this._physicImpostor) {
  8930. return;
  8931. }
  8932. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8933. };
  8934. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8935. if (!this._physicImpostor) {
  8936. return;
  8937. }
  8938. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8939. };
  8940. // Collisions
  8941. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8942. var globalPosition = this.getAbsolutePosition();
  8943. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8944. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8945. this._collider.radius = this.ellipsoid;
  8946. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8947. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8948. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8949. this.position.addInPlace(this._diffPositionForCollisions);
  8950. }
  8951. };
  8952. // Submeshes octree
  8953. /**
  8954. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8955. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8956. */
  8957. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8958. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8959. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8960. if (!this._submeshesOctree) {
  8961. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8962. }
  8963. this.computeWorldMatrix(true);
  8964. // Update octree
  8965. var bbox = this.getBoundingInfo().boundingBox;
  8966. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8967. return this._submeshesOctree;
  8968. };
  8969. // Collisions
  8970. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8971. this._generatePointsArray();
  8972. // Transformation
  8973. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8974. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8975. subMesh._lastColliderWorldVertices = [];
  8976. subMesh._trianglePlanes = [];
  8977. var start = subMesh.verticesStart;
  8978. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8979. for (var i = start; i < end; i++) {
  8980. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8981. }
  8982. }
  8983. // Collide
  8984. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8985. };
  8986. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8987. var subMeshes;
  8988. var len;
  8989. // Octrees
  8990. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8991. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8992. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8993. len = intersections.length;
  8994. subMeshes = intersections.data;
  8995. } else {
  8996. subMeshes = this.subMeshes;
  8997. len = subMeshes.length;
  8998. }
  8999. for (var index = 0; index < len; index++) {
  9000. var subMesh = subMeshes[index];
  9001. // Bounding test
  9002. if (len > 1 && !subMesh._checkCollision(collider))
  9003. continue;
  9004. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9005. }
  9006. };
  9007. AbstractMesh.prototype._checkCollision = function (collider) {
  9008. // Bounding box test
  9009. if (!this._boundingInfo._checkCollision(collider))
  9010. return;
  9011. // Transformation matrix
  9012. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9013. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9014. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9015. };
  9016. // Picking
  9017. AbstractMesh.prototype._generatePointsArray = function () {
  9018. return false;
  9019. };
  9020. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9021. var pickingInfo = new BABYLON.PickingInfo();
  9022. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9023. return pickingInfo;
  9024. }
  9025. if (!this._generatePointsArray()) {
  9026. return pickingInfo;
  9027. }
  9028. var intersectInfo = null;
  9029. // Octrees
  9030. var subMeshes;
  9031. var len;
  9032. if (this._submeshesOctree && this.useOctreeForPicking) {
  9033. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9034. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9035. len = intersections.length;
  9036. subMeshes = intersections.data;
  9037. } else {
  9038. subMeshes = this.subMeshes;
  9039. len = subMeshes.length;
  9040. }
  9041. for (var index = 0; index < len; index++) {
  9042. var subMesh = subMeshes[index];
  9043. // Bounding test
  9044. if (len > 1 && !subMesh.canIntersects(ray))
  9045. continue;
  9046. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9047. if (currentIntersectInfo) {
  9048. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9049. intersectInfo = currentIntersectInfo;
  9050. if (fastCheck) {
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. }
  9056. if (intersectInfo) {
  9057. // Get picked point
  9058. var world = this.getWorldMatrix();
  9059. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9060. var direction = ray.direction.clone();
  9061. direction.normalize();
  9062. direction = direction.scale(intersectInfo.distance);
  9063. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9064. var pickedPoint = worldOrigin.add(worldDirection);
  9065. // Return result
  9066. pickingInfo.hit = true;
  9067. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9068. pickingInfo.pickedPoint = pickedPoint;
  9069. pickingInfo.pickedMesh = this;
  9070. pickingInfo.bu = intersectInfo.bu;
  9071. pickingInfo.bv = intersectInfo.bv;
  9072. pickingInfo.faceId = intersectInfo.faceId;
  9073. return pickingInfo;
  9074. }
  9075. return pickingInfo;
  9076. };
  9077. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9078. return null;
  9079. };
  9080. AbstractMesh.prototype.releaseSubMeshes = function () {
  9081. if (this.subMeshes) {
  9082. while (this.subMeshes.length) {
  9083. this.subMeshes[0].dispose();
  9084. }
  9085. } else {
  9086. this.subMeshes = new Array();
  9087. }
  9088. };
  9089. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9090. // Physics
  9091. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9092. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9093. }
  9094. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9095. var other = this._intersectionsInProgress[index];
  9096. var pos = other._intersectionsInProgress.indexOf(this);
  9097. other._intersectionsInProgress.splice(pos, 1);
  9098. }
  9099. this._intersectionsInProgress = [];
  9100. // SubMeshes
  9101. this.releaseSubMeshes();
  9102. // Remove from scene
  9103. var index = this.getScene().meshes.indexOf(this);
  9104. if (index != -1) {
  9105. // Remove from the scene if mesh found
  9106. this.getScene().meshes.splice(index, 1);
  9107. }
  9108. if (!doNotRecurse) {
  9109. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9110. if (this.getScene().particleSystems[index].emitter == this) {
  9111. this.getScene().particleSystems[index].dispose();
  9112. index--;
  9113. }
  9114. }
  9115. // Children
  9116. var objects = this.getScene().meshes.slice(0);
  9117. for (index = 0; index < objects.length; index++) {
  9118. if (objects[index].parent == this) {
  9119. objects[index].dispose();
  9120. }
  9121. }
  9122. } else {
  9123. for (index = 0; index < this.getScene().meshes.length; index++) {
  9124. var obj = this.getScene().meshes[index];
  9125. if (obj.parent === this) {
  9126. obj.parent = null;
  9127. obj.computeWorldMatrix(true);
  9128. }
  9129. }
  9130. }
  9131. this._onAfterWorldMatrixUpdate = [];
  9132. this._isDisposed = true;
  9133. // Callback
  9134. if (this.onDispose) {
  9135. this.onDispose();
  9136. }
  9137. };
  9138. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9139. AbstractMesh._BILLBOARDMODE_X = 1;
  9140. AbstractMesh._BILLBOARDMODE_Y = 2;
  9141. AbstractMesh._BILLBOARDMODE_Z = 4;
  9142. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9143. return AbstractMesh;
  9144. })(BABYLON.Node);
  9145. BABYLON.AbstractMesh = AbstractMesh;
  9146. })(BABYLON || (BABYLON = {}));
  9147. //# sourceMappingURL=babylon.abstractMesh.js.map
  9148. var BABYLON;
  9149. (function (BABYLON) {
  9150. var _InstancesBatch = (function () {
  9151. function _InstancesBatch() {
  9152. this.mustReturn = false;
  9153. this.visibleInstances = new Array();
  9154. this.renderSelf = new Array();
  9155. }
  9156. return _InstancesBatch;
  9157. })();
  9158. BABYLON._InstancesBatch = _InstancesBatch;
  9159. var Mesh = (function (_super) {
  9160. __extends(Mesh, _super);
  9161. /**
  9162. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9163. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9164. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9165. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9166. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9167. * When false, achieved by calling a clone(), also passing False.
  9168. * This will make creation of children, recursive.
  9169. */
  9170. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9171. if (typeof parent === "undefined") { parent = null; }
  9172. _super.call(this, name, scene);
  9173. // Members
  9174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9175. this.instances = new Array();
  9176. this._LODLevels = new Array();
  9177. this._onBeforeRenderCallbacks = new Array();
  9178. this._onAfterRenderCallbacks = new Array();
  9179. this._visibleInstances = {};
  9180. this._renderIdForInstances = new Array();
  9181. this._batchCache = new _InstancesBatch();
  9182. this._instancesBufferSize = 32 * 16 * 4;
  9183. if (source) {
  9184. // Geometry
  9185. if (source._geometry) {
  9186. source._geometry.applyToMesh(this);
  9187. }
  9188. // Deep copy
  9189. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9190. // Material
  9191. this.material = source.material;
  9192. if (!doNotCloneChildren) {
  9193. for (var index = 0; index < scene.meshes.length; index++) {
  9194. var mesh = scene.meshes[index];
  9195. if (mesh.parent === source) {
  9196. // doNotCloneChildren is always going to be False
  9197. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9198. }
  9199. }
  9200. }
  9201. for (index = 0; index < scene.particleSystems.length; index++) {
  9202. var system = scene.particleSystems[index];
  9203. if (system.emitter === source) {
  9204. system.clone(system.name, this);
  9205. }
  9206. }
  9207. this.computeWorldMatrix(true);
  9208. }
  9209. // Parent
  9210. if (parent !== null) {
  9211. this.parent = parent;
  9212. }
  9213. }
  9214. Mesh.prototype._clone = function () {
  9215. };
  9216. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9217. // Methods
  9218. get: function () {
  9219. return this._LODLevels.length > 0;
  9220. },
  9221. enumerable: true,
  9222. configurable: true
  9223. });
  9224. Mesh.prototype._sortLODLevels = function () {
  9225. this._LODLevels.sort(function (a, b) {
  9226. if (a.distance < b.distance) {
  9227. return 1;
  9228. }
  9229. if (a.distance > b.distance) {
  9230. return -1;
  9231. }
  9232. return 0;
  9233. });
  9234. };
  9235. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9236. if (mesh && mesh._masterMesh) {
  9237. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9238. return this;
  9239. }
  9240. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9241. this._LODLevels.push(level);
  9242. if (mesh) {
  9243. mesh._masterMesh = this;
  9244. }
  9245. this._sortLODLevels();
  9246. return this;
  9247. };
  9248. Mesh.prototype.removeLODLevel = function (mesh) {
  9249. for (var index = 0; index < this._LODLevels.length; index++) {
  9250. if (this._LODLevels[index].mesh === mesh) {
  9251. this._LODLevels.splice(index, 1);
  9252. if (mesh) {
  9253. mesh._masterMesh = null;
  9254. }
  9255. }
  9256. }
  9257. this._sortLODLevels();
  9258. return this;
  9259. };
  9260. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9261. if (!this._LODLevels || this._LODLevels.length === 0) {
  9262. return this;
  9263. }
  9264. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9265. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9266. return this;
  9267. }
  9268. for (var index = 0; index < this._LODLevels.length; index++) {
  9269. var level = this._LODLevels[index];
  9270. if (level.distance < distanceToCamera) {
  9271. if (level.mesh) {
  9272. level.mesh._preActivate();
  9273. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9274. }
  9275. return level.mesh;
  9276. }
  9277. }
  9278. return this;
  9279. };
  9280. Object.defineProperty(Mesh.prototype, "geometry", {
  9281. get: function () {
  9282. return this._geometry;
  9283. },
  9284. enumerable: true,
  9285. configurable: true
  9286. });
  9287. Mesh.prototype.getTotalVertices = function () {
  9288. if (!this._geometry) {
  9289. return 0;
  9290. }
  9291. return this._geometry.getTotalVertices();
  9292. };
  9293. Mesh.prototype.getVerticesData = function (kind) {
  9294. if (!this._geometry) {
  9295. return null;
  9296. }
  9297. return this._geometry.getVerticesData(kind);
  9298. };
  9299. Mesh.prototype.getVertexBuffer = function (kind) {
  9300. if (!this._geometry) {
  9301. return undefined;
  9302. }
  9303. return this._geometry.getVertexBuffer(kind);
  9304. };
  9305. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9306. if (!this._geometry) {
  9307. if (this._delayInfo) {
  9308. return this._delayInfo.indexOf(kind) !== -1;
  9309. }
  9310. return false;
  9311. }
  9312. return this._geometry.isVerticesDataPresent(kind);
  9313. };
  9314. Mesh.prototype.getVerticesDataKinds = function () {
  9315. if (!this._geometry) {
  9316. var result = [];
  9317. if (this._delayInfo) {
  9318. for (var kind in this._delayInfo) {
  9319. result.push(kind);
  9320. }
  9321. }
  9322. return result;
  9323. }
  9324. return this._geometry.getVerticesDataKinds();
  9325. };
  9326. Mesh.prototype.getTotalIndices = function () {
  9327. if (!this._geometry) {
  9328. return 0;
  9329. }
  9330. return this._geometry.getTotalIndices();
  9331. };
  9332. Mesh.prototype.getIndices = function () {
  9333. if (!this._geometry) {
  9334. return [];
  9335. }
  9336. return this._geometry.getIndices();
  9337. };
  9338. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9339. get: function () {
  9340. return this._masterMesh !== null && this._masterMesh !== undefined;
  9341. },
  9342. enumerable: true,
  9343. configurable: true
  9344. });
  9345. Mesh.prototype.isReady = function () {
  9346. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9347. return false;
  9348. }
  9349. return _super.prototype.isReady.call(this);
  9350. };
  9351. Mesh.prototype.isDisposed = function () {
  9352. return this._isDisposed;
  9353. };
  9354. // Methods
  9355. Mesh.prototype._preActivate = function () {
  9356. var sceneRenderId = this.getScene().getRenderId();
  9357. if (this._preActivateId == sceneRenderId) {
  9358. return;
  9359. }
  9360. this._preActivateId = sceneRenderId;
  9361. this._visibleInstances = null;
  9362. };
  9363. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9364. if (!this._visibleInstances) {
  9365. this._visibleInstances = {};
  9366. this._visibleInstances.defaultRenderId = renderId;
  9367. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9368. }
  9369. if (!this._visibleInstances[renderId]) {
  9370. this._visibleInstances[renderId] = new Array();
  9371. }
  9372. this._visibleInstances[renderId].push(instance);
  9373. };
  9374. Mesh.prototype.refreshBoundingInfo = function () {
  9375. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9376. if (data) {
  9377. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9378. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9379. }
  9380. if (this.subMeshes) {
  9381. for (var index = 0; index < this.subMeshes.length; index++) {
  9382. this.subMeshes[index].refreshBoundingInfo();
  9383. }
  9384. }
  9385. this._updateBoundingInfo();
  9386. };
  9387. Mesh.prototype._createGlobalSubMesh = function () {
  9388. var totalVertices = this.getTotalVertices();
  9389. if (!totalVertices || !this.getIndices()) {
  9390. return null;
  9391. }
  9392. this.releaseSubMeshes();
  9393. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9394. };
  9395. Mesh.prototype.subdivide = function (count) {
  9396. if (count < 1) {
  9397. return;
  9398. }
  9399. var totalIndices = this.getTotalIndices();
  9400. var subdivisionSize = (totalIndices / count) | 0;
  9401. var offset = 0;
  9402. while (subdivisionSize % 3 != 0) {
  9403. subdivisionSize++;
  9404. }
  9405. this.releaseSubMeshes();
  9406. for (var index = 0; index < count; index++) {
  9407. if (offset >= totalIndices) {
  9408. break;
  9409. }
  9410. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9411. offset += subdivisionSize;
  9412. }
  9413. this.synchronizeInstances();
  9414. };
  9415. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9416. if (kind instanceof Array) {
  9417. var temp = data;
  9418. data = kind;
  9419. kind = temp;
  9420. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9421. }
  9422. if (!this._geometry) {
  9423. var vertexData = new BABYLON.VertexData();
  9424. vertexData.set(data, kind);
  9425. var scene = this.getScene();
  9426. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9427. } else {
  9428. this._geometry.setVerticesData(kind, data, updatable, stride);
  9429. }
  9430. };
  9431. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9432. if (!this._geometry) {
  9433. return;
  9434. }
  9435. if (!makeItUnique) {
  9436. this._geometry.updateVerticesData(kind, data, updateExtends);
  9437. } else {
  9438. this.makeGeometryUnique();
  9439. this.updateVerticesData(kind, data, updateExtends, false);
  9440. }
  9441. };
  9442. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9443. if (!this._geometry) {
  9444. return;
  9445. }
  9446. if (!makeItUnique) {
  9447. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9448. } else {
  9449. this.makeGeometryUnique();
  9450. this.updateVerticesDataDirectly(kind, data, offset, false);
  9451. }
  9452. };
  9453. Mesh.prototype.makeGeometryUnique = function () {
  9454. if (!this._geometry) {
  9455. return;
  9456. }
  9457. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9458. geometry.applyToMesh(this);
  9459. };
  9460. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9461. if (!this._geometry) {
  9462. var vertexData = new BABYLON.VertexData();
  9463. vertexData.indices = indices;
  9464. var scene = this.getScene();
  9465. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9466. } else {
  9467. this._geometry.setIndices(indices, totalVertices);
  9468. }
  9469. };
  9470. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9471. var engine = this.getScene().getEngine();
  9472. // Wireframe
  9473. var indexToBind;
  9474. switch (fillMode) {
  9475. case BABYLON.Material.PointFillMode:
  9476. indexToBind = null;
  9477. break;
  9478. case BABYLON.Material.WireFrameFillMode:
  9479. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9480. break;
  9481. default:
  9482. case BABYLON.Material.TriangleFillMode:
  9483. indexToBind = this._geometry.getIndexBuffer();
  9484. break;
  9485. }
  9486. // VBOs
  9487. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9488. };
  9489. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9490. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9491. return;
  9492. }
  9493. var engine = this.getScene().getEngine();
  9494. switch (fillMode) {
  9495. case BABYLON.Material.PointFillMode:
  9496. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9497. break;
  9498. case BABYLON.Material.WireFrameFillMode:
  9499. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9500. break;
  9501. default:
  9502. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9503. }
  9504. };
  9505. Mesh.prototype.registerBeforeRender = function (func) {
  9506. this._onBeforeRenderCallbacks.push(func);
  9507. };
  9508. Mesh.prototype.unregisterBeforeRender = function (func) {
  9509. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9510. if (index > -1) {
  9511. this._onBeforeRenderCallbacks.splice(index, 1);
  9512. }
  9513. };
  9514. Mesh.prototype.registerAfterRender = function (func) {
  9515. this._onAfterRenderCallbacks.push(func);
  9516. };
  9517. Mesh.prototype.unregisterAfterRender = function (func) {
  9518. var index = this._onAfterRenderCallbacks.indexOf(func);
  9519. if (index > -1) {
  9520. this._onAfterRenderCallbacks.splice(index, 1);
  9521. }
  9522. };
  9523. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9524. var scene = this.getScene();
  9525. this._batchCache.mustReturn = false;
  9526. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9527. this._batchCache.visibleInstances[subMeshId] = null;
  9528. if (this._visibleInstances) {
  9529. var currentRenderId = scene.getRenderId();
  9530. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9531. var selfRenderId = this._renderId;
  9532. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9533. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9534. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9535. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9536. }
  9537. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9538. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9539. this._batchCache.mustReturn = true;
  9540. return this._batchCache;
  9541. }
  9542. if (currentRenderId !== selfRenderId) {
  9543. this._batchCache.renderSelf[subMeshId] = false;
  9544. }
  9545. }
  9546. this._renderIdForInstances[subMeshId] = currentRenderId;
  9547. }
  9548. return this._batchCache;
  9549. };
  9550. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9551. var visibleInstances = batch.visibleInstances[subMesh._id];
  9552. var matricesCount = visibleInstances.length + 1;
  9553. var bufferSize = matricesCount * 16 * 4;
  9554. while (this._instancesBufferSize < bufferSize) {
  9555. this._instancesBufferSize *= 2;
  9556. }
  9557. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9558. if (this._worldMatricesInstancesBuffer) {
  9559. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9560. }
  9561. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9562. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9563. }
  9564. var offset = 0;
  9565. var instancesCount = 0;
  9566. var world = this.getWorldMatrix();
  9567. if (batch.renderSelf[subMesh._id]) {
  9568. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9569. offset += 16;
  9570. instancesCount++;
  9571. }
  9572. if (visibleInstances) {
  9573. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9574. var instance = visibleInstances[instanceIndex];
  9575. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9576. offset += 16;
  9577. instancesCount++;
  9578. }
  9579. }
  9580. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9581. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9582. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9583. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9584. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9585. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9586. this._draw(subMesh, fillMode, instancesCount);
  9587. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9588. };
  9589. Mesh.prototype.render = function (subMesh) {
  9590. var scene = this.getScene();
  9591. // Managing instances
  9592. var batch = this._getInstancesRenderList(subMesh._id);
  9593. if (batch.mustReturn) {
  9594. return;
  9595. }
  9596. // Checking geometry state
  9597. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9598. return;
  9599. }
  9600. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9601. this._onBeforeRenderCallbacks[callbackIndex]();
  9602. }
  9603. var engine = scene.getEngine();
  9604. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9605. // Material
  9606. var effectiveMaterial = subMesh.getMaterial();
  9607. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9608. return;
  9609. }
  9610. // Outline - step 1
  9611. var savedDepthWrite = engine.getDepthWrite();
  9612. if (this.renderOutline) {
  9613. engine.setDepthWrite(false);
  9614. scene.getOutlineRenderer().render(subMesh, batch);
  9615. engine.setDepthWrite(savedDepthWrite);
  9616. }
  9617. effectiveMaterial._preBind();
  9618. var effect = effectiveMaterial.getEffect();
  9619. // Bind
  9620. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9621. this._bind(subMesh, effect, fillMode);
  9622. var world = this.getWorldMatrix();
  9623. effectiveMaterial.bind(world, this);
  9624. // Instances rendering
  9625. if (hardwareInstancedRendering) {
  9626. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9627. } else {
  9628. if (batch.renderSelf[subMesh._id]) {
  9629. // Draw
  9630. this._draw(subMesh, fillMode);
  9631. }
  9632. if (batch.visibleInstances[subMesh._id]) {
  9633. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9634. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9635. // World
  9636. world = instance.getWorldMatrix();
  9637. effectiveMaterial.bindOnlyWorldMatrix(world);
  9638. // Draw
  9639. this._draw(subMesh, fillMode);
  9640. }
  9641. }
  9642. }
  9643. // Unbind
  9644. effectiveMaterial.unbind();
  9645. // Outline - step 2
  9646. if (this.renderOutline && savedDepthWrite) {
  9647. engine.setDepthWrite(true);
  9648. engine.setColorWrite(false);
  9649. scene.getOutlineRenderer().render(subMesh, batch);
  9650. engine.setColorWrite(true);
  9651. }
  9652. // Overlay
  9653. if (this.renderOverlay) {
  9654. var currentMode = engine.getAlphaMode();
  9655. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9656. scene.getOutlineRenderer().render(subMesh, batch, true);
  9657. engine.setAlphaMode(currentMode);
  9658. }
  9659. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9660. this._onAfterRenderCallbacks[callbackIndex]();
  9661. }
  9662. };
  9663. Mesh.prototype.getEmittedParticleSystems = function () {
  9664. var results = new Array();
  9665. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9666. var particleSystem = this.getScene().particleSystems[index];
  9667. if (particleSystem.emitter === this) {
  9668. results.push(particleSystem);
  9669. }
  9670. }
  9671. return results;
  9672. };
  9673. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9674. var results = new Array();
  9675. var descendants = this.getDescendants();
  9676. descendants.push(this);
  9677. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9678. var particleSystem = this.getScene().particleSystems[index];
  9679. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9680. results.push(particleSystem);
  9681. }
  9682. }
  9683. return results;
  9684. };
  9685. Mesh.prototype.getChildren = function () {
  9686. var results = [];
  9687. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9688. var mesh = this.getScene().meshes[index];
  9689. if (mesh.parent == this) {
  9690. results.push(mesh);
  9691. }
  9692. }
  9693. return results;
  9694. };
  9695. Mesh.prototype._checkDelayState = function () {
  9696. var _this = this;
  9697. var that = this;
  9698. var scene = this.getScene();
  9699. if (this._geometry) {
  9700. this._geometry.load(scene);
  9701. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9702. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9703. scene._addPendingData(that);
  9704. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9705. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9706. if (data instanceof ArrayBuffer) {
  9707. _this._delayLoadingFunction(data, _this);
  9708. } else {
  9709. _this._delayLoadingFunction(JSON.parse(data), _this);
  9710. }
  9711. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9712. scene._removePendingData(_this);
  9713. }, function () {
  9714. }, scene.database, getBinaryData);
  9715. }
  9716. };
  9717. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9719. return false;
  9720. }
  9721. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9722. return false;
  9723. }
  9724. this._checkDelayState();
  9725. return true;
  9726. };
  9727. Mesh.prototype.setMaterialByID = function (id) {
  9728. var materials = this.getScene().materials;
  9729. for (var index = 0; index < materials.length; index++) {
  9730. if (materials[index].id == id) {
  9731. this.material = materials[index];
  9732. return;
  9733. }
  9734. }
  9735. // Multi
  9736. var multiMaterials = this.getScene().multiMaterials;
  9737. for (index = 0; index < multiMaterials.length; index++) {
  9738. if (multiMaterials[index].id == id) {
  9739. this.material = multiMaterials[index];
  9740. return;
  9741. }
  9742. }
  9743. };
  9744. Mesh.prototype.getAnimatables = function () {
  9745. var results = [];
  9746. if (this.material) {
  9747. results.push(this.material);
  9748. }
  9749. if (this.skeleton) {
  9750. results.push(this.skeleton);
  9751. }
  9752. return results;
  9753. };
  9754. // Geometry
  9755. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9756. // Position
  9757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9758. return;
  9759. }
  9760. this._resetPointsArrayCache();
  9761. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9762. var temp = [];
  9763. for (var index = 0; index < data.length; index += 3) {
  9764. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9765. }
  9766. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9767. // Normals
  9768. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9769. return;
  9770. }
  9771. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9772. for (index = 0; index < data.length; index += 3) {
  9773. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9774. }
  9775. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9776. };
  9777. // Cache
  9778. Mesh.prototype._resetPointsArrayCache = function () {
  9779. this._positions = null;
  9780. };
  9781. Mesh.prototype._generatePointsArray = function () {
  9782. if (this._positions)
  9783. return true;
  9784. this._positions = [];
  9785. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9786. if (!data) {
  9787. return false;
  9788. }
  9789. for (var index = 0; index < data.length; index += 3) {
  9790. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9791. }
  9792. return true;
  9793. };
  9794. // Clone
  9795. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9796. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9797. };
  9798. // Dispose
  9799. Mesh.prototype.dispose = function (doNotRecurse) {
  9800. if (this._geometry) {
  9801. this._geometry.releaseForMesh(this, true);
  9802. }
  9803. // Instances
  9804. if (this._worldMatricesInstancesBuffer) {
  9805. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9806. this._worldMatricesInstancesBuffer = null;
  9807. }
  9808. while (this.instances.length) {
  9809. this.instances[0].dispose();
  9810. }
  9811. _super.prototype.dispose.call(this, doNotRecurse);
  9812. };
  9813. // Geometric tools
  9814. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9815. var _this = this;
  9816. var scene = this.getScene();
  9817. var onload = function (img) {
  9818. // Getting height map data
  9819. var canvas = document.createElement("canvas");
  9820. var context = canvas.getContext("2d");
  9821. var heightMapWidth = img.width;
  9822. var heightMapHeight = img.height;
  9823. canvas.width = heightMapWidth;
  9824. canvas.height = heightMapHeight;
  9825. context.drawImage(img, 0, 0);
  9826. // Create VertexData from map data
  9827. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9828. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9829. };
  9830. BABYLON.Tools.LoadImage(url, onload, function () {
  9831. }, scene.database);
  9832. };
  9833. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9834. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9835. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9836. return;
  9837. }
  9838. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9839. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9840. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9841. var position = BABYLON.Vector3.Zero();
  9842. var normal = BABYLON.Vector3.Zero();
  9843. var uv = BABYLON.Vector2.Zero();
  9844. for (var index = 0; index < positions.length; index += 3) {
  9845. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9846. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9847. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9848. // Compute height
  9849. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9850. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9851. var pos = (u + v * heightMapWidth) * 4;
  9852. var r = buffer[pos] / 255.0;
  9853. var g = buffer[pos + 1] / 255.0;
  9854. var b = buffer[pos + 2] / 255.0;
  9855. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9856. normal.normalize();
  9857. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9858. position = position.add(normal);
  9859. position.toArray(positions, index);
  9860. }
  9861. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9862. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9863. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9864. };
  9865. Mesh.prototype.convertToFlatShadedMesh = function () {
  9866. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9867. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9868. var kinds = this.getVerticesDataKinds();
  9869. var vbs = [];
  9870. var data = [];
  9871. var newdata = [];
  9872. var updatableNormals = false;
  9873. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9874. var kind = kinds[kindIndex];
  9875. var vertexBuffer = this.getVertexBuffer(kind);
  9876. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9877. updatableNormals = vertexBuffer.isUpdatable();
  9878. kinds.splice(kindIndex, 1);
  9879. kindIndex--;
  9880. continue;
  9881. }
  9882. vbs[kind] = vertexBuffer;
  9883. data[kind] = vbs[kind].getData();
  9884. newdata[kind] = [];
  9885. }
  9886. // Save previous submeshes
  9887. var previousSubmeshes = this.subMeshes.slice(0);
  9888. var indices = this.getIndices();
  9889. var totalIndices = this.getTotalIndices();
  9890. for (index = 0; index < totalIndices; index++) {
  9891. var vertexIndex = indices[index];
  9892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9893. kind = kinds[kindIndex];
  9894. var stride = vbs[kind].getStrideSize();
  9895. for (var offset = 0; offset < stride; offset++) {
  9896. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9897. }
  9898. }
  9899. }
  9900. // Updating faces & normal
  9901. var normals = [];
  9902. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9903. for (var index = 0; index < totalIndices; index += 3) {
  9904. indices[index] = index;
  9905. indices[index + 1] = index + 1;
  9906. indices[index + 2] = index + 2;
  9907. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9908. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9909. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9910. var p1p2 = p1.subtract(p2);
  9911. var p3p2 = p3.subtract(p2);
  9912. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9913. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9914. normals.push(normal.x);
  9915. normals.push(normal.y);
  9916. normals.push(normal.z);
  9917. }
  9918. }
  9919. this.setIndices(indices);
  9920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9922. kind = kinds[kindIndex];
  9923. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9924. }
  9925. // Updating submeshes
  9926. this.releaseSubMeshes();
  9927. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9928. var previousOne = previousSubmeshes[submeshIndex];
  9929. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9930. }
  9931. this.synchronizeInstances();
  9932. };
  9933. // Instances
  9934. Mesh.prototype.createInstance = function (name) {
  9935. return new BABYLON.InstancedMesh(name, this);
  9936. };
  9937. Mesh.prototype.synchronizeInstances = function () {
  9938. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9939. var instance = this.instances[instanceIndex];
  9940. instance._syncSubMeshes();
  9941. }
  9942. };
  9943. // Statics
  9944. Mesh.CreateBox = function (name, size, scene, updatable) {
  9945. var box = new BABYLON.Mesh(name, scene);
  9946. var vertexData = BABYLON.VertexData.CreateBox(size);
  9947. vertexData.applyToMesh(box, updatable);
  9948. return box;
  9949. };
  9950. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9951. var sphere = new BABYLON.Mesh(name, scene);
  9952. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9953. vertexData.applyToMesh(sphere, updatable);
  9954. return sphere;
  9955. };
  9956. // Cylinder and cone (Code inspired by SharpDX.org)
  9957. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9958. // subdivisions is a new parameter, we need to support old signature
  9959. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9960. if (scene !== undefined) {
  9961. updatable = scene;
  9962. }
  9963. scene = subdivisions;
  9964. subdivisions = 1;
  9965. }
  9966. var cylinder = new BABYLON.Mesh(name, scene);
  9967. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9968. vertexData.applyToMesh(cylinder, updatable);
  9969. return cylinder;
  9970. };
  9971. // Torus (Code from SharpDX.org)
  9972. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9973. var torus = new BABYLON.Mesh(name, scene);
  9974. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9975. vertexData.applyToMesh(torus, updatable);
  9976. return torus;
  9977. };
  9978. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9979. var torusKnot = new BABYLON.Mesh(name, scene);
  9980. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9981. vertexData.applyToMesh(torusKnot, updatable);
  9982. return torusKnot;
  9983. };
  9984. // Lines
  9985. Mesh.CreateLines = function (name, points, scene, updatable) {
  9986. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9987. var vertexData = BABYLON.VertexData.CreateLines(points);
  9988. vertexData.applyToMesh(lines, updatable);
  9989. return lines;
  9990. };
  9991. // Plane & ground
  9992. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9993. var plane = new BABYLON.Mesh(name, scene);
  9994. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9995. vertexData.applyToMesh(plane, updatable);
  9996. return plane;
  9997. };
  9998. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9999. var ground = new BABYLON.GroundMesh(name, scene);
  10000. ground._setReady(false);
  10001. ground._subdivisions = subdivisions;
  10002. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10003. vertexData.applyToMesh(ground, updatable);
  10004. ground._setReady(true);
  10005. return ground;
  10006. };
  10007. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10008. var tiledGround = new BABYLON.Mesh(name, scene);
  10009. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10010. vertexData.applyToMesh(tiledGround, updatable);
  10011. return tiledGround;
  10012. };
  10013. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10014. var ground = new BABYLON.GroundMesh(name, scene);
  10015. ground._subdivisions = subdivisions;
  10016. ground._setReady(false);
  10017. var onload = function (img) {
  10018. // Getting height map data
  10019. var canvas = document.createElement("canvas");
  10020. var context = canvas.getContext("2d");
  10021. var heightMapWidth = img.width;
  10022. var heightMapHeight = img.height;
  10023. canvas.width = heightMapWidth;
  10024. canvas.height = heightMapHeight;
  10025. context.drawImage(img, 0, 0);
  10026. // Create VertexData from map data
  10027. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10028. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10029. vertexData.applyToMesh(ground, updatable);
  10030. ground._setReady(true);
  10031. };
  10032. BABYLON.Tools.LoadImage(url, onload, function () {
  10033. }, scene.database);
  10034. return ground;
  10035. };
  10036. // Tools
  10037. Mesh.MinMax = function (meshes) {
  10038. var minVector = null;
  10039. var maxVector = null;
  10040. for (var i in meshes) {
  10041. var mesh = meshes[i];
  10042. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10043. if (!minVector) {
  10044. minVector = boundingBox.minimumWorld;
  10045. maxVector = boundingBox.maximumWorld;
  10046. continue;
  10047. }
  10048. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10049. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10050. }
  10051. return {
  10052. min: minVector,
  10053. max: maxVector
  10054. };
  10055. };
  10056. Mesh.Center = function (meshesOrMinMaxVector) {
  10057. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10058. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10059. };
  10060. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10061. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10062. var source = meshes[0];
  10063. var material = source.material;
  10064. var scene = source.getScene();
  10065. if (!allow32BitsIndices) {
  10066. var totalVertices = 0;
  10067. for (var index = 0; index < meshes.length; index++) {
  10068. totalVertices += meshes[index].getTotalVertices();
  10069. if (totalVertices > 65536) {
  10070. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10071. return null;
  10072. }
  10073. }
  10074. }
  10075. // Merge
  10076. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10077. vertexData.transform(source.getWorldMatrix());
  10078. for (index = 1; index < meshes.length; index++) {
  10079. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10080. otherVertexData.transform(meshes[index].getWorldMatrix());
  10081. vertexData.merge(otherVertexData);
  10082. }
  10083. var newMesh = new Mesh(source.name + "_merged", scene);
  10084. vertexData.applyToMesh(newMesh);
  10085. // Setting properties
  10086. newMesh.material = material;
  10087. newMesh.checkCollisions = source.checkCollisions;
  10088. // Cleaning
  10089. if (disposeSource) {
  10090. for (index = 0; index < meshes.length; index++) {
  10091. meshes[index].dispose();
  10092. }
  10093. }
  10094. return newMesh;
  10095. };
  10096. return Mesh;
  10097. })(BABYLON.AbstractMesh);
  10098. BABYLON.Mesh = Mesh;
  10099. })(BABYLON || (BABYLON = {}));
  10100. //# sourceMappingURL=babylon.mesh.js.map
  10101. var BABYLON;
  10102. (function (BABYLON) {
  10103. var GroundMesh = (function (_super) {
  10104. __extends(GroundMesh, _super);
  10105. function GroundMesh(name, scene) {
  10106. _super.call(this, name, scene);
  10107. this.generateOctree = false;
  10108. this._worldInverse = new BABYLON.Matrix();
  10109. }
  10110. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10111. get: function () {
  10112. return this._subdivisions;
  10113. },
  10114. enumerable: true,
  10115. configurable: true
  10116. });
  10117. GroundMesh.prototype.optimize = function (chunksCount) {
  10118. this.subdivide(this._subdivisions);
  10119. this.createOrUpdateSubmeshesOctree(32);
  10120. };
  10121. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10122. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10123. this.getWorldMatrix().invertToRef(this._worldInverse);
  10124. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10125. var pickInfo = this.intersects(ray);
  10126. if (pickInfo.hit) {
  10127. return pickInfo.pickedPoint.y;
  10128. }
  10129. return 0;
  10130. };
  10131. return GroundMesh;
  10132. })(BABYLON.Mesh);
  10133. BABYLON.GroundMesh = GroundMesh;
  10134. })(BABYLON || (BABYLON = {}));
  10135. //# sourceMappingURL=babylon.groundMesh.js.map
  10136. var BABYLON;
  10137. (function (BABYLON) {
  10138. var InstancedMesh = (function (_super) {
  10139. __extends(InstancedMesh, _super);
  10140. function InstancedMesh(name, source) {
  10141. _super.call(this, name, source.getScene());
  10142. source.instances.push(this);
  10143. this._sourceMesh = source;
  10144. this.position.copyFrom(source.position);
  10145. this.rotation.copyFrom(source.rotation);
  10146. this.scaling.copyFrom(source.scaling);
  10147. if (source.rotationQuaternion) {
  10148. this.rotationQuaternion = source.rotationQuaternion.clone();
  10149. }
  10150. this.infiniteDistance = source.infiniteDistance;
  10151. this.setPivotMatrix(source.getPivotMatrix());
  10152. this.refreshBoundingInfo();
  10153. this._syncSubMeshes();
  10154. }
  10155. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10156. // Methods
  10157. get: function () {
  10158. return this._sourceMesh.receiveShadows;
  10159. },
  10160. enumerable: true,
  10161. configurable: true
  10162. });
  10163. Object.defineProperty(InstancedMesh.prototype, "material", {
  10164. get: function () {
  10165. return this._sourceMesh.material;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10171. get: function () {
  10172. return this._sourceMesh.visibility;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10178. get: function () {
  10179. return this._sourceMesh.skeleton;
  10180. },
  10181. enumerable: true,
  10182. configurable: true
  10183. });
  10184. InstancedMesh.prototype.getTotalVertices = function () {
  10185. return this._sourceMesh.getTotalVertices();
  10186. };
  10187. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10188. get: function () {
  10189. return this._sourceMesh;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. InstancedMesh.prototype.getVerticesData = function (kind) {
  10195. return this._sourceMesh.getVerticesData(kind);
  10196. };
  10197. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10198. return this._sourceMesh.isVerticesDataPresent(kind);
  10199. };
  10200. InstancedMesh.prototype.getIndices = function () {
  10201. return this._sourceMesh.getIndices();
  10202. };
  10203. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10204. get: function () {
  10205. return this._sourceMesh._positions;
  10206. },
  10207. enumerable: true,
  10208. configurable: true
  10209. });
  10210. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10211. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10212. if (data) {
  10213. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10214. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10215. }
  10216. this._updateBoundingInfo();
  10217. };
  10218. InstancedMesh.prototype._preActivate = function () {
  10219. if (this._currentLOD) {
  10220. this._currentLOD._preActivate();
  10221. }
  10222. };
  10223. InstancedMesh.prototype._activate = function (renderId) {
  10224. if (this._currentLOD) {
  10225. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10226. }
  10227. };
  10228. InstancedMesh.prototype.getLOD = function (camera) {
  10229. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10230. return this._currentLOD;
  10231. };
  10232. InstancedMesh.prototype._syncSubMeshes = function () {
  10233. this.releaseSubMeshes();
  10234. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10235. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10236. }
  10237. };
  10238. InstancedMesh.prototype._generatePointsArray = function () {
  10239. return this._sourceMesh._generatePointsArray();
  10240. };
  10241. // Clone
  10242. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10243. var result = this._sourceMesh.createInstance(name);
  10244. // Deep copy
  10245. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10246. // Bounding info
  10247. this.refreshBoundingInfo();
  10248. // Parent
  10249. if (newParent) {
  10250. result.parent = newParent;
  10251. }
  10252. if (!doNotCloneChildren) {
  10253. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10254. var mesh = this.getScene().meshes[index];
  10255. if (mesh.parent == this) {
  10256. mesh.clone(mesh.name, result);
  10257. }
  10258. }
  10259. }
  10260. result.computeWorldMatrix(true);
  10261. return result;
  10262. };
  10263. // Dispoe
  10264. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10265. // Remove from mesh
  10266. var index = this._sourceMesh.instances.indexOf(this);
  10267. this._sourceMesh.instances.splice(index, 1);
  10268. _super.prototype.dispose.call(this, doNotRecurse);
  10269. };
  10270. return InstancedMesh;
  10271. })(BABYLON.AbstractMesh);
  10272. BABYLON.InstancedMesh = InstancedMesh;
  10273. })(BABYLON || (BABYLON = {}));
  10274. //# sourceMappingURL=babylon.instancedMesh.js.map
  10275. var BABYLON;
  10276. (function (BABYLON) {
  10277. var SubMesh = (function () {
  10278. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10279. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10280. this.materialIndex = materialIndex;
  10281. this.verticesStart = verticesStart;
  10282. this.verticesCount = verticesCount;
  10283. this.indexStart = indexStart;
  10284. this.indexCount = indexCount;
  10285. this._renderId = 0;
  10286. this._mesh = mesh;
  10287. this._renderingMesh = renderingMesh || mesh;
  10288. mesh.subMeshes.push(this);
  10289. this._id = mesh.subMeshes.length - 1;
  10290. if (createBoundingBox) {
  10291. this.refreshBoundingInfo();
  10292. }
  10293. }
  10294. SubMesh.prototype.getBoundingInfo = function () {
  10295. return this._boundingInfo;
  10296. };
  10297. SubMesh.prototype.getMesh = function () {
  10298. return this._mesh;
  10299. };
  10300. SubMesh.prototype.getRenderingMesh = function () {
  10301. return this._renderingMesh;
  10302. };
  10303. SubMesh.prototype.getMaterial = function () {
  10304. var rootMaterial = this._renderingMesh.material;
  10305. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10306. var multiMaterial = rootMaterial;
  10307. return multiMaterial.getSubMaterial(this.materialIndex);
  10308. }
  10309. if (!rootMaterial) {
  10310. return this._mesh.getScene().defaultMaterial;
  10311. }
  10312. return rootMaterial;
  10313. };
  10314. // Methods
  10315. SubMesh.prototype.refreshBoundingInfo = function () {
  10316. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10317. if (!data) {
  10318. this._boundingInfo = this._mesh._boundingInfo;
  10319. return;
  10320. }
  10321. var indices = this._renderingMesh.getIndices();
  10322. var extend;
  10323. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10324. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10325. } else {
  10326. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10327. }
  10328. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10329. };
  10330. SubMesh.prototype._checkCollision = function (collider) {
  10331. return this._boundingInfo._checkCollision(collider);
  10332. };
  10333. SubMesh.prototype.updateBoundingInfo = function (world) {
  10334. if (!this._boundingInfo) {
  10335. this.refreshBoundingInfo();
  10336. }
  10337. this._boundingInfo._update(world);
  10338. };
  10339. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10340. return this._boundingInfo.isInFrustum(frustumPlanes);
  10341. };
  10342. SubMesh.prototype.render = function () {
  10343. this._renderingMesh.render(this);
  10344. };
  10345. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10346. if (!this._linesIndexBuffer) {
  10347. var linesIndices = [];
  10348. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10349. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10350. }
  10351. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10352. this.linesIndexCount = linesIndices.length;
  10353. }
  10354. return this._linesIndexBuffer;
  10355. };
  10356. SubMesh.prototype.canIntersects = function (ray) {
  10357. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10358. };
  10359. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10360. var intersectInfo = null;
  10361. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10362. var p0 = positions[indices[index]];
  10363. var p1 = positions[indices[index + 1]];
  10364. var p2 = positions[indices[index + 2]];
  10365. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10366. if (currentIntersectInfo) {
  10367. if (currentIntersectInfo.distance < 0) {
  10368. continue;
  10369. }
  10370. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10371. intersectInfo = currentIntersectInfo;
  10372. intersectInfo.faceId = index / 3;
  10373. if (fastCheck) {
  10374. break;
  10375. }
  10376. }
  10377. }
  10378. }
  10379. return intersectInfo;
  10380. };
  10381. // Clone
  10382. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10383. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10384. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10385. return result;
  10386. };
  10387. // Dispose
  10388. SubMesh.prototype.dispose = function () {
  10389. if (this._linesIndexBuffer) {
  10390. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10391. this._linesIndexBuffer = null;
  10392. }
  10393. // Remove from mesh
  10394. var index = this._mesh.subMeshes.indexOf(this);
  10395. this._mesh.subMeshes.splice(index, 1);
  10396. };
  10397. // Statics
  10398. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10399. var minVertexIndex = Number.MAX_VALUE;
  10400. var maxVertexIndex = -Number.MAX_VALUE;
  10401. renderingMesh = renderingMesh || mesh;
  10402. var indices = renderingMesh.getIndices();
  10403. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10404. var vertexIndex = indices[index];
  10405. if (vertexIndex < minVertexIndex)
  10406. minVertexIndex = vertexIndex;
  10407. if (vertexIndex > maxVertexIndex)
  10408. maxVertexIndex = vertexIndex;
  10409. }
  10410. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10411. };
  10412. return SubMesh;
  10413. })();
  10414. BABYLON.SubMesh = SubMesh;
  10415. })(BABYLON || (BABYLON = {}));
  10416. //# sourceMappingURL=babylon.subMesh.js.map
  10417. var BABYLON;
  10418. (function (BABYLON) {
  10419. var BaseTexture = (function () {
  10420. function BaseTexture(scene) {
  10421. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10422. this.hasAlpha = false;
  10423. this.getAlphaFromRGB = false;
  10424. this.level = 1;
  10425. this.isCube = false;
  10426. this.isRenderTarget = false;
  10427. this.animations = new Array();
  10428. this.coordinatesIndex = 0;
  10429. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10430. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10431. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10432. this.anisotropicFilteringLevel = 4;
  10433. this._scene = scene;
  10434. this._scene.textures.push(this);
  10435. }
  10436. BaseTexture.prototype.getScene = function () {
  10437. return this._scene;
  10438. };
  10439. BaseTexture.prototype.getTextureMatrix = function () {
  10440. return null;
  10441. };
  10442. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10443. return null;
  10444. };
  10445. BaseTexture.prototype.getInternalTexture = function () {
  10446. return this._texture;
  10447. };
  10448. BaseTexture.prototype.isReady = function () {
  10449. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10450. return true;
  10451. }
  10452. if (this._texture) {
  10453. return this._texture.isReady;
  10454. }
  10455. return false;
  10456. };
  10457. BaseTexture.prototype.getSize = function () {
  10458. if (this._texture._width) {
  10459. return { width: this._texture._width, height: this._texture._height };
  10460. }
  10461. if (this._texture._size) {
  10462. return { width: this._texture._size, height: this._texture._size };
  10463. }
  10464. return { width: 0, height: 0 };
  10465. };
  10466. BaseTexture.prototype.getBaseSize = function () {
  10467. if (!this.isReady())
  10468. return { width: 0, height: 0 };
  10469. if (this._texture._size) {
  10470. return { width: this._texture._size, height: this._texture._size };
  10471. }
  10472. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10473. };
  10474. BaseTexture.prototype.scale = function (ratio) {
  10475. };
  10476. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10477. get: function () {
  10478. return false;
  10479. },
  10480. enumerable: true,
  10481. configurable: true
  10482. });
  10483. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10484. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10485. for (var index = 0; index < texturesCache.length; index++) {
  10486. var texturesCacheEntry = texturesCache[index];
  10487. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10488. texturesCache.splice(index, 1);
  10489. return;
  10490. }
  10491. }
  10492. };
  10493. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10494. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10495. for (var index = 0; index < texturesCache.length; index++) {
  10496. var texturesCacheEntry = texturesCache[index];
  10497. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10498. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10499. texturesCacheEntry.references++;
  10500. return texturesCacheEntry;
  10501. }
  10502. }
  10503. }
  10504. return null;
  10505. };
  10506. BaseTexture.prototype.delayLoad = function () {
  10507. };
  10508. BaseTexture.prototype.releaseInternalTexture = function () {
  10509. if (!this._texture) {
  10510. return;
  10511. }
  10512. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10513. this._texture.references--;
  10514. // Final reference ?
  10515. if (this._texture.references === 0) {
  10516. var index = texturesCache.indexOf(this._texture);
  10517. texturesCache.splice(index, 1);
  10518. this._scene.getEngine()._releaseTexture(this._texture);
  10519. delete this._texture;
  10520. }
  10521. };
  10522. BaseTexture.prototype.clone = function () {
  10523. return null;
  10524. };
  10525. BaseTexture.prototype.dispose = function () {
  10526. // Remove from scene
  10527. var index = this._scene.textures.indexOf(this);
  10528. if (index >= 0) {
  10529. this._scene.textures.splice(index, 1);
  10530. }
  10531. if (this._texture === undefined) {
  10532. return;
  10533. }
  10534. this.releaseInternalTexture();
  10535. // Callback
  10536. if (this.onDispose) {
  10537. this.onDispose();
  10538. }
  10539. };
  10540. return BaseTexture;
  10541. })();
  10542. BABYLON.BaseTexture = BaseTexture;
  10543. })(BABYLON || (BABYLON = {}));
  10544. //# sourceMappingURL=babylon.baseTexture.js.map
  10545. var BABYLON;
  10546. (function (BABYLON) {
  10547. var RenderingGroup = (function () {
  10548. function RenderingGroup(index, scene) {
  10549. this.index = index;
  10550. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10551. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10552. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10553. this._scene = scene;
  10554. }
  10555. RenderingGroup.prototype.render = function (customRenderFunction) {
  10556. if (customRenderFunction) {
  10557. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10558. return true;
  10559. }
  10560. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10561. return false;
  10562. }
  10563. var engine = this._scene.getEngine();
  10564. // Opaque
  10565. var subIndex;
  10566. var submesh;
  10567. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10568. submesh = this._opaqueSubMeshes.data[subIndex];
  10569. submesh.render();
  10570. }
  10571. // Alpha test
  10572. engine.setAlphaTesting(true);
  10573. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10574. submesh = this._alphaTestSubMeshes.data[subIndex];
  10575. submesh.render();
  10576. }
  10577. engine.setAlphaTesting(false);
  10578. // Transparent
  10579. if (this._transparentSubMeshes.length) {
  10580. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10581. submesh = this._transparentSubMeshes.data[subIndex];
  10582. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10583. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10584. }
  10585. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10586. sortedArray.sort(function (a, b) {
  10587. // Alpha index first
  10588. if (a._alphaIndex > b._alphaIndex) {
  10589. return 1;
  10590. }
  10591. if (a._alphaIndex < b._alphaIndex) {
  10592. return -1;
  10593. }
  10594. // Then distance to camera
  10595. if (a._distanceToCamera < b._distanceToCamera) {
  10596. return 1;
  10597. }
  10598. if (a._distanceToCamera > b._distanceToCamera) {
  10599. return -1;
  10600. }
  10601. return 0;
  10602. });
  10603. // Rendering
  10604. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10605. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10606. submesh = sortedArray[subIndex];
  10607. submesh.render();
  10608. }
  10609. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10610. }
  10611. return true;
  10612. };
  10613. RenderingGroup.prototype.prepare = function () {
  10614. this._opaqueSubMeshes.reset();
  10615. this._transparentSubMeshes.reset();
  10616. this._alphaTestSubMeshes.reset();
  10617. };
  10618. RenderingGroup.prototype.dispatch = function (subMesh) {
  10619. var material = subMesh.getMaterial();
  10620. var mesh = subMesh.getMesh();
  10621. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10622. this._transparentSubMeshes.push(subMesh);
  10623. } else if (material.needAlphaTesting()) {
  10624. this._alphaTestSubMeshes.push(subMesh);
  10625. } else {
  10626. this._opaqueSubMeshes.push(subMesh); // Opaque
  10627. }
  10628. };
  10629. return RenderingGroup;
  10630. })();
  10631. BABYLON.RenderingGroup = RenderingGroup;
  10632. })(BABYLON || (BABYLON = {}));
  10633. //# sourceMappingURL=babylon.renderingGroup.js.map
  10634. var BABYLON;
  10635. (function (BABYLON) {
  10636. var RenderingManager = (function () {
  10637. function RenderingManager(scene) {
  10638. this._renderingGroups = new Array();
  10639. this._scene = scene;
  10640. }
  10641. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10642. if (this._scene._activeParticleSystems.length === 0) {
  10643. return;
  10644. }
  10645. // Particles
  10646. var beforeParticlesDate = BABYLON.Tools.Now;
  10647. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10648. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10649. if (particleSystem.renderingGroupId !== index) {
  10650. continue;
  10651. }
  10652. this._clearDepthBuffer();
  10653. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10654. this._scene._activeParticles += particleSystem.render();
  10655. }
  10656. }
  10657. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10658. };
  10659. RenderingManager.prototype._renderSprites = function (index) {
  10660. if (this._scene.spriteManagers.length === 0) {
  10661. return;
  10662. }
  10663. // Sprites
  10664. var beforeSpritessDate = BABYLON.Tools.Now;
  10665. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10666. var spriteManager = this._scene.spriteManagers[id];
  10667. if (spriteManager.renderingGroupId === index) {
  10668. this._clearDepthBuffer();
  10669. spriteManager.render();
  10670. }
  10671. }
  10672. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10673. };
  10674. RenderingManager.prototype._clearDepthBuffer = function () {
  10675. if (this._depthBufferAlreadyCleaned) {
  10676. return;
  10677. }
  10678. this._scene.getEngine().clear(0, false, true);
  10679. this._depthBufferAlreadyCleaned = true;
  10680. };
  10681. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10682. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10683. this._depthBufferAlreadyCleaned = false;
  10684. var renderingGroup = this._renderingGroups[index];
  10685. if (renderingGroup) {
  10686. this._clearDepthBuffer();
  10687. if (!renderingGroup.render(customRenderFunction)) {
  10688. this._renderingGroups.splice(index, 1);
  10689. }
  10690. }
  10691. this._renderSprites(index);
  10692. if (renderParticles) {
  10693. this._renderParticles(index, activeMeshes);
  10694. }
  10695. }
  10696. };
  10697. RenderingManager.prototype.reset = function () {
  10698. for (var index in this._renderingGroups) {
  10699. var renderingGroup = this._renderingGroups[index];
  10700. renderingGroup.prepare();
  10701. }
  10702. };
  10703. RenderingManager.prototype.dispatch = function (subMesh) {
  10704. var mesh = subMesh.getMesh();
  10705. var renderingGroupId = mesh.renderingGroupId || 0;
  10706. if (!this._renderingGroups[renderingGroupId]) {
  10707. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10708. }
  10709. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10710. };
  10711. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10712. return RenderingManager;
  10713. })();
  10714. BABYLON.RenderingManager = RenderingManager;
  10715. })(BABYLON || (BABYLON = {}));
  10716. //# sourceMappingURL=babylon.renderingManager.js.map
  10717. var BABYLON;
  10718. (function (BABYLON) {
  10719. var Texture = (function (_super) {
  10720. __extends(Texture, _super);
  10721. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10722. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10723. if (typeof onLoad === "undefined") { onLoad = null; }
  10724. if (typeof onError === "undefined") { onError = null; }
  10725. if (typeof buffer === "undefined") { buffer = null; }
  10726. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10727. _super.call(this, scene);
  10728. this.uOffset = 0;
  10729. this.vOffset = 0;
  10730. this.uScale = 1.0;
  10731. this.vScale = 1.0;
  10732. this.uAng = 0;
  10733. this.vAng = 0;
  10734. this.wAng = 0;
  10735. this.name = url;
  10736. this.url = url;
  10737. this._noMipmap = noMipmap;
  10738. this._invertY = invertY;
  10739. this._samplingMode = samplingMode;
  10740. this._buffer = buffer;
  10741. this._deleteBuffer = deleteBuffer;
  10742. if (!url) {
  10743. return;
  10744. }
  10745. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10746. if (!this._texture) {
  10747. if (!scene.useDelayedTextureLoading) {
  10748. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10749. if (deleteBuffer) {
  10750. delete this._buffer;
  10751. }
  10752. } else {
  10753. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10754. }
  10755. }
  10756. }
  10757. Texture.prototype.delayLoad = function () {
  10758. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10759. return;
  10760. }
  10761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10762. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10763. if (!this._texture) {
  10764. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10765. if (this._deleteBuffer) {
  10766. delete this._buffer;
  10767. }
  10768. }
  10769. };
  10770. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10771. x -= this.uOffset + 0.5;
  10772. y -= this.vOffset + 0.5;
  10773. z -= 0.5;
  10774. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10775. t.x *= this.uScale;
  10776. t.y *= this.vScale;
  10777. t.x += 0.5;
  10778. t.y += 0.5;
  10779. t.z += 0.5;
  10780. };
  10781. Texture.prototype.getTextureMatrix = function () {
  10782. 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) {
  10783. return this._cachedTextureMatrix;
  10784. }
  10785. this._cachedUOffset = this.uOffset;
  10786. this._cachedVOffset = this.vOffset;
  10787. this._cachedUScale = this.uScale;
  10788. this._cachedVScale = this.vScale;
  10789. this._cachedUAng = this.uAng;
  10790. this._cachedVAng = this.vAng;
  10791. this._cachedWAng = this.wAng;
  10792. if (!this._cachedTextureMatrix) {
  10793. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10794. this._rowGenerationMatrix = new BABYLON.Matrix();
  10795. this._t0 = BABYLON.Vector3.Zero();
  10796. this._t1 = BABYLON.Vector3.Zero();
  10797. this._t2 = BABYLON.Vector3.Zero();
  10798. }
  10799. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10800. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10801. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10802. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10803. this._t1.subtractInPlace(this._t0);
  10804. this._t2.subtractInPlace(this._t0);
  10805. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10806. this._cachedTextureMatrix.m[0] = this._t1.x;
  10807. this._cachedTextureMatrix.m[1] = this._t1.y;
  10808. this._cachedTextureMatrix.m[2] = this._t1.z;
  10809. this._cachedTextureMatrix.m[4] = this._t2.x;
  10810. this._cachedTextureMatrix.m[5] = this._t2.y;
  10811. this._cachedTextureMatrix.m[6] = this._t2.z;
  10812. this._cachedTextureMatrix.m[8] = this._t0.x;
  10813. this._cachedTextureMatrix.m[9] = this._t0.y;
  10814. this._cachedTextureMatrix.m[10] = this._t0.z;
  10815. return this._cachedTextureMatrix;
  10816. };
  10817. Texture.prototype.getReflectionTextureMatrix = function () {
  10818. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10819. return this._cachedTextureMatrix;
  10820. }
  10821. if (!this._cachedTextureMatrix) {
  10822. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10823. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10824. }
  10825. this._cachedCoordinatesMode = this.coordinatesMode;
  10826. switch (this.coordinatesMode) {
  10827. case BABYLON.Texture.SPHERICAL_MODE:
  10828. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10829. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10830. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10831. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10832. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10833. break;
  10834. case BABYLON.Texture.PLANAR_MODE:
  10835. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10836. this._cachedTextureMatrix[0] = this.uScale;
  10837. this._cachedTextureMatrix[5] = this.vScale;
  10838. this._cachedTextureMatrix[12] = this.uOffset;
  10839. this._cachedTextureMatrix[13] = this.vOffset;
  10840. break;
  10841. case BABYLON.Texture.PROJECTION_MODE:
  10842. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10843. this._projectionModeMatrix.m[0] = 0.5;
  10844. this._projectionModeMatrix.m[5] = -0.5;
  10845. this._projectionModeMatrix.m[10] = 0.0;
  10846. this._projectionModeMatrix.m[12] = 0.5;
  10847. this._projectionModeMatrix.m[13] = 0.5;
  10848. this._projectionModeMatrix.m[14] = 1.0;
  10849. this._projectionModeMatrix.m[15] = 1.0;
  10850. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10851. break;
  10852. default:
  10853. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10854. break;
  10855. }
  10856. return this._cachedTextureMatrix;
  10857. };
  10858. Texture.prototype.clone = function () {
  10859. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10860. // Base texture
  10861. newTexture.hasAlpha = this.hasAlpha;
  10862. newTexture.level = this.level;
  10863. newTexture.wrapU = this.wrapU;
  10864. newTexture.wrapV = this.wrapV;
  10865. newTexture.coordinatesIndex = this.coordinatesIndex;
  10866. newTexture.coordinatesMode = this.coordinatesMode;
  10867. // Texture
  10868. newTexture.uOffset = this.uOffset;
  10869. newTexture.vOffset = this.vOffset;
  10870. newTexture.uScale = this.uScale;
  10871. newTexture.vScale = this.vScale;
  10872. newTexture.uAng = this.uAng;
  10873. newTexture.vAng = this.vAng;
  10874. newTexture.wAng = this.wAng;
  10875. return newTexture;
  10876. };
  10877. // Statics
  10878. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10879. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10880. if (typeof onLoad === "undefined") { onLoad = null; }
  10881. if (typeof onError === "undefined") { onError = null; }
  10882. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10883. };
  10884. Texture.NEAREST_SAMPLINGMODE = 1;
  10885. Texture.BILINEAR_SAMPLINGMODE = 2;
  10886. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10887. Texture.EXPLICIT_MODE = 0;
  10888. Texture.SPHERICAL_MODE = 1;
  10889. Texture.PLANAR_MODE = 2;
  10890. Texture.CUBIC_MODE = 3;
  10891. Texture.PROJECTION_MODE = 4;
  10892. Texture.SKYBOX_MODE = 5;
  10893. Texture.CLAMP_ADDRESSMODE = 0;
  10894. Texture.WRAP_ADDRESSMODE = 1;
  10895. Texture.MIRROR_ADDRESSMODE = 2;
  10896. return Texture;
  10897. })(BABYLON.BaseTexture);
  10898. BABYLON.Texture = Texture;
  10899. })(BABYLON || (BABYLON = {}));
  10900. //# sourceMappingURL=babylon.texture.js.map
  10901. var BABYLON;
  10902. (function (BABYLON) {
  10903. var CubeTexture = (function (_super) {
  10904. __extends(CubeTexture, _super);
  10905. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10906. _super.call(this, scene);
  10907. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10908. this.name = rootUrl;
  10909. this.url = rootUrl;
  10910. this._noMipmap = noMipmap;
  10911. this.hasAlpha = false;
  10912. this._texture = this._getFromCache(rootUrl, noMipmap);
  10913. if (!extensions) {
  10914. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10915. }
  10916. this._extensions = extensions;
  10917. if (!this._texture) {
  10918. if (!scene.useDelayedTextureLoading) {
  10919. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10920. } else {
  10921. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10922. }
  10923. }
  10924. this.isCube = true;
  10925. this._textureMatrix = BABYLON.Matrix.Identity();
  10926. }
  10927. CubeTexture.prototype.clone = function () {
  10928. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10929. // Base texture
  10930. newTexture.level = this.level;
  10931. newTexture.wrapU = this.wrapU;
  10932. newTexture.wrapV = this.wrapV;
  10933. newTexture.coordinatesIndex = this.coordinatesIndex;
  10934. newTexture.coordinatesMode = this.coordinatesMode;
  10935. return newTexture;
  10936. };
  10937. // Methods
  10938. CubeTexture.prototype.delayLoad = function () {
  10939. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10940. return;
  10941. }
  10942. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10943. this._texture = this._getFromCache(this.url, this._noMipmap);
  10944. if (!this._texture) {
  10945. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10946. }
  10947. };
  10948. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10949. return this._textureMatrix;
  10950. };
  10951. return CubeTexture;
  10952. })(BABYLON.BaseTexture);
  10953. BABYLON.CubeTexture = CubeTexture;
  10954. })(BABYLON || (BABYLON = {}));
  10955. //# sourceMappingURL=babylon.cubeTexture.js.map
  10956. var BABYLON;
  10957. (function (BABYLON) {
  10958. var RenderTargetTexture = (function (_super) {
  10959. __extends(RenderTargetTexture, _super);
  10960. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10961. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10962. _super.call(this, null, scene, !generateMipMaps);
  10963. this.renderList = new Array();
  10964. this.renderParticles = true;
  10965. this.renderSprites = false;
  10966. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10967. this._currentRefreshId = -1;
  10968. this._refreshRate = 1;
  10969. this.name = name;
  10970. this.isRenderTarget = true;
  10971. this._size = size;
  10972. this._generateMipMaps = generateMipMaps;
  10973. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10974. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10975. // Rendering groups
  10976. this._renderingManager = new BABYLON.RenderingManager(scene);
  10977. }
  10978. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10979. this._currentRefreshId = -1;
  10980. };
  10981. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10982. get: function () {
  10983. return this._refreshRate;
  10984. },
  10985. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10986. set: function (value) {
  10987. this._refreshRate = value;
  10988. this.resetRefreshCounter();
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. RenderTargetTexture.prototype._shouldRender = function () {
  10994. if (this._currentRefreshId === -1) {
  10995. this._currentRefreshId = 1;
  10996. return true;
  10997. }
  10998. if (this.refreshRate == this._currentRefreshId) {
  10999. this._currentRefreshId = 1;
  11000. return true;
  11001. }
  11002. this._currentRefreshId++;
  11003. return false;
  11004. };
  11005. RenderTargetTexture.prototype.isReady = function () {
  11006. if (!this.getScene().renderTargetsEnabled) {
  11007. return false;
  11008. }
  11009. return _super.prototype.isReady.call(this);
  11010. };
  11011. RenderTargetTexture.prototype.getRenderSize = function () {
  11012. return this._size;
  11013. };
  11014. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11015. get: function () {
  11016. return true;
  11017. },
  11018. enumerable: true,
  11019. configurable: true
  11020. });
  11021. RenderTargetTexture.prototype.scale = function (ratio) {
  11022. var newSize = this._size * ratio;
  11023. this.resize(newSize, this._generateMipMaps);
  11024. };
  11025. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11026. this.releaseInternalTexture();
  11027. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11028. };
  11029. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11030. var scene = this.getScene();
  11031. var engine = scene.getEngine();
  11032. if (this._waitingRenderList) {
  11033. this.renderList = [];
  11034. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11035. var id = this._waitingRenderList[index];
  11036. this.renderList.push(scene.getMeshByID(id));
  11037. }
  11038. delete this._waitingRenderList;
  11039. }
  11040. if (!this.renderList) {
  11041. return;
  11042. }
  11043. // Bind
  11044. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11045. engine.bindFramebuffer(this._texture);
  11046. }
  11047. // Clear
  11048. engine.clear(scene.clearColor, true, true);
  11049. this._renderingManager.reset();
  11050. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11051. var mesh = this.renderList[meshIndex];
  11052. if (mesh) {
  11053. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11054. // Reset _currentRefreshId
  11055. this.resetRefreshCounter();
  11056. continue;
  11057. }
  11058. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11059. mesh._activate(scene.getRenderId());
  11060. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11061. var subMesh = mesh.subMeshes[subIndex];
  11062. scene._activeVertices += subMesh.indexCount;
  11063. this._renderingManager.dispatch(subMesh);
  11064. }
  11065. }
  11066. }
  11067. }
  11068. if (!this._doNotChangeAspectRatio) {
  11069. scene.updateTransformMatrix(true);
  11070. }
  11071. if (this.onBeforeRender) {
  11072. this.onBeforeRender();
  11073. }
  11074. // Render
  11075. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11076. if (useCameraPostProcess) {
  11077. scene.postProcessManager._finalizeFrame(false, this._texture);
  11078. }
  11079. if (this.onAfterRender) {
  11080. this.onAfterRender();
  11081. }
  11082. // Unbind
  11083. engine.unBindFramebuffer(this._texture);
  11084. if (!this._doNotChangeAspectRatio) {
  11085. scene.updateTransformMatrix(true);
  11086. }
  11087. };
  11088. RenderTargetTexture.prototype.clone = function () {
  11089. var textureSize = this.getSize();
  11090. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11091. // Base texture
  11092. newTexture.hasAlpha = this.hasAlpha;
  11093. newTexture.level = this.level;
  11094. // RenderTarget Texture
  11095. newTexture.coordinatesMode = this.coordinatesMode;
  11096. newTexture.renderList = this.renderList.slice(0);
  11097. return newTexture;
  11098. };
  11099. return RenderTargetTexture;
  11100. })(BABYLON.Texture);
  11101. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11102. })(BABYLON || (BABYLON = {}));
  11103. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11104. var BABYLON;
  11105. (function (BABYLON) {
  11106. var ProceduralTexture = (function (_super) {
  11107. __extends(ProceduralTexture, _super);
  11108. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11109. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11110. _super.call(this, null, scene, !generateMipMaps);
  11111. this._currentRefreshId = -1;
  11112. this._refreshRate = 1;
  11113. this._vertexDeclaration = [2];
  11114. this._vertexStrideSize = 2 * 4;
  11115. this._uniforms = new Array();
  11116. this._samplers = new Array();
  11117. this._textures = new Array();
  11118. this._floats = new Array();
  11119. this._floatsArrays = {};
  11120. this._colors3 = new Array();
  11121. this._colors4 = new Array();
  11122. this._vectors2 = new Array();
  11123. this._vectors3 = new Array();
  11124. this._matrices = new Array();
  11125. this._fallbackTextureUsed = false;
  11126. scene._proceduralTextures.push(this);
  11127. this.name = name;
  11128. this.isRenderTarget = true;
  11129. this._size = size;
  11130. this._generateMipMaps = generateMipMaps;
  11131. this.setFragment(fragment);
  11132. this._fallbackTexture = fallbackTexture;
  11133. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11134. // VBO
  11135. var vertices = [];
  11136. vertices.push(1, 1);
  11137. vertices.push(-1, 1);
  11138. vertices.push(-1, -1);
  11139. vertices.push(1, -1);
  11140. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11141. // Indices
  11142. var indices = [];
  11143. indices.push(0);
  11144. indices.push(1);
  11145. indices.push(2);
  11146. indices.push(0);
  11147. indices.push(2);
  11148. indices.push(3);
  11149. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11150. }
  11151. ProceduralTexture.prototype.reset = function () {
  11152. if (this._effect === undefined) {
  11153. return;
  11154. }
  11155. var engine = this.getScene().getEngine();
  11156. engine._releaseEffect(this._effect);
  11157. };
  11158. ProceduralTexture.prototype.isReady = function () {
  11159. var _this = this;
  11160. var engine = this.getScene().getEngine();
  11161. var shaders;
  11162. if (!this._fragment) {
  11163. return false;
  11164. }
  11165. if (this._fallbackTextureUsed) {
  11166. return true;
  11167. }
  11168. if (this._fragment.fragmentElement !== undefined) {
  11169. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11170. } else {
  11171. shaders = { vertex: "procedural", fragment: this._fragment };
  11172. }
  11173. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11174. _this.releaseInternalTexture();
  11175. if (_this._fallbackTexture) {
  11176. _this._texture = _this._fallbackTexture._texture;
  11177. _this._texture.references++;
  11178. }
  11179. _this._fallbackTextureUsed = true;
  11180. });
  11181. return this._effect.isReady();
  11182. };
  11183. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11184. this._currentRefreshId = -1;
  11185. };
  11186. ProceduralTexture.prototype.setFragment = function (fragment) {
  11187. this._fragment = fragment;
  11188. };
  11189. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11190. get: function () {
  11191. return this._refreshRate;
  11192. },
  11193. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11194. set: function (value) {
  11195. this._refreshRate = value;
  11196. this.resetRefreshCounter();
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. ProceduralTexture.prototype._shouldRender = function () {
  11202. if (!this.isReady() || !this._texture) {
  11203. return false;
  11204. }
  11205. if (this._fallbackTextureUsed) {
  11206. return false;
  11207. }
  11208. if (this._currentRefreshId === -1) {
  11209. this._currentRefreshId = 1;
  11210. return true;
  11211. }
  11212. if (this.refreshRate === this._currentRefreshId) {
  11213. this._currentRefreshId = 1;
  11214. return true;
  11215. }
  11216. this._currentRefreshId++;
  11217. return false;
  11218. };
  11219. ProceduralTexture.prototype.getRenderSize = function () {
  11220. return this._size;
  11221. };
  11222. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11223. if (this._fallbackTextureUsed) {
  11224. return;
  11225. }
  11226. this.releaseInternalTexture();
  11227. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11228. };
  11229. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11230. if (this._uniforms.indexOf(uniformName) === -1) {
  11231. this._uniforms.push(uniformName);
  11232. }
  11233. };
  11234. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11235. if (this._samplers.indexOf(name) === -1) {
  11236. this._samplers.push(name);
  11237. }
  11238. this._textures[name] = texture;
  11239. return this;
  11240. };
  11241. ProceduralTexture.prototype.setFloat = function (name, value) {
  11242. this._checkUniform(name);
  11243. this._floats[name] = value;
  11244. return this;
  11245. };
  11246. ProceduralTexture.prototype.setFloats = function (name, value) {
  11247. this._checkUniform(name);
  11248. this._floatsArrays[name] = value;
  11249. return this;
  11250. };
  11251. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11252. this._checkUniform(name);
  11253. this._colors3[name] = value;
  11254. return this;
  11255. };
  11256. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11257. this._checkUniform(name);
  11258. this._colors4[name] = value;
  11259. return this;
  11260. };
  11261. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11262. this._checkUniform(name);
  11263. this._vectors2[name] = value;
  11264. return this;
  11265. };
  11266. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11267. this._checkUniform(name);
  11268. this._vectors3[name] = value;
  11269. return this;
  11270. };
  11271. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11272. this._checkUniform(name);
  11273. this._matrices[name] = value;
  11274. return this;
  11275. };
  11276. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11277. var scene = this.getScene();
  11278. var engine = scene.getEngine();
  11279. engine.bindFramebuffer(this._texture);
  11280. // Clear
  11281. engine.clear(scene.clearColor, true, true);
  11282. // Render
  11283. engine.enableEffect(this._effect);
  11284. engine.setState(false);
  11285. for (var name in this._textures) {
  11286. this._effect.setTexture(name, this._textures[name]);
  11287. }
  11288. for (name in this._floats) {
  11289. this._effect.setFloat(name, this._floats[name]);
  11290. }
  11291. for (name in this._floatsArrays) {
  11292. this._effect.setArray(name, this._floatsArrays[name]);
  11293. }
  11294. for (name in this._colors3) {
  11295. this._effect.setColor3(name, this._colors3[name]);
  11296. }
  11297. for (name in this._colors4) {
  11298. var color = this._colors4[name];
  11299. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11300. }
  11301. for (name in this._vectors2) {
  11302. this._effect.setVector2(name, this._vectors2[name]);
  11303. }
  11304. for (name in this._vectors3) {
  11305. this._effect.setVector3(name, this._vectors3[name]);
  11306. }
  11307. for (name in this._matrices) {
  11308. this._effect.setMatrix(name, this._matrices[name]);
  11309. }
  11310. // VBOs
  11311. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11312. // Draw order
  11313. engine.draw(true, 0, 6);
  11314. // Unbind
  11315. engine.unBindFramebuffer(this._texture);
  11316. };
  11317. ProceduralTexture.prototype.clone = function () {
  11318. var textureSize = this.getSize();
  11319. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11320. // Base texture
  11321. newTexture.hasAlpha = this.hasAlpha;
  11322. newTexture.level = this.level;
  11323. // RenderTarget Texture
  11324. newTexture.coordinatesMode = this.coordinatesMode;
  11325. return newTexture;
  11326. };
  11327. ProceduralTexture.prototype.dispose = function () {
  11328. var index = this.getScene()._proceduralTextures.indexOf(this);
  11329. if (index >= 0) {
  11330. this.getScene()._proceduralTextures.splice(index, 1);
  11331. }
  11332. _super.prototype.dispose.call(this);
  11333. };
  11334. return ProceduralTexture;
  11335. })(BABYLON.Texture);
  11336. BABYLON.ProceduralTexture = ProceduralTexture;
  11337. })(BABYLON || (BABYLON = {}));
  11338. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11339. var BABYLON;
  11340. (function (BABYLON) {
  11341. var WoodProceduralTexture = (function (_super) {
  11342. __extends(WoodProceduralTexture, _super);
  11343. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11344. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11345. this._ampScale = 100.0;
  11346. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11347. this.updateShaderUniforms();
  11348. this.refreshRate = 0;
  11349. }
  11350. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11351. this.setFloat("ampScale", this._ampScale);
  11352. this.setColor3("woodColor", this._woodColor);
  11353. };
  11354. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11355. get: function () {
  11356. return this._ampScale;
  11357. },
  11358. set: function (value) {
  11359. this._ampScale = value;
  11360. this.updateShaderUniforms();
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11366. get: function () {
  11367. return this._woodColor;
  11368. },
  11369. set: function (value) {
  11370. this._woodColor = value;
  11371. this.updateShaderUniforms();
  11372. },
  11373. enumerable: true,
  11374. configurable: true
  11375. });
  11376. return WoodProceduralTexture;
  11377. })(BABYLON.ProceduralTexture);
  11378. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11379. var FireProceduralTexture = (function (_super) {
  11380. __extends(FireProceduralTexture, _super);
  11381. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11382. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11383. this._time = 0.0;
  11384. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11385. this._shift = 1.6;
  11386. this._autoGenerateTime = true;
  11387. this._alphaThreshold = 0.5;
  11388. this._fireColors = FireProceduralTexture.RedFireColors;
  11389. this.updateShaderUniforms();
  11390. this.refreshRate = 1;
  11391. }
  11392. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11393. this.setFloat("time", this._time);
  11394. this.setVector2("speed", this._speed);
  11395. this.setFloat("shift", this._shift);
  11396. this.setColor3("c1", this._fireColors[0]);
  11397. this.setColor3("c2", this._fireColors[1]);
  11398. this.setColor3("c3", this._fireColors[2]);
  11399. this.setColor3("c4", this._fireColors[3]);
  11400. this.setColor3("c5", this._fireColors[4]);
  11401. this.setColor3("c6", this._fireColors[5]);
  11402. this.setFloat("alphaThreshold", this._alphaThreshold);
  11403. };
  11404. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11405. if (this._autoGenerateTime) {
  11406. this._time += this.getScene().getAnimationRatio() * 0.03;
  11407. this.updateShaderUniforms();
  11408. }
  11409. _super.prototype.render.call(this, useCameraPostProcess);
  11410. };
  11411. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11412. get: function () {
  11413. return [
  11414. new BABYLON.Color3(0.5, 0.0, 1.0),
  11415. new BABYLON.Color3(0.9, 0.0, 1.0),
  11416. new BABYLON.Color3(0.2, 0.0, 1.0),
  11417. new BABYLON.Color3(1.0, 0.9, 1.0),
  11418. new BABYLON.Color3(0.1, 0.1, 1.0),
  11419. new BABYLON.Color3(0.9, 0.9, 1.0)
  11420. ];
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11426. get: function () {
  11427. return [
  11428. new BABYLON.Color3(0.5, 1.0, 0.0),
  11429. new BABYLON.Color3(0.5, 1.0, 0.0),
  11430. new BABYLON.Color3(0.3, 0.4, 0.0),
  11431. new BABYLON.Color3(0.5, 1.0, 0.0),
  11432. new BABYLON.Color3(0.2, 0.0, 0.0),
  11433. new BABYLON.Color3(0.5, 1.0, 0.0)
  11434. ];
  11435. },
  11436. enumerable: true,
  11437. configurable: true
  11438. });
  11439. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11440. get: function () {
  11441. return [
  11442. new BABYLON.Color3(0.5, 0.0, 0.1),
  11443. new BABYLON.Color3(0.9, 0.0, 0.0),
  11444. new BABYLON.Color3(0.2, 0.0, 0.0),
  11445. new BABYLON.Color3(1.0, 0.9, 0.0),
  11446. new BABYLON.Color3(0.1, 0.1, 0.1),
  11447. new BABYLON.Color3(0.9, 0.9, 0.9)
  11448. ];
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11454. get: function () {
  11455. return [
  11456. new BABYLON.Color3(0.1, 0.0, 0.5),
  11457. new BABYLON.Color3(0.0, 0.0, 0.5),
  11458. new BABYLON.Color3(0.1, 0.0, 0.2),
  11459. new BABYLON.Color3(0.0, 0.0, 1.0),
  11460. new BABYLON.Color3(0.1, 0.2, 0.3),
  11461. new BABYLON.Color3(0.0, 0.2, 0.9)
  11462. ];
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11468. get: function () {
  11469. return this._fireColors;
  11470. },
  11471. set: function (value) {
  11472. this._fireColors = value;
  11473. this.updateShaderUniforms();
  11474. },
  11475. enumerable: true,
  11476. configurable: true
  11477. });
  11478. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11479. get: function () {
  11480. return this._time;
  11481. },
  11482. set: function (value) {
  11483. this._time = value;
  11484. this.updateShaderUniforms();
  11485. },
  11486. enumerable: true,
  11487. configurable: true
  11488. });
  11489. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11490. get: function () {
  11491. return this._speed;
  11492. },
  11493. set: function (value) {
  11494. this._speed = value;
  11495. this.updateShaderUniforms();
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11501. get: function () {
  11502. return this._shift;
  11503. },
  11504. set: function (value) {
  11505. this._shift = value;
  11506. this.updateShaderUniforms();
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11512. get: function () {
  11513. return this._alphaThreshold;
  11514. },
  11515. set: function (value) {
  11516. this._alphaThreshold = value;
  11517. this.updateShaderUniforms();
  11518. },
  11519. enumerable: true,
  11520. configurable: true
  11521. });
  11522. return FireProceduralTexture;
  11523. })(BABYLON.ProceduralTexture);
  11524. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11525. var CloudProceduralTexture = (function (_super) {
  11526. __extends(CloudProceduralTexture, _super);
  11527. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11528. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11529. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11530. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11531. this.updateShaderUniforms();
  11532. this.refreshRate = 0;
  11533. }
  11534. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11535. this.setColor3("skyColor", this._skyColor);
  11536. this.setColor3("cloudColor", this._cloudColor);
  11537. };
  11538. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11539. get: function () {
  11540. return this._skyColor;
  11541. },
  11542. set: function (value) {
  11543. this._skyColor = value;
  11544. this.updateShaderUniforms();
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11550. get: function () {
  11551. return this._cloudColor;
  11552. },
  11553. set: function (value) {
  11554. this._cloudColor = value;
  11555. this.updateShaderUniforms();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. return CloudProceduralTexture;
  11561. })(BABYLON.ProceduralTexture);
  11562. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11563. var GrassProceduralTexture = (function (_super) {
  11564. __extends(GrassProceduralTexture, _super);
  11565. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11566. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11567. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11568. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11569. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11570. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11571. this._grassColors = [
  11572. new BABYLON.Color3(0.29, 0.38, 0.02),
  11573. new BABYLON.Color3(0.36, 0.49, 0.09),
  11574. new BABYLON.Color3(0.51, 0.6, 0.28)
  11575. ];
  11576. this.updateShaderUniforms();
  11577. this.refreshRate = 0;
  11578. }
  11579. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11580. this.setColor3("herb1Color", this._grassColors[0]);
  11581. this.setColor3("herb2Color", this._grassColors[1]);
  11582. this.setColor3("herb3Color", this._grassColors[2]);
  11583. this.setColor3("groundColor", this._groundColor);
  11584. };
  11585. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11586. get: function () {
  11587. return this._grassColors;
  11588. },
  11589. set: function (value) {
  11590. this._grassColors = value;
  11591. this.updateShaderUniforms();
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11597. get: function () {
  11598. return this._groundColor;
  11599. },
  11600. set: function (value) {
  11601. this.groundColor = value;
  11602. this.updateShaderUniforms();
  11603. },
  11604. enumerable: true,
  11605. configurable: true
  11606. });
  11607. return GrassProceduralTexture;
  11608. })(BABYLON.ProceduralTexture);
  11609. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11610. var RoadProceduralTexture = (function (_super) {
  11611. __extends(RoadProceduralTexture, _super);
  11612. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11613. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11614. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11615. this.updateShaderUniforms();
  11616. this.refreshRate = 0;
  11617. }
  11618. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11619. this.setColor3("roadColor", this._roadColor);
  11620. };
  11621. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11622. get: function () {
  11623. return this._roadColor;
  11624. },
  11625. set: function (value) {
  11626. this._roadColor = value;
  11627. this.updateShaderUniforms();
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. return RoadProceduralTexture;
  11633. })(BABYLON.ProceduralTexture);
  11634. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11635. var BrickProceduralTexture = (function (_super) {
  11636. __extends(BrickProceduralTexture, _super);
  11637. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11638. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11639. this._numberOfBricksHeight = 15;
  11640. this._numberOfBricksWidth = 5;
  11641. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11642. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11643. this.updateShaderUniforms();
  11644. this.refreshRate = 0;
  11645. }
  11646. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11647. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11648. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11649. this.setColor3("brickColor", this._brickColor);
  11650. this.setColor3("jointColor", this._jointColor);
  11651. };
  11652. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11653. get: function () {
  11654. return this._numberOfBricksHeight;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11660. set: function (value) {
  11661. this._numberOfBricksHeight = value;
  11662. this.updateShaderUniforms();
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11668. get: function () {
  11669. return this._numberOfBricksWidth;
  11670. },
  11671. set: function (value) {
  11672. this._numberOfBricksHeight = value;
  11673. this.updateShaderUniforms();
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11679. get: function () {
  11680. return this._jointColor;
  11681. },
  11682. set: function (value) {
  11683. this._jointColor = value;
  11684. this.updateShaderUniforms();
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11690. get: function () {
  11691. return this._brickColor;
  11692. },
  11693. set: function (value) {
  11694. this._brickColor = value;
  11695. this.updateShaderUniforms();
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. return BrickProceduralTexture;
  11701. })(BABYLON.ProceduralTexture);
  11702. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11703. var MarbleProceduralTexture = (function (_super) {
  11704. __extends(MarbleProceduralTexture, _super);
  11705. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11706. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11707. this._numberOfTilesHeight = 3;
  11708. this._numberOfTilesWidth = 3;
  11709. this._amplitude = 9.0;
  11710. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11711. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11712. this.updateShaderUniforms();
  11713. this.refreshRate = 0;
  11714. }
  11715. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11716. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11717. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11718. this.setFloat("amplitude", this._amplitude);
  11719. this.setColor3("marbleColor", this._marbleColor);
  11720. this.setColor3("jointColor", this._jointColor);
  11721. };
  11722. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11723. get: function () {
  11724. return this._numberOfTilesHeight;
  11725. },
  11726. set: function (value) {
  11727. this._numberOfTilesHeight = value;
  11728. this.updateShaderUniforms();
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11734. get: function () {
  11735. return this._numberOfTilesWidth;
  11736. },
  11737. set: function (value) {
  11738. this._numberOfTilesWidth = value;
  11739. this.updateShaderUniforms();
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11745. get: function () {
  11746. return this._jointColor;
  11747. },
  11748. set: function (value) {
  11749. this._jointColor = value;
  11750. this.updateShaderUniforms();
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11756. get: function () {
  11757. return this._marbleColor;
  11758. },
  11759. set: function (value) {
  11760. this._marbleColor = value;
  11761. this.updateShaderUniforms();
  11762. },
  11763. enumerable: true,
  11764. configurable: true
  11765. });
  11766. return MarbleProceduralTexture;
  11767. })(BABYLON.ProceduralTexture);
  11768. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11769. })(BABYLON || (BABYLON = {}));
  11770. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11771. var BABYLON;
  11772. (function (BABYLON) {
  11773. var CustomProceduralTexture = (function (_super) {
  11774. __extends(CustomProceduralTexture, _super);
  11775. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11776. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11777. this._animate = true;
  11778. this._time = 0;
  11779. this._texturePath = texturePath;
  11780. //Try to load json
  11781. this.loadJson(texturePath);
  11782. this.refreshRate = 1;
  11783. }
  11784. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11785. var _this = this;
  11786. var that = this;
  11787. function noConfigFile() {
  11788. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11789. try {
  11790. that.setFragment(that._texturePath);
  11791. } catch (ex) {
  11792. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11793. }
  11794. }
  11795. var configFileUrl = jsonUrl + "/config.json";
  11796. var xhr = new XMLHttpRequest();
  11797. xhr.open("GET", configFileUrl, true);
  11798. xhr.addEventListener("load", function () {
  11799. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11800. try {
  11801. _this._config = JSON.parse(xhr.response);
  11802. _this.updateShaderUniforms();
  11803. _this.updateTextures();
  11804. _this.setFragment(_this._texturePath + "/custom");
  11805. _this._animate = _this._config.animate;
  11806. _this.refreshRate = _this._config.refreshrate;
  11807. } catch (ex) {
  11808. noConfigFile();
  11809. }
  11810. } else {
  11811. noConfigFile();
  11812. }
  11813. }, false);
  11814. xhr.addEventListener("error", function (event) {
  11815. noConfigFile();
  11816. }, false);
  11817. try {
  11818. xhr.send();
  11819. } catch (ex) {
  11820. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11821. }
  11822. };
  11823. CustomProceduralTexture.prototype.isReady = function () {
  11824. if (!_super.prototype.isReady.call(this)) {
  11825. return false;
  11826. }
  11827. for (var name in this._textures) {
  11828. var texture = this._textures[name];
  11829. if (!texture.isReady()) {
  11830. return false;
  11831. }
  11832. }
  11833. return true;
  11834. };
  11835. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11836. if (this._animate) {
  11837. this._time += this.getScene().getAnimationRatio() * 0.03;
  11838. this.updateShaderUniforms();
  11839. }
  11840. _super.prototype.render.call(this, useCameraPostProcess);
  11841. };
  11842. CustomProceduralTexture.prototype.updateTextures = function () {
  11843. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11844. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11845. }
  11846. };
  11847. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11848. if (this._config) {
  11849. for (var j = 0; j < this._config.uniforms.length; j++) {
  11850. var uniform = this._config.uniforms[j];
  11851. switch (uniform.type) {
  11852. case "float":
  11853. this.setFloat(uniform.name, uniform.value);
  11854. break;
  11855. case "color3":
  11856. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11857. break;
  11858. case "color4":
  11859. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11860. break;
  11861. case "vector2":
  11862. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11863. break;
  11864. case "vector3":
  11865. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11866. break;
  11867. }
  11868. }
  11869. }
  11870. this.setFloat("time", this._time);
  11871. };
  11872. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11873. get: function () {
  11874. return this._animate;
  11875. },
  11876. set: function (value) {
  11877. this._animate = value;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. return CustomProceduralTexture;
  11883. })(BABYLON.ProceduralTexture);
  11884. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11885. })(BABYLON || (BABYLON = {}));
  11886. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11887. var BABYLON;
  11888. (function (BABYLON) {
  11889. var MirrorTexture = (function (_super) {
  11890. __extends(MirrorTexture, _super);
  11891. function MirrorTexture(name, size, scene, generateMipMaps) {
  11892. var _this = this;
  11893. _super.call(this, name, size, scene, generateMipMaps, true);
  11894. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11895. this._transformMatrix = BABYLON.Matrix.Zero();
  11896. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11897. this.onBeforeRender = function () {
  11898. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11899. _this._savedViewMatrix = scene.getViewMatrix();
  11900. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11901. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11902. scene.clipPlane = _this.mirrorPlane;
  11903. scene.getEngine().cullBackFaces = false;
  11904. };
  11905. this.onAfterRender = function () {
  11906. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11907. scene.getEngine().cullBackFaces = true;
  11908. delete scene.clipPlane;
  11909. };
  11910. }
  11911. MirrorTexture.prototype.clone = function () {
  11912. var textureSize = this.getSize();
  11913. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11914. // Base texture
  11915. newTexture.hasAlpha = this.hasAlpha;
  11916. newTexture.level = this.level;
  11917. // Mirror Texture
  11918. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11919. newTexture.renderList = this.renderList.slice(0);
  11920. return newTexture;
  11921. };
  11922. return MirrorTexture;
  11923. })(BABYLON.RenderTargetTexture);
  11924. BABYLON.MirrorTexture = MirrorTexture;
  11925. })(BABYLON || (BABYLON = {}));
  11926. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11927. var BABYLON;
  11928. (function (BABYLON) {
  11929. var DynamicTexture = (function (_super) {
  11930. __extends(DynamicTexture, _super);
  11931. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11932. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11933. _super.call(this, null, scene, !generateMipMaps);
  11934. this.name = name;
  11935. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11936. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11937. this._generateMipMaps = generateMipMaps;
  11938. if (options.getContext) {
  11939. this._canvas = options;
  11940. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11941. } else {
  11942. this._canvas = document.createElement("canvas");
  11943. if (options.width) {
  11944. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11945. } else {
  11946. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11947. }
  11948. }
  11949. var textureSize = this.getSize();
  11950. this._canvas.width = textureSize.width;
  11951. this._canvas.height = textureSize.height;
  11952. this._context = this._canvas.getContext("2d");
  11953. }
  11954. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11955. get: function () {
  11956. return true;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. DynamicTexture.prototype.scale = function (ratio) {
  11962. var textureSize = this.getSize();
  11963. textureSize.width *= ratio;
  11964. textureSize.height *= ratio;
  11965. this._canvas.width = textureSize.width;
  11966. this._canvas.height = textureSize.height;
  11967. this.releaseInternalTexture();
  11968. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11969. };
  11970. DynamicTexture.prototype.getContext = function () {
  11971. return this._context;
  11972. };
  11973. DynamicTexture.prototype.update = function (invertY) {
  11974. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11975. };
  11976. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11977. var size = this.getSize();
  11978. if (clearColor) {
  11979. this._context.fillStyle = clearColor;
  11980. this._context.fillRect(0, 0, size.width, size.height);
  11981. }
  11982. this._context.font = font;
  11983. if (x === null) {
  11984. var textSize = this._context.measureText(text);
  11985. x = (size.width - textSize.width) / 2;
  11986. }
  11987. this._context.fillStyle = color;
  11988. this._context.fillText(text, x, y);
  11989. this.update(invertY);
  11990. };
  11991. DynamicTexture.prototype.clone = function () {
  11992. var textureSize = this.getSize();
  11993. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11994. // Base texture
  11995. newTexture.hasAlpha = this.hasAlpha;
  11996. newTexture.level = this.level;
  11997. // Dynamic Texture
  11998. newTexture.wrapU = this.wrapU;
  11999. newTexture.wrapV = this.wrapV;
  12000. return newTexture;
  12001. };
  12002. return DynamicTexture;
  12003. })(BABYLON.Texture);
  12004. BABYLON.DynamicTexture = DynamicTexture;
  12005. })(BABYLON || (BABYLON = {}));
  12006. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12007. var BABYLON;
  12008. (function (BABYLON) {
  12009. var VideoTexture = (function (_super) {
  12010. __extends(VideoTexture, _super);
  12011. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12012. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12013. var _this = this;
  12014. _super.call(this, null, scene, !generateMipMaps, invertY);
  12015. this._autoLaunch = true;
  12016. this.name = name;
  12017. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12018. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12019. var requiredWidth = size.width || size;
  12020. var requiredHeight = size.height || size;
  12021. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12022. var textureSize = this.getSize();
  12023. this.video = document.createElement("video");
  12024. this.video.width = textureSize.width;
  12025. this.video.height = textureSize.height;
  12026. this.video.autoplay = false;
  12027. this.video.loop = true;
  12028. this.video.addEventListener("canplaythrough", function () {
  12029. if (_this._texture) {
  12030. _this._texture.isReady = true;
  12031. }
  12032. });
  12033. urls.forEach(function (url) {
  12034. var source = document.createElement("source");
  12035. source.src = url;
  12036. _this.video.appendChild(source);
  12037. });
  12038. this._lastUpdate = BABYLON.Tools.Now;
  12039. }
  12040. VideoTexture.prototype.update = function () {
  12041. if (this._autoLaunch) {
  12042. this._autoLaunch = false;
  12043. this.video.play();
  12044. }
  12045. var now = BABYLON.Tools.Now;
  12046. if (now - this._lastUpdate < 15) {
  12047. return false;
  12048. }
  12049. this._lastUpdate = now;
  12050. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12051. return true;
  12052. };
  12053. return VideoTexture;
  12054. })(BABYLON.Texture);
  12055. BABYLON.VideoTexture = VideoTexture;
  12056. })(BABYLON || (BABYLON = {}));
  12057. //# sourceMappingURL=babylon.videoTexture.js.map
  12058. var BABYLON;
  12059. (function (BABYLON) {
  12060. var EffectFallbacks = (function () {
  12061. function EffectFallbacks() {
  12062. this._defines = {};
  12063. this._currentRank = 32;
  12064. this._maxRank = -1;
  12065. }
  12066. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12067. if (!this._defines[rank]) {
  12068. if (rank < this._currentRank) {
  12069. this._currentRank = rank;
  12070. }
  12071. if (rank > this._maxRank) {
  12072. this._maxRank = rank;
  12073. }
  12074. this._defines[rank] = new Array();
  12075. }
  12076. this._defines[rank].push(define);
  12077. };
  12078. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12079. get: function () {
  12080. return this._currentRank <= this._maxRank;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12086. var currentFallbacks = this._defines[this._currentRank];
  12087. for (var index = 0; index < currentFallbacks.length; index++) {
  12088. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12089. }
  12090. this._currentRank++;
  12091. return currentDefines;
  12092. };
  12093. return EffectFallbacks;
  12094. })();
  12095. BABYLON.EffectFallbacks = EffectFallbacks;
  12096. var Effect = (function () {
  12097. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12098. var _this = this;
  12099. this._isReady = false;
  12100. this._compilationError = "";
  12101. this._valueCache = [];
  12102. this._engine = engine;
  12103. this.name = baseName;
  12104. this.defines = defines;
  12105. this._uniformsNames = uniformsNames.concat(samplers);
  12106. this._samplers = samplers;
  12107. this._attributesNames = attributesNames;
  12108. this.onError = onError;
  12109. this.onCompiled = onCompiled;
  12110. var vertexSource;
  12111. var fragmentSource;
  12112. if (baseName.vertexElement) {
  12113. vertexSource = document.getElementById(baseName.vertexElement);
  12114. if (!vertexSource) {
  12115. vertexSource = baseName.vertexElement;
  12116. }
  12117. } else {
  12118. vertexSource = baseName.vertex || baseName;
  12119. }
  12120. if (baseName.fragmentElement) {
  12121. fragmentSource = document.getElementById(baseName.fragmentElement);
  12122. if (!fragmentSource) {
  12123. fragmentSource = baseName.fragmentElement;
  12124. }
  12125. } else {
  12126. fragmentSource = baseName.fragment || baseName;
  12127. }
  12128. this._loadVertexShader(vertexSource, function (vertexCode) {
  12129. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12130. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12131. });
  12132. });
  12133. }
  12134. // Properties
  12135. Effect.prototype.isReady = function () {
  12136. return this._isReady;
  12137. };
  12138. Effect.prototype.getProgram = function () {
  12139. return this._program;
  12140. };
  12141. Effect.prototype.getAttributesNames = function () {
  12142. return this._attributesNames;
  12143. };
  12144. Effect.prototype.getAttributeLocation = function (index) {
  12145. return this._attributes[index];
  12146. };
  12147. Effect.prototype.getAttributeLocationByName = function (name) {
  12148. var index = this._attributesNames.indexOf(name);
  12149. return this._attributes[index];
  12150. };
  12151. Effect.prototype.getAttributesCount = function () {
  12152. return this._attributes.length;
  12153. };
  12154. Effect.prototype.getUniformIndex = function (uniformName) {
  12155. return this._uniformsNames.indexOf(uniformName);
  12156. };
  12157. Effect.prototype.getUniform = function (uniformName) {
  12158. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12159. };
  12160. Effect.prototype.getSamplers = function () {
  12161. return this._samplers;
  12162. };
  12163. Effect.prototype.getCompilationError = function () {
  12164. return this._compilationError;
  12165. };
  12166. // Methods
  12167. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12168. // DOM element ?
  12169. if (vertex instanceof HTMLElement) {
  12170. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12171. callback(vertexCode);
  12172. return;
  12173. }
  12174. // Is in local store ?
  12175. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12176. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12177. return;
  12178. }
  12179. var vertexShaderUrl;
  12180. if (vertex[0] === ".") {
  12181. vertexShaderUrl = vertex;
  12182. } else {
  12183. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12184. }
  12185. // Vertex shader
  12186. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12187. };
  12188. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12189. // DOM element ?
  12190. if (fragment instanceof HTMLElement) {
  12191. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12192. callback(fragmentCode);
  12193. return;
  12194. }
  12195. // Is in local store ?
  12196. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12197. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12198. return;
  12199. }
  12200. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12201. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12202. return;
  12203. }
  12204. var fragmentShaderUrl;
  12205. if (fragment[0] === ".") {
  12206. fragmentShaderUrl = fragment;
  12207. } else {
  12208. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12209. }
  12210. // Fragment shader
  12211. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12212. };
  12213. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12214. try {
  12215. var engine = this._engine;
  12216. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12217. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12218. this._attributes = engine.getAttributes(this._program, attributesNames);
  12219. for (var index = 0; index < this._samplers.length; index++) {
  12220. var sampler = this.getUniform(this._samplers[index]);
  12221. if (sampler == null) {
  12222. this._samplers.splice(index, 1);
  12223. index--;
  12224. }
  12225. }
  12226. engine.bindSamplers(this);
  12227. this._isReady = true;
  12228. if (this.onCompiled) {
  12229. this.onCompiled(this);
  12230. }
  12231. } catch (e) {
  12232. // Is it a problem with precision?
  12233. if (e.message.indexOf("highp") !== -1) {
  12234. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12235. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12236. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12237. return;
  12238. }
  12239. // Let's go through fallbacks then
  12240. if (fallbacks && fallbacks.isMoreFallbacks) {
  12241. defines = fallbacks.reduce(defines);
  12242. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12243. } else {
  12244. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12245. BABYLON.Tools.Error("Defines: " + defines);
  12246. BABYLON.Tools.Error("Error: " + e.message);
  12247. this._compilationError = e.message;
  12248. if (this.onError) {
  12249. this.onError(this, this._compilationError);
  12250. }
  12251. }
  12252. }
  12253. };
  12254. Effect.prototype._bindTexture = function (channel, texture) {
  12255. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12256. };
  12257. Effect.prototype.setTexture = function (channel, texture) {
  12258. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12259. };
  12260. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12261. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12262. };
  12263. //public _cacheMatrix(uniformName, matrix) {
  12264. // if (!this._valueCache[uniformName]) {
  12265. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12266. // }
  12267. // for (var index = 0; index < 16; index++) {
  12268. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12269. // }
  12270. //};
  12271. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12272. if (!this._valueCache[uniformName]) {
  12273. this._valueCache[uniformName] = [x, y];
  12274. return;
  12275. }
  12276. this._valueCache[uniformName][0] = x;
  12277. this._valueCache[uniformName][1] = y;
  12278. };
  12279. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12280. if (!this._valueCache[uniformName]) {
  12281. this._valueCache[uniformName] = [x, y, z];
  12282. return;
  12283. }
  12284. this._valueCache[uniformName][0] = x;
  12285. this._valueCache[uniformName][1] = y;
  12286. this._valueCache[uniformName][2] = z;
  12287. };
  12288. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12289. if (!this._valueCache[uniformName]) {
  12290. this._valueCache[uniformName] = [x, y, z, w];
  12291. return;
  12292. }
  12293. this._valueCache[uniformName][0] = x;
  12294. this._valueCache[uniformName][1] = y;
  12295. this._valueCache[uniformName][2] = z;
  12296. this._valueCache[uniformName][3] = w;
  12297. };
  12298. Effect.prototype.setArray = function (uniformName, array) {
  12299. this._engine.setArray(this.getUniform(uniformName), array);
  12300. return this;
  12301. };
  12302. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12303. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12304. return this;
  12305. };
  12306. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12307. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12308. // return;
  12309. //this._cacheMatrix(uniformName, matrix);
  12310. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12311. return this;
  12312. };
  12313. Effect.prototype.setFloat = function (uniformName, value) {
  12314. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12315. return this;
  12316. this._valueCache[uniformName] = value;
  12317. this._engine.setFloat(this.getUniform(uniformName), value);
  12318. return this;
  12319. };
  12320. Effect.prototype.setBool = function (uniformName, bool) {
  12321. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12322. return this;
  12323. this._valueCache[uniformName] = bool;
  12324. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12325. return this;
  12326. };
  12327. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12328. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12329. return this;
  12330. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12331. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12332. return this;
  12333. };
  12334. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12335. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12336. return this;
  12337. this._cacheFloat2(uniformName, x, y);
  12338. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12339. return this;
  12340. };
  12341. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12342. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12343. return this;
  12344. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12345. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12346. return this;
  12347. };
  12348. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12349. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12350. return this;
  12351. this._cacheFloat3(uniformName, x, y, z);
  12352. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12353. return this;
  12354. };
  12355. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12356. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12357. return this;
  12358. this._cacheFloat4(uniformName, x, y, z, w);
  12359. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12360. return this;
  12361. };
  12362. Effect.prototype.setColor3 = function (uniformName, color3) {
  12363. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12364. return this;
  12365. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12366. this._engine.setColor3(this.getUniform(uniformName), color3);
  12367. return this;
  12368. };
  12369. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12370. 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)
  12371. return this;
  12372. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12373. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12374. return this;
  12375. };
  12376. 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}",
  12377. 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}",
  12378. 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}",
  12379. 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}",
  12380. 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}",
  12381. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12382. 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}",
  12383. 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}",
  12384. 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}",
  12385. 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}",
  12386. 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}",
  12387. 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}",
  12388. 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}",
  12389. 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}",
  12390. 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}",
  12391. 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}",
  12392. 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}",
  12393. 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}",
  12394. 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}",
  12395. 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}",
  12396. 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}",
  12397. 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}",
  12398. 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}",
  12399. 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}",
  12400. 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}",
  12401. 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}",
  12402. 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}",
  12403. 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}",
  12404. 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}",
  12405. 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}",
  12406. 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}",
  12407. 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}",
  12408. 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}",
  12409. 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}",
  12410. 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}",
  12411. 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}",
  12412. 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}",
  12413. };
  12414. return Effect;
  12415. })();
  12416. BABYLON.Effect = Effect;
  12417. })(BABYLON || (BABYLON = {}));
  12418. //# sourceMappingURL=babylon.effect.js.map
  12419. var BABYLON;
  12420. (function (BABYLON) {
  12421. var Material = (function () {
  12422. function Material(name, scene, doNotAdd) {
  12423. this.name = name;
  12424. this.checkReadyOnEveryCall = true;
  12425. this.checkReadyOnlyOnce = false;
  12426. this.state = "";
  12427. this.alpha = 1.0;
  12428. this.backFaceCulling = true;
  12429. this._wasPreviouslyReady = false;
  12430. this._fillMode = Material.TriangleFillMode;
  12431. this.pointSize = 1.0;
  12432. this.id = name;
  12433. this._scene = scene;
  12434. if (!doNotAdd) {
  12435. scene.materials.push(this);
  12436. }
  12437. }
  12438. Object.defineProperty(Material, "TriangleFillMode", {
  12439. get: function () {
  12440. return Material._TriangleFillMode;
  12441. },
  12442. enumerable: true,
  12443. configurable: true
  12444. });
  12445. Object.defineProperty(Material, "WireFrameFillMode", {
  12446. get: function () {
  12447. return Material._WireFrameFillMode;
  12448. },
  12449. enumerable: true,
  12450. configurable: true
  12451. });
  12452. Object.defineProperty(Material, "PointFillMode", {
  12453. get: function () {
  12454. return Material._PointFillMode;
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Material.prototype, "wireframe", {
  12460. get: function () {
  12461. return this._fillMode === Material.WireFrameFillMode;
  12462. },
  12463. set: function (value) {
  12464. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12465. },
  12466. enumerable: true,
  12467. configurable: true
  12468. });
  12469. Object.defineProperty(Material.prototype, "pointsCloud", {
  12470. get: function () {
  12471. return this._fillMode === Material.PointFillMode;
  12472. },
  12473. set: function (value) {
  12474. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. Object.defineProperty(Material.prototype, "fillMode", {
  12480. get: function () {
  12481. return this._fillMode;
  12482. },
  12483. set: function (value) {
  12484. this._fillMode = value;
  12485. },
  12486. enumerable: true,
  12487. configurable: true
  12488. });
  12489. Material.prototype.isReady = function (mesh, useInstances) {
  12490. return true;
  12491. };
  12492. Material.prototype.getEffect = function () {
  12493. return this._effect;
  12494. };
  12495. Material.prototype.getScene = function () {
  12496. return this._scene;
  12497. };
  12498. Material.prototype.needAlphaBlending = function () {
  12499. return (this.alpha < 1.0);
  12500. };
  12501. Material.prototype.needAlphaTesting = function () {
  12502. return false;
  12503. };
  12504. Material.prototype.getAlphaTestTexture = function () {
  12505. return null;
  12506. };
  12507. Material.prototype.trackCreation = function (onCompiled, onError) {
  12508. };
  12509. Material.prototype._preBind = function () {
  12510. var engine = this._scene.getEngine();
  12511. engine.enableEffect(this._effect);
  12512. engine.setState(this.backFaceCulling);
  12513. };
  12514. Material.prototype.bind = function (world, mesh) {
  12515. this._scene._cachedMaterial = this;
  12516. if (this.onBind) {
  12517. this.onBind(this);
  12518. }
  12519. };
  12520. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12521. };
  12522. Material.prototype.unbind = function () {
  12523. };
  12524. Material.prototype.dispose = function (forceDisposeEffect) {
  12525. // Remove from scene
  12526. var index = this._scene.materials.indexOf(this);
  12527. this._scene.materials.splice(index, 1);
  12528. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12529. if (forceDisposeEffect && this._effect) {
  12530. this._scene.getEngine()._releaseEffect(this._effect);
  12531. this._effect = null;
  12532. }
  12533. // Callback
  12534. if (this.onDispose) {
  12535. this.onDispose();
  12536. }
  12537. };
  12538. Material._TriangleFillMode = 0;
  12539. Material._WireFrameFillMode = 1;
  12540. Material._PointFillMode = 2;
  12541. return Material;
  12542. })();
  12543. BABYLON.Material = Material;
  12544. })(BABYLON || (BABYLON = {}));
  12545. //# sourceMappingURL=babylon.material.js.map
  12546. var BABYLON;
  12547. (function (BABYLON) {
  12548. var maxSimultaneousLights = 4;
  12549. var FresnelParameters = (function () {
  12550. function FresnelParameters() {
  12551. this.isEnabled = true;
  12552. this.leftColor = BABYLON.Color3.White();
  12553. this.rightColor = BABYLON.Color3.Black();
  12554. this.bias = 0;
  12555. this.power = 1;
  12556. }
  12557. return FresnelParameters;
  12558. })();
  12559. BABYLON.FresnelParameters = FresnelParameters;
  12560. var StandardMaterial = (function (_super) {
  12561. __extends(StandardMaterial, _super);
  12562. function StandardMaterial(name, scene) {
  12563. var _this = this;
  12564. _super.call(this, name, scene);
  12565. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12566. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12567. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12568. this.specularPower = 64;
  12569. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12570. this.useAlphaFromDiffuseTexture = false;
  12571. this.useSpecularOverAlpha = true;
  12572. this.fogEnabled = true;
  12573. this._cachedDefines = null;
  12574. this._renderTargets = new BABYLON.SmartArray(16);
  12575. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12576. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12577. this._scaledDiffuse = new BABYLON.Color3();
  12578. this._scaledSpecular = new BABYLON.Color3();
  12579. this.getRenderTargetTextures = function () {
  12580. _this._renderTargets.reset();
  12581. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12582. _this._renderTargets.push(_this.reflectionTexture);
  12583. }
  12584. return _this._renderTargets;
  12585. };
  12586. }
  12587. StandardMaterial.prototype.needAlphaBlending = function () {
  12588. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12589. };
  12590. StandardMaterial.prototype.needAlphaTesting = function () {
  12591. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12592. };
  12593. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12594. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12595. };
  12596. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12597. return this.diffuseTexture;
  12598. };
  12599. // Methods
  12600. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12601. if (this.checkReadyOnlyOnce) {
  12602. if (this._wasPreviouslyReady) {
  12603. return true;
  12604. }
  12605. }
  12606. var scene = this.getScene();
  12607. if (!this.checkReadyOnEveryCall) {
  12608. if (this._renderId === scene.getRenderId()) {
  12609. return true;
  12610. }
  12611. }
  12612. var engine = scene.getEngine();
  12613. var defines = [];
  12614. var fallbacks = new BABYLON.EffectFallbacks();
  12615. // Textures
  12616. if (scene.texturesEnabled) {
  12617. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12618. if (!this.diffuseTexture.isReady()) {
  12619. return false;
  12620. } else {
  12621. defines.push("#define DIFFUSE");
  12622. }
  12623. }
  12624. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12625. if (!this.ambientTexture.isReady()) {
  12626. return false;
  12627. } else {
  12628. defines.push("#define AMBIENT");
  12629. }
  12630. }
  12631. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12632. if (!this.opacityTexture.isReady()) {
  12633. return false;
  12634. } else {
  12635. defines.push("#define OPACITY");
  12636. if (this.opacityTexture.getAlphaFromRGB) {
  12637. defines.push("#define OPACITYRGB");
  12638. }
  12639. }
  12640. }
  12641. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12642. if (!this.reflectionTexture.isReady()) {
  12643. return false;
  12644. } else {
  12645. defines.push("#define REFLECTION");
  12646. fallbacks.addFallback(0, "REFLECTION");
  12647. }
  12648. }
  12649. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12650. if (!this.emissiveTexture.isReady()) {
  12651. return false;
  12652. } else {
  12653. defines.push("#define EMISSIVE");
  12654. }
  12655. }
  12656. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12657. if (!this.specularTexture.isReady()) {
  12658. return false;
  12659. } else {
  12660. defines.push("#define SPECULAR");
  12661. fallbacks.addFallback(0, "SPECULAR");
  12662. }
  12663. }
  12664. }
  12665. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12666. if (!this.bumpTexture.isReady()) {
  12667. return false;
  12668. } else {
  12669. defines.push("#define BUMP");
  12670. fallbacks.addFallback(0, "BUMP");
  12671. }
  12672. }
  12673. // Effect
  12674. if (this.useSpecularOverAlpha) {
  12675. defines.push("#define SPECULAROVERALPHA");
  12676. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12677. }
  12678. if (scene.clipPlane) {
  12679. defines.push("#define CLIPPLANE");
  12680. }
  12681. if (engine.getAlphaTesting()) {
  12682. defines.push("#define ALPHATEST");
  12683. }
  12684. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12685. defines.push("#define ALPHAFROMDIFFUSE");
  12686. }
  12687. // Point size
  12688. if (this.pointsCloud || scene.forcePointsCloud) {
  12689. defines.push("#define POINTSIZE");
  12690. }
  12691. // Fog
  12692. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12693. defines.push("#define FOG");
  12694. fallbacks.addFallback(1, "FOG");
  12695. }
  12696. var shadowsActivated = false;
  12697. var lightIndex = 0;
  12698. if (scene.lightsEnabled) {
  12699. for (var index = 0; index < scene.lights.length; index++) {
  12700. var light = scene.lights[index];
  12701. if (!light.isEnabled()) {
  12702. continue;
  12703. }
  12704. // Excluded check
  12705. if (light._excludedMeshesIds.length > 0) {
  12706. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12707. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12708. if (excludedMesh) {
  12709. light.excludedMeshes.push(excludedMesh);
  12710. }
  12711. }
  12712. light._excludedMeshesIds = [];
  12713. }
  12714. // Included check
  12715. if (light._includedOnlyMeshesIds.length > 0) {
  12716. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12717. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12718. if (includedOnlyMesh) {
  12719. light.includedOnlyMeshes.push(includedOnlyMesh);
  12720. }
  12721. }
  12722. light._includedOnlyMeshesIds = [];
  12723. }
  12724. if (!light.canAffectMesh(mesh)) {
  12725. continue;
  12726. }
  12727. defines.push("#define LIGHT" + lightIndex);
  12728. if (lightIndex > 0) {
  12729. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12730. }
  12731. var type;
  12732. if (light instanceof BABYLON.SpotLight) {
  12733. type = "#define SPOTLIGHT" + lightIndex;
  12734. } else if (light instanceof BABYLON.HemisphericLight) {
  12735. type = "#define HEMILIGHT" + lightIndex;
  12736. } else {
  12737. type = "#define POINTDIRLIGHT" + lightIndex;
  12738. }
  12739. defines.push(type);
  12740. if (lightIndex > 0) {
  12741. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12742. }
  12743. // Shadows
  12744. if (scene.shadowsEnabled) {
  12745. var shadowGenerator = light.getShadowGenerator();
  12746. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12747. defines.push("#define SHADOW" + lightIndex);
  12748. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12749. if (!shadowsActivated) {
  12750. defines.push("#define SHADOWS");
  12751. shadowsActivated = true;
  12752. }
  12753. if (shadowGenerator.useVarianceShadowMap) {
  12754. defines.push("#define SHADOWVSM" + lightIndex);
  12755. if (lightIndex > 0) {
  12756. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12757. }
  12758. }
  12759. if (shadowGenerator.usePoissonSampling) {
  12760. defines.push("#define SHADOWPCF" + lightIndex);
  12761. if (lightIndex > 0) {
  12762. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12763. }
  12764. }
  12765. }
  12766. }
  12767. lightIndex++;
  12768. if (lightIndex === maxSimultaneousLights)
  12769. break;
  12770. }
  12771. }
  12772. if (StandardMaterial.FresnelEnabled) {
  12773. // Fresnel
  12774. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12775. var fresnelRank = 1;
  12776. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12777. defines.push("#define DIFFUSEFRESNEL");
  12778. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12779. fresnelRank++;
  12780. }
  12781. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12782. defines.push("#define OPACITYFRESNEL");
  12783. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12784. fresnelRank++;
  12785. }
  12786. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12787. defines.push("#define REFLECTIONFRESNEL");
  12788. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12789. fresnelRank++;
  12790. }
  12791. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12792. defines.push("#define EMISSIVEFRESNEL");
  12793. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12794. fresnelRank++;
  12795. }
  12796. defines.push("#define FRESNEL");
  12797. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12798. }
  12799. }
  12800. // Attribs
  12801. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12802. if (mesh) {
  12803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12804. attribs.push(BABYLON.VertexBuffer.UVKind);
  12805. defines.push("#define UV1");
  12806. }
  12807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12809. defines.push("#define UV2");
  12810. }
  12811. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12812. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12813. defines.push("#define VERTEXCOLOR");
  12814. if (mesh.hasVertexAlpha) {
  12815. defines.push("#define VERTEXALPHA");
  12816. }
  12817. }
  12818. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12819. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12820. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12821. defines.push("#define BONES");
  12822. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12823. defines.push("#define BONES4");
  12824. fallbacks.addFallback(0, "BONES4");
  12825. }
  12826. // Instances
  12827. if (useInstances) {
  12828. defines.push("#define INSTANCES");
  12829. attribs.push("world0");
  12830. attribs.push("world1");
  12831. attribs.push("world2");
  12832. attribs.push("world3");
  12833. }
  12834. }
  12835. // Get correct effect
  12836. var join = defines.join("\n");
  12837. if (this._cachedDefines !== join) {
  12838. this._cachedDefines = join;
  12839. scene.resetCachedMaterial();
  12840. // Legacy browser patch
  12841. var shaderName = "default";
  12842. if (!scene.getEngine().getCaps().standardDerivatives) {
  12843. shaderName = "legacydefault";
  12844. }
  12845. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12846. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12847. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12848. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12849. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12850. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12851. "vFogInfos", "vFogColor", "pointSize",
  12852. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12853. "mBones",
  12854. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12855. "darkness0", "darkness1", "darkness2", "darkness3",
  12856. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12857. ], [
  12858. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12859. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12860. ], join, fallbacks, this.onCompiled, this.onError);
  12861. }
  12862. if (!this._effect.isReady()) {
  12863. return false;
  12864. }
  12865. this._renderId = scene.getRenderId();
  12866. this._wasPreviouslyReady = true;
  12867. return true;
  12868. };
  12869. StandardMaterial.prototype.unbind = function () {
  12870. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12871. this._effect.setTexture("reflection2DSampler", null);
  12872. }
  12873. };
  12874. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12875. this._effect.setMatrix("world", world);
  12876. };
  12877. StandardMaterial.prototype.bind = function (world, mesh) {
  12878. var scene = this.getScene();
  12879. // Matrices
  12880. this.bindOnlyWorldMatrix(world);
  12881. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12882. // Bones
  12883. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12884. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12885. }
  12886. if (scene.getCachedMaterial() !== this) {
  12887. if (StandardMaterial.FresnelEnabled) {
  12888. // Fresnel
  12889. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12890. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12891. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12892. }
  12893. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12894. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12895. }
  12896. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12897. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12898. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12899. }
  12900. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12901. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12902. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12903. }
  12904. }
  12905. // Textures
  12906. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12907. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12908. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12909. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12910. }
  12911. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12912. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12913. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12914. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12915. }
  12916. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12917. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12918. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12919. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12920. }
  12921. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12922. if (this.reflectionTexture.isCube) {
  12923. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12924. } else {
  12925. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12926. }
  12927. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12928. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12929. }
  12930. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12931. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12932. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12933. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12934. }
  12935. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12936. this._effect.setTexture("specularSampler", this.specularTexture);
  12937. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12938. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12939. }
  12940. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12941. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12942. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12943. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12944. }
  12945. // Clip plane
  12946. if (scene.clipPlane) {
  12947. var clipPlane = scene.clipPlane;
  12948. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12949. }
  12950. // Point size
  12951. if (this.pointsCloud) {
  12952. this._effect.setFloat("pointSize", this.pointSize);
  12953. }
  12954. // Colors
  12955. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12956. // Scaling down color according to emissive
  12957. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12958. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12959. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12960. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12961. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12962. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12963. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12964. }
  12965. // Scaling down color according to emissive
  12966. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12967. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12968. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12969. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12970. if (scene.lightsEnabled) {
  12971. var lightIndex = 0;
  12972. for (var index = 0; index < scene.lights.length; index++) {
  12973. var light = scene.lights[index];
  12974. if (!light.isEnabled()) {
  12975. continue;
  12976. }
  12977. if (!light.canAffectMesh(mesh)) {
  12978. continue;
  12979. }
  12980. if (light instanceof BABYLON.PointLight) {
  12981. // Point Light
  12982. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12983. } else if (light instanceof BABYLON.DirectionalLight) {
  12984. // Directional Light
  12985. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12986. } else if (light instanceof BABYLON.SpotLight) {
  12987. // Spot Light
  12988. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12989. } else if (light instanceof BABYLON.HemisphericLight) {
  12990. // Hemispheric Light
  12991. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12992. }
  12993. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12994. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12995. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12996. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12997. // Shadows
  12998. if (scene.shadowsEnabled) {
  12999. var shadowGenerator = light.getShadowGenerator();
  13000. if (mesh.receiveShadows && shadowGenerator) {
  13001. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13002. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13003. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13004. }
  13005. }
  13006. lightIndex++;
  13007. if (lightIndex === maxSimultaneousLights)
  13008. break;
  13009. }
  13010. }
  13011. // View
  13012. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13013. this._effect.setMatrix("view", scene.getViewMatrix());
  13014. }
  13015. // Fog
  13016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13017. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13018. this._effect.setColor3("vFogColor", scene.fogColor);
  13019. }
  13020. _super.prototype.bind.call(this, world, mesh);
  13021. };
  13022. StandardMaterial.prototype.getAnimatables = function () {
  13023. var results = [];
  13024. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13025. results.push(this.diffuseTexture);
  13026. }
  13027. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13028. results.push(this.ambientTexture);
  13029. }
  13030. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13031. results.push(this.opacityTexture);
  13032. }
  13033. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13034. results.push(this.reflectionTexture);
  13035. }
  13036. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13037. results.push(this.emissiveTexture);
  13038. }
  13039. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13040. results.push(this.specularTexture);
  13041. }
  13042. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13043. results.push(this.bumpTexture);
  13044. }
  13045. return results;
  13046. };
  13047. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13048. if (this.diffuseTexture) {
  13049. this.diffuseTexture.dispose();
  13050. }
  13051. if (this.ambientTexture) {
  13052. this.ambientTexture.dispose();
  13053. }
  13054. if (this.opacityTexture) {
  13055. this.opacityTexture.dispose();
  13056. }
  13057. if (this.reflectionTexture) {
  13058. this.reflectionTexture.dispose();
  13059. }
  13060. if (this.emissiveTexture) {
  13061. this.emissiveTexture.dispose();
  13062. }
  13063. if (this.specularTexture) {
  13064. this.specularTexture.dispose();
  13065. }
  13066. if (this.bumpTexture) {
  13067. this.bumpTexture.dispose();
  13068. }
  13069. _super.prototype.dispose.call(this, forceDisposeEffect);
  13070. };
  13071. StandardMaterial.prototype.clone = function (name) {
  13072. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13073. // Base material
  13074. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13075. newStandardMaterial.alpha = this.alpha;
  13076. newStandardMaterial.fillMode = this.fillMode;
  13077. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13078. // Standard material
  13079. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13080. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13081. }
  13082. if (this.ambientTexture && this.ambientTexture.clone) {
  13083. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13084. }
  13085. if (this.opacityTexture && this.opacityTexture.clone) {
  13086. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13087. }
  13088. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13089. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13090. }
  13091. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13092. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13093. }
  13094. if (this.specularTexture && this.specularTexture.clone) {
  13095. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13096. }
  13097. if (this.bumpTexture && this.bumpTexture.clone) {
  13098. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13099. }
  13100. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13101. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13102. newStandardMaterial.specularColor = this.specularColor.clone();
  13103. newStandardMaterial.specularPower = this.specularPower;
  13104. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13105. return newStandardMaterial;
  13106. };
  13107. StandardMaterial.DiffuseTextureEnabled = true;
  13108. StandardMaterial.AmbientTextureEnabled = true;
  13109. StandardMaterial.OpacityTextureEnabled = true;
  13110. StandardMaterial.ReflectionTextureEnabled = true;
  13111. StandardMaterial.EmissiveTextureEnabled = true;
  13112. StandardMaterial.SpecularTextureEnabled = true;
  13113. StandardMaterial.BumpTextureEnabled = true;
  13114. StandardMaterial.FresnelEnabled = true;
  13115. return StandardMaterial;
  13116. })(BABYLON.Material);
  13117. BABYLON.StandardMaterial = StandardMaterial;
  13118. })(BABYLON || (BABYLON = {}));
  13119. //# sourceMappingURL=babylon.standardMaterial.js.map
  13120. var BABYLON;
  13121. (function (BABYLON) {
  13122. var MultiMaterial = (function (_super) {
  13123. __extends(MultiMaterial, _super);
  13124. function MultiMaterial(name, scene) {
  13125. _super.call(this, name, scene, true);
  13126. this.subMaterials = new Array();
  13127. scene.multiMaterials.push(this);
  13128. }
  13129. // Properties
  13130. MultiMaterial.prototype.getSubMaterial = function (index) {
  13131. if (index < 0 || index >= this.subMaterials.length) {
  13132. return this.getScene().defaultMaterial;
  13133. }
  13134. return this.subMaterials[index];
  13135. };
  13136. // Methods
  13137. MultiMaterial.prototype.isReady = function (mesh) {
  13138. for (var index = 0; index < this.subMaterials.length; index++) {
  13139. var subMaterial = this.subMaterials[index];
  13140. if (subMaterial) {
  13141. if (!this.subMaterials[index].isReady(mesh)) {
  13142. return false;
  13143. }
  13144. }
  13145. }
  13146. return true;
  13147. };
  13148. return MultiMaterial;
  13149. })(BABYLON.Material);
  13150. BABYLON.MultiMaterial = MultiMaterial;
  13151. })(BABYLON || (BABYLON = {}));
  13152. //# sourceMappingURL=babylon.multiMaterial.js.map
  13153. var BABYLON;
  13154. (function (BABYLON) {
  13155. var Database = (function () {
  13156. function Database(urlToScene, callbackManifestChecked) {
  13157. // Handling various flavors of prefixed version of IndexedDB
  13158. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13159. this.callbackManifestChecked = callbackManifestChecked;
  13160. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13161. this.db = null;
  13162. this.enableSceneOffline = false;
  13163. this.enableTexturesOffline = false;
  13164. this.manifestVersionFound = 0;
  13165. this.mustUpdateRessources = false;
  13166. this.hasReachedQuota = false;
  13167. this.checkManifestFile();
  13168. }
  13169. Database.prototype.checkManifestFile = function () {
  13170. var _this = this;
  13171. function noManifestFile() {
  13172. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13173. that.enableSceneOffline = false;
  13174. that.enableTexturesOffline = false;
  13175. that.callbackManifestChecked(false);
  13176. }
  13177. var that = this;
  13178. var manifestURL = this.currentSceneUrl + ".manifest";
  13179. var xhr = new XMLHttpRequest();
  13180. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13181. xhr.open("GET", manifestURLTimeStamped, true);
  13182. xhr.addEventListener("load", function () {
  13183. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13184. try {
  13185. var manifestFile = JSON.parse(xhr.response);
  13186. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13187. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13188. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13189. _this.manifestVersionFound = manifestFile.version;
  13190. }
  13191. if (_this.callbackManifestChecked) {
  13192. _this.callbackManifestChecked(true);
  13193. }
  13194. } catch (ex) {
  13195. noManifestFile();
  13196. }
  13197. } else {
  13198. noManifestFile();
  13199. }
  13200. }, false);
  13201. xhr.addEventListener("error", function (event) {
  13202. noManifestFile();
  13203. }, false);
  13204. try {
  13205. xhr.send();
  13206. } catch (ex) {
  13207. BABYLON.Tools.Error("Error on XHR send request.");
  13208. that.callbackManifestChecked(false);
  13209. }
  13210. };
  13211. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13212. var _this = this;
  13213. function handleError() {
  13214. that.isSupported = false;
  13215. if (errorCallback)
  13216. errorCallback();
  13217. }
  13218. var that = this;
  13219. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13220. // Your browser doesn't support IndexedDB
  13221. this.isSupported = false;
  13222. if (errorCallback)
  13223. errorCallback();
  13224. } else {
  13225. // If the DB hasn't been opened or created yet
  13226. if (!this.db) {
  13227. this.hasReachedQuota = false;
  13228. this.isSupported = true;
  13229. var request = this.idbFactory.open("babylonjs", 1);
  13230. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13231. request.onerror = function (event) {
  13232. handleError();
  13233. };
  13234. // executes when a version change transaction cannot complete due to other active transactions
  13235. request.onblocked = function (event) {
  13236. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13237. handleError();
  13238. };
  13239. // DB has been opened successfully
  13240. request.onsuccess = function (event) {
  13241. _this.db = request.result;
  13242. successCallback();
  13243. };
  13244. // Initialization of the DB. Creating Scenes & Textures stores
  13245. request.onupgradeneeded = function (event) {
  13246. _this.db = (event.target).result;
  13247. try {
  13248. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13249. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13250. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13251. } catch (ex) {
  13252. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13253. handleError();
  13254. }
  13255. };
  13256. } else {
  13257. if (successCallback)
  13258. successCallback();
  13259. }
  13260. }
  13261. };
  13262. Database.prototype.loadImageFromDB = function (url, image) {
  13263. var _this = this;
  13264. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13265. var saveAndLoadImage = function () {
  13266. if (!_this.hasReachedQuota && _this.db !== null) {
  13267. // the texture is not yet in the DB, let's try to save it
  13268. _this._saveImageIntoDBAsync(completeURL, image);
  13269. } else {
  13270. image.src = url;
  13271. }
  13272. };
  13273. if (!this.mustUpdateRessources) {
  13274. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13275. } else {
  13276. saveAndLoadImage();
  13277. }
  13278. };
  13279. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13280. if (this.isSupported && this.db !== null) {
  13281. var texture;
  13282. var transaction = this.db.transaction(["textures"]);
  13283. transaction.onabort = function (event) {
  13284. image.src = url;
  13285. };
  13286. transaction.oncomplete = function (event) {
  13287. var blobTextureURL;
  13288. if (texture) {
  13289. var URL = window.URL || window.webkitURL;
  13290. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13291. image.onerror = function () {
  13292. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13293. image.src = url;
  13294. };
  13295. image.src = blobTextureURL;
  13296. } else {
  13297. notInDBCallback();
  13298. }
  13299. };
  13300. var getRequest = transaction.objectStore("textures").get(url);
  13301. getRequest.onsuccess = function (event) {
  13302. texture = (event.target).result;
  13303. };
  13304. getRequest.onerror = function (event) {
  13305. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13306. image.src = url;
  13307. };
  13308. } else {
  13309. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13310. image.src = url;
  13311. }
  13312. };
  13313. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13314. var _this = this;
  13315. if (this.isSupported) {
  13316. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13317. var generateBlobUrl = function () {
  13318. var blobTextureURL;
  13319. if (blob) {
  13320. var URL = window.URL || window.webkitURL;
  13321. try {
  13322. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13323. } catch (ex) {
  13324. blobTextureURL = URL.createObjectURL(blob);
  13325. }
  13326. }
  13327. image.src = blobTextureURL;
  13328. };
  13329. if (BABYLON.Database.isUASupportingBlobStorage) {
  13330. var xhr = new XMLHttpRequest(), blob;
  13331. xhr.open("GET", url, true);
  13332. xhr.responseType = "blob";
  13333. xhr.addEventListener("load", function () {
  13334. if (xhr.status === 200) {
  13335. // Blob as response (XHR2)
  13336. blob = xhr.response;
  13337. var transaction = _this.db.transaction(["textures"], "readwrite");
  13338. // the transaction could abort because of a QuotaExceededError error
  13339. transaction.onabort = function (event) {
  13340. try {
  13341. if (event.srcElement.error.name === "QuotaExceededError") {
  13342. this.hasReachedQuota = true;
  13343. }
  13344. } catch (ex) {
  13345. }
  13346. generateBlobUrl();
  13347. };
  13348. transaction.oncomplete = function (event) {
  13349. generateBlobUrl();
  13350. };
  13351. var newTexture = { textureUrl: url, data: blob };
  13352. try {
  13353. // Put the blob into the dabase
  13354. var addRequest = transaction.objectStore("textures").put(newTexture);
  13355. addRequest.onsuccess = function (event) {
  13356. };
  13357. addRequest.onerror = function (event) {
  13358. generateBlobUrl();
  13359. };
  13360. } catch (ex) {
  13361. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13362. if (ex.code === 25) {
  13363. BABYLON.Database.isUASupportingBlobStorage = false;
  13364. }
  13365. image.src = url;
  13366. }
  13367. } else {
  13368. image.src = url;
  13369. }
  13370. }, false);
  13371. xhr.addEventListener("error", function (event) {
  13372. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13373. image.src = url;
  13374. }, false);
  13375. xhr.send();
  13376. } else {
  13377. image.src = url;
  13378. }
  13379. } else {
  13380. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13381. image.src = url;
  13382. }
  13383. };
  13384. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13385. var _this = this;
  13386. var updateVersion = function (event) {
  13387. // the version is not yet in the DB or we need to update it
  13388. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13389. };
  13390. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13391. };
  13392. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13393. var _this = this;
  13394. if (this.isSupported) {
  13395. var version;
  13396. try {
  13397. var transaction = this.db.transaction(["versions"]);
  13398. transaction.oncomplete = function (event) {
  13399. if (version) {
  13400. // If the version in the JSON file is > than the version in DB
  13401. if (_this.manifestVersionFound > version.data) {
  13402. _this.mustUpdateRessources = true;
  13403. updateInDBCallback();
  13404. } else {
  13405. callback(version.data);
  13406. }
  13407. } else {
  13408. _this.mustUpdateRessources = true;
  13409. updateInDBCallback();
  13410. }
  13411. };
  13412. transaction.onabort = function (event) {
  13413. callback(-1);
  13414. };
  13415. var getRequest = transaction.objectStore("versions").get(url);
  13416. getRequest.onsuccess = function (event) {
  13417. version = (event.target).result;
  13418. };
  13419. getRequest.onerror = function (event) {
  13420. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13421. callback(-1);
  13422. };
  13423. } catch (ex) {
  13424. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13425. callback(-1);
  13426. }
  13427. } else {
  13428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13429. callback(-1);
  13430. }
  13431. };
  13432. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13433. var _this = this;
  13434. if (this.isSupported && !this.hasReachedQuota) {
  13435. try {
  13436. // Open a transaction to the database
  13437. var transaction = this.db.transaction(["versions"], "readwrite");
  13438. // the transaction could abort because of a QuotaExceededError error
  13439. transaction.onabort = function (event) {
  13440. try {
  13441. if (event.srcElement.error.name === "QuotaExceededError") {
  13442. _this.hasReachedQuota = true;
  13443. }
  13444. } catch (ex) {
  13445. }
  13446. callback(-1);
  13447. };
  13448. transaction.oncomplete = function (event) {
  13449. callback(_this.manifestVersionFound);
  13450. };
  13451. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13452. // Put the scene into the database
  13453. var addRequest = transaction.objectStore("versions").put(newVersion);
  13454. addRequest.onsuccess = function (event) {
  13455. };
  13456. addRequest.onerror = function (event) {
  13457. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13458. };
  13459. } catch (ex) {
  13460. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13461. callback(-1);
  13462. }
  13463. } else {
  13464. callback(-1);
  13465. }
  13466. };
  13467. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13468. var _this = this;
  13469. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13470. var saveAndLoadFile = function (event) {
  13471. // the scene is not yet in the DB, let's try to save it
  13472. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13473. };
  13474. this._checkVersionFromDB(completeUrl, function (version) {
  13475. if (version !== -1) {
  13476. if (!_this.mustUpdateRessources) {
  13477. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13478. } else {
  13479. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13480. }
  13481. } else {
  13482. errorCallback();
  13483. }
  13484. });
  13485. };
  13486. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13487. if (this.isSupported) {
  13488. var targetStore;
  13489. if (url.indexOf(".babylon") !== -1) {
  13490. targetStore = "scenes";
  13491. } else {
  13492. targetStore = "textures";
  13493. }
  13494. var file;
  13495. var transaction = this.db.transaction([targetStore]);
  13496. transaction.oncomplete = function (event) {
  13497. if (file) {
  13498. callback(file.data);
  13499. } else {
  13500. notInDBCallback();
  13501. }
  13502. };
  13503. transaction.onabort = function (event) {
  13504. notInDBCallback();
  13505. };
  13506. var getRequest = transaction.objectStore(targetStore).get(url);
  13507. getRequest.onsuccess = function (event) {
  13508. file = (event.target).result;
  13509. };
  13510. getRequest.onerror = function (event) {
  13511. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13512. notInDBCallback();
  13513. };
  13514. } else {
  13515. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13516. callback();
  13517. }
  13518. };
  13519. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13520. var _this = this;
  13521. if (this.isSupported) {
  13522. var targetStore;
  13523. if (url.indexOf(".babylon") !== -1) {
  13524. targetStore = "scenes";
  13525. } else {
  13526. targetStore = "textures";
  13527. }
  13528. // Create XHR
  13529. var xhr = new XMLHttpRequest(), fileData;
  13530. xhr.open("GET", url, true);
  13531. if (useArrayBuffer) {
  13532. xhr.responseType = "arraybuffer";
  13533. }
  13534. xhr.onprogress = progressCallback;
  13535. xhr.addEventListener("load", function () {
  13536. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13537. // Blob as response (XHR2)
  13538. //fileData = xhr.responseText;
  13539. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13540. if (!_this.hasReachedQuota) {
  13541. // Open a transaction to the database
  13542. var transaction = _this.db.transaction([targetStore], "readwrite");
  13543. // the transaction could abort because of a QuotaExceededError error
  13544. transaction.onabort = function (event) {
  13545. try {
  13546. if (event.srcElement.error.name === "QuotaExceededError") {
  13547. this.hasReachedQuota = true;
  13548. }
  13549. } catch (ex) {
  13550. }
  13551. callback(fileData);
  13552. };
  13553. transaction.oncomplete = function (event) {
  13554. callback(fileData);
  13555. };
  13556. var newFile;
  13557. if (targetStore === "scenes") {
  13558. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13559. } else {
  13560. newFile = { textureUrl: url, data: fileData };
  13561. }
  13562. try {
  13563. // Put the scene into the database
  13564. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13565. addRequest.onsuccess = function (event) {
  13566. };
  13567. addRequest.onerror = function (event) {
  13568. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13569. };
  13570. } catch (ex) {
  13571. callback(fileData);
  13572. }
  13573. } else {
  13574. callback(fileData);
  13575. }
  13576. } else {
  13577. callback();
  13578. }
  13579. }, false);
  13580. xhr.addEventListener("error", function (event) {
  13581. BABYLON.Tools.Error("error on XHR request.");
  13582. callback();
  13583. }, false);
  13584. xhr.send();
  13585. } else {
  13586. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13587. callback();
  13588. }
  13589. };
  13590. Database.isUASupportingBlobStorage = true;
  13591. Database.parseURL = function (url) {
  13592. var a = document.createElement('a');
  13593. a.href = url;
  13594. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13595. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13596. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13597. return absLocation;
  13598. };
  13599. Database.ReturnFullUrlLocation = function (url) {
  13600. if (url.indexOf("http:/") === -1) {
  13601. return (BABYLON.Database.parseURL(window.location.href) + url);
  13602. } else {
  13603. return url;
  13604. }
  13605. };
  13606. return Database;
  13607. })();
  13608. BABYLON.Database = Database;
  13609. })(BABYLON || (BABYLON = {}));
  13610. //# sourceMappingURL=babylon.database.js.map
  13611. var BABYLON;
  13612. (function (BABYLON) {
  13613. var SpriteManager = (function () {
  13614. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13615. this.name = name;
  13616. this.cellSize = cellSize;
  13617. this.sprites = new Array();
  13618. this.renderingGroupId = 0;
  13619. this.fogEnabled = true;
  13620. this._vertexDeclaration = [3, 4, 4, 4];
  13621. this._vertexStrideSize = 15 * 4;
  13622. this._capacity = capacity;
  13623. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13624. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13625. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13626. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13627. this._scene = scene;
  13628. this._scene.spriteManagers.push(this);
  13629. // VBO
  13630. this._vertexDeclaration = [3, 4, 4, 4];
  13631. this._vertexStrideSize = 15 * 4;
  13632. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13633. var indices = [];
  13634. var index = 0;
  13635. for (var count = 0; count < capacity; count++) {
  13636. indices.push(index);
  13637. indices.push(index + 1);
  13638. indices.push(index + 2);
  13639. indices.push(index);
  13640. indices.push(index + 2);
  13641. indices.push(index + 3);
  13642. index += 4;
  13643. }
  13644. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13645. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13646. // Effects
  13647. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13648. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13649. }
  13650. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13651. var arrayOffset = index * 15;
  13652. if (offsetX == 0)
  13653. offsetX = this._epsilon;
  13654. else if (offsetX == 1)
  13655. offsetX = 1 - this._epsilon;
  13656. if (offsetY == 0)
  13657. offsetY = this._epsilon;
  13658. else if (offsetY == 1)
  13659. offsetY = 1 - this._epsilon;
  13660. this._vertices[arrayOffset] = sprite.position.x;
  13661. this._vertices[arrayOffset + 1] = sprite.position.y;
  13662. this._vertices[arrayOffset + 2] = sprite.position.z;
  13663. this._vertices[arrayOffset + 3] = sprite.angle;
  13664. this._vertices[arrayOffset + 4] = sprite.size;
  13665. this._vertices[arrayOffset + 5] = offsetX;
  13666. this._vertices[arrayOffset + 6] = offsetY;
  13667. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13668. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13669. var offset = (sprite.cellIndex / rowSize) >> 0;
  13670. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13671. this._vertices[arrayOffset + 10] = offset;
  13672. // Color
  13673. this._vertices[arrayOffset + 11] = sprite.color.r;
  13674. this._vertices[arrayOffset + 12] = sprite.color.g;
  13675. this._vertices[arrayOffset + 13] = sprite.color.b;
  13676. this._vertices[arrayOffset + 14] = sprite.color.a;
  13677. };
  13678. SpriteManager.prototype.render = function () {
  13679. // Check
  13680. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13681. return;
  13682. var engine = this._scene.getEngine();
  13683. var baseSize = this._spriteTexture.getBaseSize();
  13684. // Sprites
  13685. var deltaTime = engine.getDeltaTime();
  13686. var max = Math.min(this._capacity, this.sprites.length);
  13687. var rowSize = baseSize.width / this.cellSize;
  13688. var offset = 0;
  13689. for (var index = 0; index < max; index++) {
  13690. var sprite = this.sprites[index];
  13691. if (!sprite) {
  13692. continue;
  13693. }
  13694. sprite._animate(deltaTime);
  13695. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13696. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13697. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13698. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13699. }
  13700. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13701. // Render
  13702. var effect = this._effectBase;
  13703. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13704. effect = this._effectFog;
  13705. }
  13706. engine.enableEffect(effect);
  13707. var viewMatrix = this._scene.getViewMatrix();
  13708. effect.setTexture("diffuseSampler", this._spriteTexture);
  13709. effect.setMatrix("view", viewMatrix);
  13710. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13711. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13712. // Fog
  13713. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13714. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13715. effect.setColor3("vFogColor", this._scene.fogColor);
  13716. }
  13717. // VBOs
  13718. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13719. // Draw order
  13720. effect.setBool("alphaTest", true);
  13721. engine.setColorWrite(false);
  13722. engine.draw(true, 0, max * 6);
  13723. engine.setColorWrite(true);
  13724. effect.setBool("alphaTest", false);
  13725. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13726. engine.draw(true, 0, max * 6);
  13727. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13728. };
  13729. SpriteManager.prototype.dispose = function () {
  13730. if (this._vertexBuffer) {
  13731. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13732. this._vertexBuffer = null;
  13733. }
  13734. if (this._indexBuffer) {
  13735. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13736. this._indexBuffer = null;
  13737. }
  13738. if (this._spriteTexture) {
  13739. this._spriteTexture.dispose();
  13740. this._spriteTexture = null;
  13741. }
  13742. // Remove from scene
  13743. var index = this._scene.spriteManagers.indexOf(this);
  13744. this._scene.spriteManagers.splice(index, 1);
  13745. // Callback
  13746. if (this.onDispose) {
  13747. this.onDispose();
  13748. }
  13749. };
  13750. return SpriteManager;
  13751. })();
  13752. BABYLON.SpriteManager = SpriteManager;
  13753. })(BABYLON || (BABYLON = {}));
  13754. //# sourceMappingURL=babylon.spriteManager.js.map
  13755. var BABYLON;
  13756. (function (BABYLON) {
  13757. var Sprite = (function () {
  13758. function Sprite(name, manager) {
  13759. this.name = name;
  13760. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13761. this.size = 1.0;
  13762. this.angle = 0;
  13763. this.cellIndex = 0;
  13764. this.invertU = 0;
  13765. this.invertV = 0;
  13766. this.animations = new Array();
  13767. this._animationStarted = false;
  13768. this._loopAnimation = false;
  13769. this._fromIndex = 0;
  13770. this._toIndex = 0;
  13771. this._delay = 0;
  13772. this._direction = 1;
  13773. this._frameCount = 0;
  13774. this._time = 0;
  13775. this._manager = manager;
  13776. this._manager.sprites.push(this);
  13777. this.position = BABYLON.Vector3.Zero();
  13778. }
  13779. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13780. this._fromIndex = from;
  13781. this._toIndex = to;
  13782. this._loopAnimation = loop;
  13783. this._delay = delay;
  13784. this._animationStarted = true;
  13785. this._direction = from < to ? 1 : -1;
  13786. this.cellIndex = from;
  13787. this._time = 0;
  13788. };
  13789. Sprite.prototype.stopAnimation = function () {
  13790. this._animationStarted = false;
  13791. };
  13792. Sprite.prototype._animate = function (deltaTime) {
  13793. if (!this._animationStarted)
  13794. return;
  13795. this._time += deltaTime;
  13796. if (this._time > this._delay) {
  13797. this._time = this._time % this._delay;
  13798. this.cellIndex += this._direction;
  13799. if (this.cellIndex == this._toIndex) {
  13800. if (this._loopAnimation) {
  13801. this.cellIndex = this._fromIndex;
  13802. } else {
  13803. this._animationStarted = false;
  13804. if (this.disposeWhenFinishedAnimating) {
  13805. this.dispose();
  13806. }
  13807. }
  13808. }
  13809. }
  13810. };
  13811. Sprite.prototype.dispose = function () {
  13812. for (var i = 0; i < this._manager.sprites.length; i++) {
  13813. if (this._manager.sprites[i] == this) {
  13814. this._manager.sprites.splice(i, 1);
  13815. }
  13816. }
  13817. };
  13818. return Sprite;
  13819. })();
  13820. BABYLON.Sprite = Sprite;
  13821. })(BABYLON || (BABYLON = {}));
  13822. //# sourceMappingURL=babylon.sprite.js.map
  13823. var BABYLON;
  13824. (function (BABYLON) {
  13825. var Layer = (function () {
  13826. function Layer(name, imgUrl, scene, isBackground, color) {
  13827. this.name = name;
  13828. this._vertexDeclaration = [2];
  13829. this._vertexStrideSize = 2 * 4;
  13830. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13831. this.isBackground = isBackground === undefined ? true : isBackground;
  13832. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13833. this._scene = scene;
  13834. this._scene.layers.push(this);
  13835. // VBO
  13836. var vertices = [];
  13837. vertices.push(1, 1);
  13838. vertices.push(-1, 1);
  13839. vertices.push(-1, -1);
  13840. vertices.push(1, -1);
  13841. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13842. // Indices
  13843. var indices = [];
  13844. indices.push(0);
  13845. indices.push(1);
  13846. indices.push(2);
  13847. indices.push(0);
  13848. indices.push(2);
  13849. indices.push(3);
  13850. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13851. // Effects
  13852. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13853. }
  13854. Layer.prototype.render = function () {
  13855. // Check
  13856. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13857. return;
  13858. var engine = this._scene.getEngine();
  13859. // Render
  13860. engine.enableEffect(this._effect);
  13861. engine.setState(false);
  13862. // Texture
  13863. this._effect.setTexture("textureSampler", this.texture);
  13864. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13865. // Color
  13866. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13867. // VBOs
  13868. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13869. // Draw order
  13870. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13871. engine.draw(true, 0, 6);
  13872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13873. };
  13874. Layer.prototype.dispose = function () {
  13875. if (this._vertexBuffer) {
  13876. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13877. this._vertexBuffer = null;
  13878. }
  13879. if (this._indexBuffer) {
  13880. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13881. this._indexBuffer = null;
  13882. }
  13883. if (this.texture) {
  13884. this.texture.dispose();
  13885. this.texture = null;
  13886. }
  13887. // Remove from scene
  13888. var index = this._scene.layers.indexOf(this);
  13889. this._scene.layers.splice(index, 1);
  13890. // Callback
  13891. if (this.onDispose) {
  13892. this.onDispose();
  13893. }
  13894. };
  13895. return Layer;
  13896. })();
  13897. BABYLON.Layer = Layer;
  13898. })(BABYLON || (BABYLON = {}));
  13899. //# sourceMappingURL=babylon.layer.js.map
  13900. var BABYLON;
  13901. (function (BABYLON) {
  13902. var Particle = (function () {
  13903. function Particle() {
  13904. this.position = BABYLON.Vector3.Zero();
  13905. this.direction = BABYLON.Vector3.Zero();
  13906. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13907. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13908. this.lifeTime = 1.0;
  13909. this.age = 0;
  13910. this.size = 0;
  13911. this.angle = 0;
  13912. this.angularSpeed = 0;
  13913. }
  13914. return Particle;
  13915. })();
  13916. BABYLON.Particle = Particle;
  13917. })(BABYLON || (BABYLON = {}));
  13918. //# sourceMappingURL=babylon.particle.js.map
  13919. var BABYLON;
  13920. (function (BABYLON) {
  13921. var randomNumber = function (min, max) {
  13922. if (min === max) {
  13923. return (min);
  13924. }
  13925. var random = Math.random();
  13926. return ((random * (max - min)) + min);
  13927. };
  13928. var ParticleSystem = (function () {
  13929. function ParticleSystem(name, capacity, scene, customEffect) {
  13930. var _this = this;
  13931. this.name = name;
  13932. this.renderingGroupId = 0;
  13933. this.emitter = null;
  13934. this.emitRate = 10;
  13935. this.manualEmitCount = -1;
  13936. this.updateSpeed = 0.01;
  13937. this.targetStopDuration = 0;
  13938. this.disposeOnStop = false;
  13939. this.minEmitPower = 1;
  13940. this.maxEmitPower = 1;
  13941. this.minLifeTime = 1;
  13942. this.maxLifeTime = 1;
  13943. this.minSize = 1;
  13944. this.maxSize = 1;
  13945. this.minAngularSpeed = 0;
  13946. this.maxAngularSpeed = 0;
  13947. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13948. this.forceDepthWrite = false;
  13949. this.gravity = BABYLON.Vector3.Zero();
  13950. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13951. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13952. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13953. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13954. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13955. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13956. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13957. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13958. this.particles = new Array();
  13959. this._vertexDeclaration = [3, 4, 4];
  13960. this._vertexStrideSize = 11 * 4;
  13961. this._stockParticles = new Array();
  13962. this._newPartsExcess = 0;
  13963. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13964. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13965. this._scaledDirection = BABYLON.Vector3.Zero();
  13966. this._scaledGravity = BABYLON.Vector3.Zero();
  13967. this._currentRenderId = -1;
  13968. this._started = false;
  13969. this._stopped = false;
  13970. this._actualFrame = 0;
  13971. this.id = name;
  13972. this._capacity = capacity;
  13973. this._scene = scene;
  13974. this._customEffect = customEffect;
  13975. scene.particleSystems.push(this);
  13976. // VBO
  13977. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13978. var indices = [];
  13979. var index = 0;
  13980. for (var count = 0; count < capacity; count++) {
  13981. indices.push(index);
  13982. indices.push(index + 1);
  13983. indices.push(index + 2);
  13984. indices.push(index);
  13985. indices.push(index + 2);
  13986. indices.push(index + 3);
  13987. index += 4;
  13988. }
  13989. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13990. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13991. // Default behaviors
  13992. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13993. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13994. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13995. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13996. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13997. };
  13998. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13999. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14000. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14001. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14003. };
  14004. this.updateFunction = function (particles) {
  14005. for (var index = 0; index < particles.length; index++) {
  14006. var particle = particles[index];
  14007. particle.age += _this._scaledUpdateSpeed;
  14008. if (particle.age >= particle.lifeTime) {
  14009. particles.splice(index, 1);
  14010. _this._stockParticles.push(particle);
  14011. index--;
  14012. continue;
  14013. } else {
  14014. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14015. particle.color.addInPlace(_this._scaledColorStep);
  14016. if (particle.color.a < 0)
  14017. particle.color.a = 0;
  14018. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14019. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14020. particle.position.addInPlace(_this._scaledDirection);
  14021. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14022. particle.direction.addInPlace(_this._scaledGravity);
  14023. }
  14024. }
  14025. };
  14026. }
  14027. ParticleSystem.prototype.getCapacity = function () {
  14028. return this._capacity;
  14029. };
  14030. ParticleSystem.prototype.isAlive = function () {
  14031. return this._alive;
  14032. };
  14033. ParticleSystem.prototype.isStarted = function () {
  14034. return this._started;
  14035. };
  14036. ParticleSystem.prototype.start = function () {
  14037. this._started = true;
  14038. this._stopped = false;
  14039. this._actualFrame = 0;
  14040. };
  14041. ParticleSystem.prototype.stop = function () {
  14042. this._stopped = true;
  14043. };
  14044. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14045. var offset = index * 11;
  14046. this._vertices[offset] = particle.position.x;
  14047. this._vertices[offset + 1] = particle.position.y;
  14048. this._vertices[offset + 2] = particle.position.z;
  14049. this._vertices[offset + 3] = particle.color.r;
  14050. this._vertices[offset + 4] = particle.color.g;
  14051. this._vertices[offset + 5] = particle.color.b;
  14052. this._vertices[offset + 6] = particle.color.a;
  14053. this._vertices[offset + 7] = particle.angle;
  14054. this._vertices[offset + 8] = particle.size;
  14055. this._vertices[offset + 9] = offsetX;
  14056. this._vertices[offset + 10] = offsetY;
  14057. };
  14058. ParticleSystem.prototype._update = function (newParticles) {
  14059. // Update current
  14060. this._alive = this.particles.length > 0;
  14061. this.updateFunction(this.particles);
  14062. // Add new ones
  14063. var worldMatrix;
  14064. if (this.emitter.position) {
  14065. worldMatrix = this.emitter.getWorldMatrix();
  14066. } else {
  14067. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14068. }
  14069. for (var index = 0; index < newParticles; index++) {
  14070. if (this.particles.length === this._capacity) {
  14071. break;
  14072. }
  14073. if (this._stockParticles.length !== 0) {
  14074. var particle = this._stockParticles.pop();
  14075. particle.age = 0;
  14076. } else {
  14077. particle = new BABYLON.Particle();
  14078. }
  14079. this.particles.push(particle);
  14080. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14081. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14082. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14083. particle.size = randomNumber(this.minSize, this.maxSize);
  14084. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14085. this.startPositionFunction(worldMatrix, particle.position);
  14086. var step = randomNumber(0, 1.0);
  14087. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14088. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14089. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14090. }
  14091. };
  14092. ParticleSystem.prototype._getEffect = function () {
  14093. if (this._customEffect) {
  14094. return this._customEffect;
  14095. }
  14096. ;
  14097. var defines = [];
  14098. if (this._scene.clipPlane) {
  14099. defines.push("#define CLIPPLANE");
  14100. }
  14101. // Effect
  14102. var join = defines.join("\n");
  14103. if (this._cachedDefines !== join) {
  14104. this._cachedDefines = join;
  14105. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14106. }
  14107. return this._effect;
  14108. };
  14109. ParticleSystem.prototype.animate = function () {
  14110. if (!this._started)
  14111. return;
  14112. var effect = this._getEffect();
  14113. // Check
  14114. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14115. return;
  14116. if (this._currentRenderId === this._scene.getRenderId()) {
  14117. return;
  14118. }
  14119. this._currentRenderId = this._scene.getRenderId();
  14120. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14121. // determine the number of particles we need to create
  14122. var emitCout;
  14123. if (this.manualEmitCount > -1) {
  14124. emitCout = this.manualEmitCount;
  14125. this.manualEmitCount = 0;
  14126. } else {
  14127. emitCout = this.emitRate;
  14128. }
  14129. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14130. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14131. if (this._newPartsExcess > 1.0) {
  14132. newParticles += this._newPartsExcess >> 0;
  14133. this._newPartsExcess -= this._newPartsExcess >> 0;
  14134. }
  14135. this._alive = false;
  14136. if (!this._stopped) {
  14137. this._actualFrame += this._scaledUpdateSpeed;
  14138. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14139. this.stop();
  14140. } else {
  14141. newParticles = 0;
  14142. }
  14143. this._update(newParticles);
  14144. // Stopped?
  14145. if (this._stopped) {
  14146. if (!this._alive) {
  14147. this._started = false;
  14148. if (this.disposeOnStop) {
  14149. this._scene._toBeDisposed.push(this);
  14150. }
  14151. }
  14152. }
  14153. // Update VBO
  14154. var offset = 0;
  14155. for (var index = 0; index < this.particles.length; index++) {
  14156. var particle = this.particles[index];
  14157. this._appendParticleVertex(offset++, particle, 0, 0);
  14158. this._appendParticleVertex(offset++, particle, 1, 0);
  14159. this._appendParticleVertex(offset++, particle, 1, 1);
  14160. this._appendParticleVertex(offset++, particle, 0, 1);
  14161. }
  14162. var engine = this._scene.getEngine();
  14163. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14164. };
  14165. ParticleSystem.prototype.render = function () {
  14166. var effect = this._getEffect();
  14167. // Check
  14168. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14169. return 0;
  14170. var engine = this._scene.getEngine();
  14171. // Render
  14172. engine.enableEffect(effect);
  14173. engine.setState(false);
  14174. var viewMatrix = this._scene.getViewMatrix();
  14175. effect.setTexture("diffuseSampler", this.particleTexture);
  14176. effect.setMatrix("view", viewMatrix);
  14177. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14178. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14179. if (this._scene.clipPlane) {
  14180. var clipPlane = this._scene.clipPlane;
  14181. var invView = viewMatrix.clone();
  14182. invView.invert();
  14183. effect.setMatrix("invView", invView);
  14184. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14185. }
  14186. // VBOs
  14187. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14188. // Draw order
  14189. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14190. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14191. } else {
  14192. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14193. }
  14194. if (this.forceDepthWrite) {
  14195. engine.setDepthWrite(true);
  14196. }
  14197. engine.draw(true, 0, this.particles.length * 6);
  14198. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14199. return this.particles.length;
  14200. };
  14201. ParticleSystem.prototype.dispose = function () {
  14202. if (this._vertexBuffer) {
  14203. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14204. this._vertexBuffer = null;
  14205. }
  14206. if (this._indexBuffer) {
  14207. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14208. this._indexBuffer = null;
  14209. }
  14210. if (this.particleTexture) {
  14211. this.particleTexture.dispose();
  14212. this.particleTexture = null;
  14213. }
  14214. // Remove from scene
  14215. var index = this._scene.particleSystems.indexOf(this);
  14216. this._scene.particleSystems.splice(index, 1);
  14217. // Callback
  14218. if (this.onDispose) {
  14219. this.onDispose();
  14220. }
  14221. };
  14222. // Clone
  14223. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14224. var result = new ParticleSystem(name, this._capacity, this._scene);
  14225. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14226. if (newEmitter === undefined) {
  14227. newEmitter = this.emitter;
  14228. }
  14229. result.emitter = newEmitter;
  14230. if (this.particleTexture) {
  14231. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14232. }
  14233. result.start();
  14234. return result;
  14235. };
  14236. ParticleSystem.BLENDMODE_ONEONE = 0;
  14237. ParticleSystem.BLENDMODE_STANDARD = 1;
  14238. return ParticleSystem;
  14239. })();
  14240. BABYLON.ParticleSystem = ParticleSystem;
  14241. })(BABYLON || (BABYLON = {}));
  14242. //# sourceMappingURL=babylon.particleSystem.js.map
  14243. var BABYLON;
  14244. (function (BABYLON) {
  14245. var Animation = (function () {
  14246. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14247. this.name = name;
  14248. this.targetProperty = targetProperty;
  14249. this.framePerSecond = framePerSecond;
  14250. this.dataType = dataType;
  14251. this.loopMode = loopMode;
  14252. this._offsetsCache = {};
  14253. this._highLimitsCache = {};
  14254. this._stopped = false;
  14255. this.targetPropertyPath = targetProperty.split(".");
  14256. this.dataType = dataType;
  14257. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14258. }
  14259. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14260. var dataType = undefined;
  14261. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14262. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14263. } else if (from instanceof BABYLON.Quaternion) {
  14264. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14265. } else if (from instanceof BABYLON.Vector3) {
  14266. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14267. } else if (from instanceof BABYLON.Vector2) {
  14268. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14269. } else if (from instanceof BABYLON.Color3) {
  14270. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14271. }
  14272. if (dataType == undefined) {
  14273. return;
  14274. }
  14275. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14276. var keys = [];
  14277. keys.push({ frame: 0, value: from });
  14278. keys.push({ frame: totalFrame, value: to });
  14279. animation.setKeys(keys);
  14280. mesh.animations.push(animation);
  14281. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14282. };
  14283. // Methods
  14284. Animation.prototype.isStopped = function () {
  14285. return this._stopped;
  14286. };
  14287. Animation.prototype.getKeys = function () {
  14288. return this._keys;
  14289. };
  14290. Animation.prototype.getEasingFunction = function () {
  14291. return this._easingFunction;
  14292. };
  14293. Animation.prototype.setEasingFunction = function (easingFunction) {
  14294. this._easingFunction = easingFunction;
  14295. };
  14296. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14297. return startValue + (endValue - startValue) * gradient;
  14298. };
  14299. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14300. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14301. };
  14302. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14303. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14304. };
  14305. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14306. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14307. };
  14308. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14309. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14310. };
  14311. Animation.prototype.clone = function () {
  14312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14313. clone.setKeys(this._keys);
  14314. return clone;
  14315. };
  14316. Animation.prototype.setKeys = function (values) {
  14317. this._keys = values.slice(0);
  14318. this._offsetsCache = {};
  14319. this._highLimitsCache = {};
  14320. };
  14321. Animation.prototype._getKeyValue = function (value) {
  14322. if (typeof value === "function") {
  14323. return value();
  14324. }
  14325. return value;
  14326. };
  14327. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14328. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14329. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14330. }
  14331. this.currentFrame = currentFrame;
  14332. for (var key = 0; key < this._keys.length; key++) {
  14333. // for each frame, we need the key just before the frame superior
  14334. if (this._keys[key + 1].frame >= currentFrame) {
  14335. var startValue = this._getKeyValue(this._keys[key].value);
  14336. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14337. // gradient : percent of currentFrame between the frame inf and the frame sup
  14338. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14339. // check for easingFunction and correction of gradient
  14340. if (this._easingFunction != null) {
  14341. gradient = this._easingFunction.ease(gradient);
  14342. }
  14343. switch (this.dataType) {
  14344. case Animation.ANIMATIONTYPE_FLOAT:
  14345. switch (loopMode) {
  14346. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14347. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14348. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14349. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14350. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14351. }
  14352. break;
  14353. case Animation.ANIMATIONTYPE_QUATERNION:
  14354. var quaternion = null;
  14355. switch (loopMode) {
  14356. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14357. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14358. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14359. break;
  14360. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14361. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14362. break;
  14363. }
  14364. return quaternion;
  14365. case Animation.ANIMATIONTYPE_VECTOR3:
  14366. switch (loopMode) {
  14367. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14368. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14369. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14370. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14371. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14372. }
  14373. case Animation.ANIMATIONTYPE_VECTOR2:
  14374. switch (loopMode) {
  14375. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14376. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14377. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14378. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14379. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14380. }
  14381. case Animation.ANIMATIONTYPE_COLOR3:
  14382. switch (loopMode) {
  14383. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14384. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14385. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14386. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14387. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14388. }
  14389. case Animation.ANIMATIONTYPE_MATRIX:
  14390. switch (loopMode) {
  14391. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14392. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14393. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14394. return startValue;
  14395. }
  14396. default:
  14397. break;
  14398. }
  14399. break;
  14400. }
  14401. }
  14402. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14403. };
  14404. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14405. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14406. this._stopped = true;
  14407. return false;
  14408. }
  14409. var returnValue = true;
  14410. // Adding a start key at frame 0 if missing
  14411. if (this._keys[0].frame !== 0) {
  14412. var newKey = { frame: 0, value: this._keys[0].value };
  14413. this._keys.splice(0, 0, newKey);
  14414. }
  14415. // Check limits
  14416. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14417. from = this._keys[0].frame;
  14418. }
  14419. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14420. to = this._keys[this._keys.length - 1].frame;
  14421. }
  14422. // Compute ratio
  14423. var range = to - from;
  14424. var offsetValue;
  14425. // ratio represents the frame delta between from and to
  14426. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14427. var highLimitValue = 0;
  14428. if (ratio > range && !loop) {
  14429. returnValue = false;
  14430. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14431. } else {
  14432. // Get max value if required
  14433. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14434. var keyOffset = to.toString() + from.toString();
  14435. if (!this._offsetsCache[keyOffset]) {
  14436. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14437. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14438. switch (this.dataType) {
  14439. case Animation.ANIMATIONTYPE_FLOAT:
  14440. this._offsetsCache[keyOffset] = toValue - fromValue;
  14441. break;
  14442. case Animation.ANIMATIONTYPE_QUATERNION:
  14443. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14444. break;
  14445. case Animation.ANIMATIONTYPE_VECTOR3:
  14446. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14447. case Animation.ANIMATIONTYPE_VECTOR2:
  14448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14449. case Animation.ANIMATIONTYPE_COLOR3:
  14450. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14451. default:
  14452. break;
  14453. }
  14454. this._highLimitsCache[keyOffset] = toValue;
  14455. }
  14456. highLimitValue = this._highLimitsCache[keyOffset];
  14457. offsetValue = this._offsetsCache[keyOffset];
  14458. }
  14459. }
  14460. if (offsetValue === undefined) {
  14461. switch (this.dataType) {
  14462. case Animation.ANIMATIONTYPE_FLOAT:
  14463. offsetValue = 0;
  14464. break;
  14465. case Animation.ANIMATIONTYPE_QUATERNION:
  14466. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14467. break;
  14468. case Animation.ANIMATIONTYPE_VECTOR3:
  14469. offsetValue = BABYLON.Vector3.Zero();
  14470. break;
  14471. case Animation.ANIMATIONTYPE_VECTOR2:
  14472. offsetValue = BABYLON.Vector2.Zero();
  14473. break;
  14474. case Animation.ANIMATIONTYPE_COLOR3:
  14475. offsetValue = BABYLON.Color3.Black();
  14476. }
  14477. }
  14478. // Compute value
  14479. var repeatCount = (ratio / range) >> 0;
  14480. var currentFrame = returnValue ? from + ratio % range : to;
  14481. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14482. // Set value
  14483. if (this.targetPropertyPath.length > 1) {
  14484. var property = this._target[this.targetPropertyPath[0]];
  14485. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14486. property = property[this.targetPropertyPath[index]];
  14487. }
  14488. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14489. } else {
  14490. this._target[this.targetPropertyPath[0]] = currentValue;
  14491. }
  14492. if (this._target.markAsDirty) {
  14493. this._target.markAsDirty(this.targetProperty);
  14494. }
  14495. if (!returnValue) {
  14496. this._stopped = true;
  14497. }
  14498. return returnValue;
  14499. };
  14500. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14501. get: function () {
  14502. return Animation._ANIMATIONTYPE_FLOAT;
  14503. },
  14504. enumerable: true,
  14505. configurable: true
  14506. });
  14507. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14508. get: function () {
  14509. return Animation._ANIMATIONTYPE_VECTOR3;
  14510. },
  14511. enumerable: true,
  14512. configurable: true
  14513. });
  14514. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14515. get: function () {
  14516. return Animation._ANIMATIONTYPE_VECTOR2;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14522. get: function () {
  14523. return Animation._ANIMATIONTYPE_QUATERNION;
  14524. },
  14525. enumerable: true,
  14526. configurable: true
  14527. });
  14528. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14529. get: function () {
  14530. return Animation._ANIMATIONTYPE_MATRIX;
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14536. get: function () {
  14537. return Animation._ANIMATIONTYPE_COLOR3;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14543. get: function () {
  14544. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14550. get: function () {
  14551. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14552. },
  14553. enumerable: true,
  14554. configurable: true
  14555. });
  14556. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14557. get: function () {
  14558. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14559. },
  14560. enumerable: true,
  14561. configurable: true
  14562. });
  14563. Animation._ANIMATIONTYPE_FLOAT = 0;
  14564. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14565. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14566. Animation._ANIMATIONTYPE_MATRIX = 3;
  14567. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14568. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14569. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14570. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14571. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14572. return Animation;
  14573. })();
  14574. BABYLON.Animation = Animation;
  14575. })(BABYLON || (BABYLON = {}));
  14576. //# sourceMappingURL=babylon.animation.js.map
  14577. var BABYLON;
  14578. (function (BABYLON) {
  14579. var Animatable = (function () {
  14580. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14581. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14582. if (typeof toFrame === "undefined") { toFrame = 100; }
  14583. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14584. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14585. this.target = target;
  14586. this.fromFrame = fromFrame;
  14587. this.toFrame = toFrame;
  14588. this.loopAnimation = loopAnimation;
  14589. this.speedRatio = speedRatio;
  14590. this.onAnimationEnd = onAnimationEnd;
  14591. this._animations = new Array();
  14592. this._paused = false;
  14593. this.animationStarted = false;
  14594. if (animations) {
  14595. this.appendAnimations(target, animations);
  14596. }
  14597. this._scene = scene;
  14598. scene._activeAnimatables.push(this);
  14599. }
  14600. // Methods
  14601. Animatable.prototype.appendAnimations = function (target, animations) {
  14602. for (var index = 0; index < animations.length; index++) {
  14603. var animation = animations[index];
  14604. animation._target = target;
  14605. this._animations.push(animation);
  14606. }
  14607. };
  14608. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14609. var animations = this._animations;
  14610. for (var index = 0; index < animations.length; index++) {
  14611. if (animations[index].targetProperty === property) {
  14612. return animations[index];
  14613. }
  14614. }
  14615. return null;
  14616. };
  14617. Animatable.prototype.pause = function () {
  14618. if (this._paused) {
  14619. return;
  14620. }
  14621. this._paused = true;
  14622. };
  14623. Animatable.prototype.restart = function () {
  14624. this._paused = false;
  14625. };
  14626. Animatable.prototype.stop = function () {
  14627. var index = this._scene._activeAnimatables.indexOf(this);
  14628. if (index > -1) {
  14629. this._scene._activeAnimatables.splice(index, 1);
  14630. }
  14631. if (this.onAnimationEnd) {
  14632. this.onAnimationEnd();
  14633. }
  14634. };
  14635. Animatable.prototype._animate = function (delay) {
  14636. if (this._paused) {
  14637. if (!this._pausedDelay) {
  14638. this._pausedDelay = delay;
  14639. }
  14640. return true;
  14641. }
  14642. if (!this._localDelayOffset) {
  14643. this._localDelayOffset = delay;
  14644. } else if (this._pausedDelay) {
  14645. this._localDelayOffset += delay - this._pausedDelay;
  14646. this._pausedDelay = null;
  14647. }
  14648. // Animating
  14649. var running = false;
  14650. var animations = this._animations;
  14651. for (var index = 0; index < animations.length; index++) {
  14652. var animation = animations[index];
  14653. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14654. running = running || isRunning;
  14655. }
  14656. if (!running && this.onAnimationEnd) {
  14657. this.onAnimationEnd();
  14658. }
  14659. return running;
  14660. };
  14661. return Animatable;
  14662. })();
  14663. BABYLON.Animatable = Animatable;
  14664. })(BABYLON || (BABYLON = {}));
  14665. //# sourceMappingURL=babylon.animatable.js.map
  14666. var BABYLON;
  14667. (function (BABYLON) {
  14668. var EasingFunction = (function () {
  14669. function EasingFunction() {
  14670. // Properties
  14671. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14672. }
  14673. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14674. get: function () {
  14675. return EasingFunction._EASINGMODE_EASEIN;
  14676. },
  14677. enumerable: true,
  14678. configurable: true
  14679. });
  14680. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14681. get: function () {
  14682. return EasingFunction._EASINGMODE_EASEOUT;
  14683. },
  14684. enumerable: true,
  14685. configurable: true
  14686. });
  14687. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14688. get: function () {
  14689. return EasingFunction._EASINGMODE_EASEINOUT;
  14690. },
  14691. enumerable: true,
  14692. configurable: true
  14693. });
  14694. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14695. var n = Math.min(Math.max(easingMode, 0), 2);
  14696. this._easingMode = n;
  14697. };
  14698. EasingFunction.prototype.getEasingMode = function () {
  14699. return this._easingMode;
  14700. };
  14701. EasingFunction.prototype.easeInCore = function (gradient) {
  14702. throw new Error('You must implement this method');
  14703. };
  14704. EasingFunction.prototype.ease = function (gradient) {
  14705. switch (this._easingMode) {
  14706. case EasingFunction.EASINGMODE_EASEIN:
  14707. return this.easeInCore(gradient);
  14708. case EasingFunction.EASINGMODE_EASEOUT:
  14709. return (1 - this.easeInCore(1 - gradient));
  14710. }
  14711. if (gradient >= 0.5) {
  14712. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14713. }
  14714. return (this.easeInCore(gradient * 2) * 0.5);
  14715. };
  14716. EasingFunction._EASINGMODE_EASEIN = 0;
  14717. EasingFunction._EASINGMODE_EASEOUT = 1;
  14718. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14719. return EasingFunction;
  14720. })();
  14721. BABYLON.EasingFunction = EasingFunction;
  14722. var CircleEase = (function (_super) {
  14723. __extends(CircleEase, _super);
  14724. function CircleEase() {
  14725. _super.apply(this, arguments);
  14726. }
  14727. CircleEase.prototype.easeInCore = function (gradient) {
  14728. gradient = Math.max(0, Math.min(1, gradient));
  14729. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14730. };
  14731. return CircleEase;
  14732. })(EasingFunction);
  14733. BABYLON.CircleEase = CircleEase;
  14734. var BackEase = (function (_super) {
  14735. __extends(BackEase, _super);
  14736. function BackEase(amplitude) {
  14737. if (typeof amplitude === "undefined") { amplitude = 1; }
  14738. _super.call(this);
  14739. this.amplitude = amplitude;
  14740. }
  14741. BackEase.prototype.easeInCore = function (gradient) {
  14742. var num = Math.max(0, this.amplitude);
  14743. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14744. };
  14745. return BackEase;
  14746. })(EasingFunction);
  14747. BABYLON.BackEase = BackEase;
  14748. var BounceEase = (function (_super) {
  14749. __extends(BounceEase, _super);
  14750. function BounceEase(bounces, bounciness) {
  14751. if (typeof bounces === "undefined") { bounces = 3; }
  14752. if (typeof bounciness === "undefined") { bounciness = 2; }
  14753. _super.call(this);
  14754. this.bounces = bounces;
  14755. this.bounciness = bounciness;
  14756. }
  14757. BounceEase.prototype.easeInCore = function (gradient) {
  14758. var y = Math.max(0.0, this.bounces);
  14759. var bounciness = this.bounciness;
  14760. if (bounciness <= 1.0) {
  14761. bounciness = 1.001;
  14762. }
  14763. var num9 = Math.pow(bounciness, y);
  14764. var num5 = 1.0 - bounciness;
  14765. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14766. var num15 = gradient * num4;
  14767. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14768. var num3 = Math.floor(num65);
  14769. var num13 = num3 + 1.0;
  14770. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14771. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14772. var num7 = (num8 + num12) * 0.5;
  14773. var num6 = gradient - num7;
  14774. var num2 = num7 - num8;
  14775. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14776. };
  14777. return BounceEase;
  14778. })(EasingFunction);
  14779. BABYLON.BounceEase = BounceEase;
  14780. var CubicEase = (function (_super) {
  14781. __extends(CubicEase, _super);
  14782. function CubicEase() {
  14783. _super.apply(this, arguments);
  14784. }
  14785. CubicEase.prototype.easeInCore = function (gradient) {
  14786. return (gradient * gradient * gradient);
  14787. };
  14788. return CubicEase;
  14789. })(EasingFunction);
  14790. BABYLON.CubicEase = CubicEase;
  14791. var ElasticEase = (function (_super) {
  14792. __extends(ElasticEase, _super);
  14793. function ElasticEase(oscillations, springiness) {
  14794. if (typeof oscillations === "undefined") { oscillations = 3; }
  14795. if (typeof springiness === "undefined") { springiness = 3; }
  14796. _super.call(this);
  14797. this.oscillations = oscillations;
  14798. this.springiness = springiness;
  14799. }
  14800. ElasticEase.prototype.easeInCore = function (gradient) {
  14801. var num2;
  14802. var num3 = Math.max(0.0, this.oscillations);
  14803. var num = Math.max(0.0, this.springiness);
  14804. if (num == 0) {
  14805. num2 = gradient;
  14806. } else {
  14807. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14808. }
  14809. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14810. };
  14811. return ElasticEase;
  14812. })(EasingFunction);
  14813. BABYLON.ElasticEase = ElasticEase;
  14814. var ExponentialEase = (function (_super) {
  14815. __extends(ExponentialEase, _super);
  14816. function ExponentialEase(exponent) {
  14817. if (typeof exponent === "undefined") { exponent = 2; }
  14818. _super.call(this);
  14819. this.exponent = exponent;
  14820. }
  14821. ExponentialEase.prototype.easeInCore = function (gradient) {
  14822. if (this.exponent <= 0) {
  14823. return gradient;
  14824. }
  14825. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14826. };
  14827. return ExponentialEase;
  14828. })(EasingFunction);
  14829. BABYLON.ExponentialEase = ExponentialEase;
  14830. var PowerEase = (function (_super) {
  14831. __extends(PowerEase, _super);
  14832. function PowerEase(power) {
  14833. if (typeof power === "undefined") { power = 2; }
  14834. _super.call(this);
  14835. this.power = power;
  14836. }
  14837. PowerEase.prototype.easeInCore = function (gradient) {
  14838. var y = Math.max(0.0, this.power);
  14839. return Math.pow(gradient, y);
  14840. };
  14841. return PowerEase;
  14842. })(EasingFunction);
  14843. BABYLON.PowerEase = PowerEase;
  14844. var QuadraticEase = (function (_super) {
  14845. __extends(QuadraticEase, _super);
  14846. function QuadraticEase() {
  14847. _super.apply(this, arguments);
  14848. }
  14849. QuadraticEase.prototype.easeInCore = function (gradient) {
  14850. return (gradient * gradient);
  14851. };
  14852. return QuadraticEase;
  14853. })(EasingFunction);
  14854. BABYLON.QuadraticEase = QuadraticEase;
  14855. var QuarticEase = (function (_super) {
  14856. __extends(QuarticEase, _super);
  14857. function QuarticEase() {
  14858. _super.apply(this, arguments);
  14859. }
  14860. QuarticEase.prototype.easeInCore = function (gradient) {
  14861. return (gradient * gradient * gradient * gradient);
  14862. };
  14863. return QuarticEase;
  14864. })(EasingFunction);
  14865. BABYLON.QuarticEase = QuarticEase;
  14866. var QuinticEase = (function (_super) {
  14867. __extends(QuinticEase, _super);
  14868. function QuinticEase() {
  14869. _super.apply(this, arguments);
  14870. }
  14871. QuinticEase.prototype.easeInCore = function (gradient) {
  14872. return (gradient * gradient * gradient * gradient * gradient);
  14873. };
  14874. return QuinticEase;
  14875. })(EasingFunction);
  14876. BABYLON.QuinticEase = QuinticEase;
  14877. var SineEase = (function (_super) {
  14878. __extends(SineEase, _super);
  14879. function SineEase() {
  14880. _super.apply(this, arguments);
  14881. }
  14882. SineEase.prototype.easeInCore = function (gradient) {
  14883. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14884. };
  14885. return SineEase;
  14886. })(EasingFunction);
  14887. BABYLON.SineEase = SineEase;
  14888. var BezierCurveEase = (function (_super) {
  14889. __extends(BezierCurveEase, _super);
  14890. function BezierCurveEase(x1, y1, x2, y2) {
  14891. if (typeof x1 === "undefined") { x1 = 0; }
  14892. if (typeof y1 === "undefined") { y1 = 0; }
  14893. if (typeof x2 === "undefined") { x2 = 1; }
  14894. if (typeof y2 === "undefined") { y2 = 1; }
  14895. _super.call(this);
  14896. this.x1 = x1;
  14897. this.y1 = y1;
  14898. this.x2 = x2;
  14899. this.y2 = y2;
  14900. }
  14901. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14902. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14903. };
  14904. return BezierCurveEase;
  14905. })(EasingFunction);
  14906. BABYLON.BezierCurveEase = BezierCurveEase;
  14907. })(BABYLON || (BABYLON = {}));
  14908. //# sourceMappingURL=babylon.easing.js.map
  14909. var BABYLON;
  14910. (function (BABYLON) {
  14911. var Octree = (function () {
  14912. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14913. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14914. this.maxDepth = maxDepth;
  14915. this.dynamicContent = new Array();
  14916. this._maxBlockCapacity = maxBlockCapacity || 64;
  14917. this._selectionContent = new BABYLON.SmartArray(1024);
  14918. this._creationFunc = creationFunc;
  14919. }
  14920. // Methods
  14921. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14922. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14923. };
  14924. Octree.prototype.addMesh = function (entry) {
  14925. for (var index = 0; index < this.blocks.length; index++) {
  14926. var block = this.blocks[index];
  14927. block.addEntry(entry);
  14928. }
  14929. };
  14930. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14931. this._selectionContent.reset();
  14932. for (var index = 0; index < this.blocks.length; index++) {
  14933. var block = this.blocks[index];
  14934. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14935. }
  14936. if (allowDuplicate) {
  14937. this._selectionContent.concat(this.dynamicContent);
  14938. } else {
  14939. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14940. }
  14941. return this._selectionContent;
  14942. };
  14943. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14944. this._selectionContent.reset();
  14945. for (var index = 0; index < this.blocks.length; index++) {
  14946. var block = this.blocks[index];
  14947. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14948. }
  14949. if (allowDuplicate) {
  14950. this._selectionContent.concat(this.dynamicContent);
  14951. } else {
  14952. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14953. }
  14954. return this._selectionContent;
  14955. };
  14956. Octree.prototype.intersectsRay = function (ray) {
  14957. this._selectionContent.reset();
  14958. for (var index = 0; index < this.blocks.length; index++) {
  14959. var block = this.blocks[index];
  14960. block.intersectsRay(ray, this._selectionContent);
  14961. }
  14962. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14963. return this._selectionContent;
  14964. };
  14965. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14966. target.blocks = new Array();
  14967. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14968. for (var x = 0; x < 2; x++) {
  14969. for (var y = 0; y < 2; y++) {
  14970. for (var z = 0; z < 2; z++) {
  14971. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14972. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14973. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14974. block.addEntries(entries);
  14975. target.blocks.push(block);
  14976. }
  14977. }
  14978. }
  14979. };
  14980. Octree.CreationFuncForMeshes = function (entry, block) {
  14981. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14982. block.entries.push(entry);
  14983. }
  14984. };
  14985. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14986. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14987. block.entries.push(entry);
  14988. }
  14989. };
  14990. return Octree;
  14991. })();
  14992. BABYLON.Octree = Octree;
  14993. })(BABYLON || (BABYLON = {}));
  14994. //# sourceMappingURL=babylon.octree.js.map
  14995. var BABYLON;
  14996. (function (BABYLON) {
  14997. var OctreeBlock = (function () {
  14998. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14999. this.entries = new Array();
  15000. this._boundingVectors = new Array();
  15001. this._capacity = capacity;
  15002. this._depth = depth;
  15003. this._maxDepth = maxDepth;
  15004. this._creationFunc = creationFunc;
  15005. this._minPoint = minPoint;
  15006. this._maxPoint = maxPoint;
  15007. this._boundingVectors.push(minPoint.clone());
  15008. this._boundingVectors.push(maxPoint.clone());
  15009. this._boundingVectors.push(minPoint.clone());
  15010. this._boundingVectors[2].x = maxPoint.x;
  15011. this._boundingVectors.push(minPoint.clone());
  15012. this._boundingVectors[3].y = maxPoint.y;
  15013. this._boundingVectors.push(minPoint.clone());
  15014. this._boundingVectors[4].z = maxPoint.z;
  15015. this._boundingVectors.push(maxPoint.clone());
  15016. this._boundingVectors[5].z = minPoint.z;
  15017. this._boundingVectors.push(maxPoint.clone());
  15018. this._boundingVectors[6].x = minPoint.x;
  15019. this._boundingVectors.push(maxPoint.clone());
  15020. this._boundingVectors[7].y = minPoint.y;
  15021. }
  15022. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15023. // Property
  15024. get: function () {
  15025. return this._capacity;
  15026. },
  15027. enumerable: true,
  15028. configurable: true
  15029. });
  15030. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15031. get: function () {
  15032. return this._minPoint;
  15033. },
  15034. enumerable: true,
  15035. configurable: true
  15036. });
  15037. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15038. get: function () {
  15039. return this._maxPoint;
  15040. },
  15041. enumerable: true,
  15042. configurable: true
  15043. });
  15044. // Methods
  15045. OctreeBlock.prototype.addEntry = function (entry) {
  15046. if (this.blocks) {
  15047. for (var index = 0; index < this.blocks.length; index++) {
  15048. var block = this.blocks[index];
  15049. block.addEntry(entry);
  15050. }
  15051. return;
  15052. }
  15053. this._creationFunc(entry, this);
  15054. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15055. this.createInnerBlocks();
  15056. }
  15057. };
  15058. OctreeBlock.prototype.addEntries = function (entries) {
  15059. for (var index = 0; index < entries.length; index++) {
  15060. var mesh = entries[index];
  15061. this.addEntry(mesh);
  15062. }
  15063. };
  15064. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15065. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15066. if (this.blocks) {
  15067. for (var index = 0; index < this.blocks.length; index++) {
  15068. var block = this.blocks[index];
  15069. block.select(frustumPlanes, selection, allowDuplicate);
  15070. }
  15071. return;
  15072. }
  15073. if (allowDuplicate) {
  15074. selection.concat(this.entries);
  15075. } else {
  15076. selection.concatWithNoDuplicate(this.entries);
  15077. }
  15078. }
  15079. };
  15080. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15081. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15082. if (this.blocks) {
  15083. for (var index = 0; index < this.blocks.length; index++) {
  15084. var block = this.blocks[index];
  15085. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15086. }
  15087. return;
  15088. }
  15089. if (allowDuplicate) {
  15090. selection.concat(this.entries);
  15091. } else {
  15092. selection.concatWithNoDuplicate(this.entries);
  15093. }
  15094. }
  15095. };
  15096. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15097. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15098. if (this.blocks) {
  15099. for (var index = 0; index < this.blocks.length; index++) {
  15100. var block = this.blocks[index];
  15101. block.intersectsRay(ray, selection);
  15102. }
  15103. return;
  15104. }
  15105. selection.concatWithNoDuplicate(this.entries);
  15106. }
  15107. };
  15108. OctreeBlock.prototype.createInnerBlocks = function () {
  15109. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15110. };
  15111. return OctreeBlock;
  15112. })();
  15113. BABYLON.OctreeBlock = OctreeBlock;
  15114. })(BABYLON || (BABYLON = {}));
  15115. //# sourceMappingURL=babylon.octreeBlock.js.map
  15116. var BABYLON;
  15117. (function (BABYLON) {
  15118. var Bone = (function () {
  15119. function Bone(name, skeleton, parentBone, matrix) {
  15120. this.name = name;
  15121. this.children = new Array();
  15122. this.animations = new Array();
  15123. this._worldTransform = new BABYLON.Matrix();
  15124. this._absoluteTransform = new BABYLON.Matrix();
  15125. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15126. this._skeleton = skeleton;
  15127. this._matrix = matrix;
  15128. this._baseMatrix = matrix;
  15129. skeleton.bones.push(this);
  15130. if (parentBone) {
  15131. this._parent = parentBone;
  15132. parentBone.children.push(this);
  15133. } else {
  15134. this._parent = null;
  15135. }
  15136. this._updateDifferenceMatrix();
  15137. }
  15138. // Members
  15139. Bone.prototype.getParent = function () {
  15140. return this._parent;
  15141. };
  15142. Bone.prototype.getLocalMatrix = function () {
  15143. return this._matrix;
  15144. };
  15145. Bone.prototype.getBaseMatrix = function () {
  15146. return this._baseMatrix;
  15147. };
  15148. Bone.prototype.getWorldMatrix = function () {
  15149. return this._worldTransform;
  15150. };
  15151. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15152. return this._invertedAbsoluteTransform;
  15153. };
  15154. Bone.prototype.getAbsoluteMatrix = function () {
  15155. var matrix = this._matrix.clone();
  15156. var parent = this._parent;
  15157. while (parent) {
  15158. matrix = matrix.multiply(parent.getLocalMatrix());
  15159. parent = parent.getParent();
  15160. }
  15161. return matrix;
  15162. };
  15163. // Methods
  15164. Bone.prototype.updateMatrix = function (matrix) {
  15165. this._matrix = matrix;
  15166. this._skeleton._markAsDirty();
  15167. this._updateDifferenceMatrix();
  15168. };
  15169. Bone.prototype._updateDifferenceMatrix = function () {
  15170. if (this._parent) {
  15171. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15172. } else {
  15173. this._absoluteTransform.copyFrom(this._matrix);
  15174. }
  15175. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15176. for (var index = 0; index < this.children.length; index++) {
  15177. this.children[index]._updateDifferenceMatrix();
  15178. }
  15179. };
  15180. Bone.prototype.markAsDirty = function () {
  15181. this._skeleton._markAsDirty();
  15182. };
  15183. return Bone;
  15184. })();
  15185. BABYLON.Bone = Bone;
  15186. })(BABYLON || (BABYLON = {}));
  15187. //# sourceMappingURL=babylon.bone.js.map
  15188. var BABYLON;
  15189. (function (BABYLON) {
  15190. var Skeleton = (function () {
  15191. function Skeleton(name, id, scene) {
  15192. this.name = name;
  15193. this.id = id;
  15194. this.bones = new Array();
  15195. this._isDirty = true;
  15196. this._identity = BABYLON.Matrix.Identity();
  15197. this.bones = [];
  15198. this._scene = scene;
  15199. scene.skeletons.push(this);
  15200. }
  15201. // Members
  15202. Skeleton.prototype.getTransformMatrices = function () {
  15203. return this._transformMatrices;
  15204. };
  15205. // Methods
  15206. Skeleton.prototype._markAsDirty = function () {
  15207. this._isDirty = true;
  15208. };
  15209. Skeleton.prototype.prepare = function () {
  15210. if (!this._isDirty) {
  15211. return;
  15212. }
  15213. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15214. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15215. }
  15216. for (var index = 0; index < this.bones.length; index++) {
  15217. var bone = this.bones[index];
  15218. var parentBone = bone.getParent();
  15219. if (parentBone) {
  15220. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15221. } else {
  15222. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15223. }
  15224. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15225. }
  15226. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15227. this._isDirty = false;
  15228. };
  15229. Skeleton.prototype.getAnimatables = function () {
  15230. if (!this._animatables || this._animatables.length != this.bones.length) {
  15231. this._animatables = [];
  15232. for (var index = 0; index < this.bones.length; index++) {
  15233. this._animatables.push(this.bones[index]);
  15234. }
  15235. }
  15236. return this._animatables;
  15237. };
  15238. Skeleton.prototype.clone = function (name, id) {
  15239. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15240. for (var index = 0; index < this.bones.length; index++) {
  15241. var source = this.bones[index];
  15242. var parentBone = null;
  15243. if (source.getParent()) {
  15244. var parentIndex = this.bones.indexOf(source.getParent());
  15245. parentBone = result.bones[parentIndex];
  15246. }
  15247. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15248. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15249. }
  15250. return result;
  15251. };
  15252. return Skeleton;
  15253. })();
  15254. BABYLON.Skeleton = Skeleton;
  15255. })(BABYLON || (BABYLON = {}));
  15256. //# sourceMappingURL=babylon.skeleton.js.map
  15257. var BABYLON;
  15258. (function (BABYLON) {
  15259. var PostProcess = (function () {
  15260. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15261. this.name = name;
  15262. this.width = -1;
  15263. this.height = -1;
  15264. this._reusable = false;
  15265. this._textures = new BABYLON.SmartArray(2);
  15266. this._currentRenderTextureInd = 0;
  15267. if (camera != null) {
  15268. this._camera = camera;
  15269. this._scene = camera.getScene();
  15270. camera.attachPostProcess(this);
  15271. this._engine = this._scene.getEngine();
  15272. } else {
  15273. this._engine = engine;
  15274. }
  15275. this._renderRatio = ratio;
  15276. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15277. this._reusable = reusable || false;
  15278. samplers = samplers || [];
  15279. samplers.push("textureSampler");
  15280. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15281. }
  15282. PostProcess.prototype.isReusable = function () {
  15283. return this._reusable;
  15284. };
  15285. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15286. camera = camera || this._camera;
  15287. var scene = camera.getScene();
  15288. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15289. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15290. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15291. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15292. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15293. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15294. if (this._textures.length > 0) {
  15295. for (var i = 0; i < this._textures.length; i++) {
  15296. this._engine._releaseTexture(this._textures.data[i]);
  15297. }
  15298. this._textures.reset();
  15299. }
  15300. this.width = desiredWidth;
  15301. this.height = desiredHeight;
  15302. 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 }));
  15303. if (this._reusable) {
  15304. 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 }));
  15305. }
  15306. if (this.onSizeChanged) {
  15307. this.onSizeChanged();
  15308. }
  15309. }
  15310. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15311. if (this.onActivate) {
  15312. this.onActivate(camera);
  15313. }
  15314. // Clear
  15315. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15316. if (this._reusable) {
  15317. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15318. }
  15319. };
  15320. PostProcess.prototype.apply = function () {
  15321. // Check
  15322. if (!this._effect.isReady())
  15323. return null;
  15324. // States
  15325. this._engine.enableEffect(this._effect);
  15326. this._engine.setState(false);
  15327. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15328. this._engine.setDepthBuffer(false);
  15329. this._engine.setDepthWrite(false);
  15330. // Texture
  15331. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15332. // Parameters
  15333. if (this.onApply) {
  15334. this.onApply(this._effect);
  15335. }
  15336. return this._effect;
  15337. };
  15338. PostProcess.prototype.dispose = function (camera) {
  15339. camera = camera || this._camera;
  15340. if (this._textures.length > 0) {
  15341. for (var i = 0; i < this._textures.length; i++) {
  15342. this._engine._releaseTexture(this._textures.data[i]);
  15343. }
  15344. this._textures.reset();
  15345. }
  15346. camera.detachPostProcess(this);
  15347. var index = camera._postProcesses.indexOf(this);
  15348. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15349. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15350. }
  15351. };
  15352. return PostProcess;
  15353. })();
  15354. BABYLON.PostProcess = PostProcess;
  15355. })(BABYLON || (BABYLON = {}));
  15356. //# sourceMappingURL=babylon.postProcess.js.map
  15357. var BABYLON;
  15358. (function (BABYLON) {
  15359. var PostProcessManager = (function () {
  15360. function PostProcessManager(scene) {
  15361. this._vertexDeclaration = [2];
  15362. this._vertexStrideSize = 2 * 4;
  15363. this._scene = scene;
  15364. // VBO
  15365. var vertices = [];
  15366. vertices.push(1, 1);
  15367. vertices.push(-1, 1);
  15368. vertices.push(-1, -1);
  15369. vertices.push(1, -1);
  15370. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15371. // Indices
  15372. var indices = [];
  15373. indices.push(0);
  15374. indices.push(1);
  15375. indices.push(2);
  15376. indices.push(0);
  15377. indices.push(2);
  15378. indices.push(3);
  15379. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15380. }
  15381. // Methods
  15382. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15383. var postProcesses = this._scene.activeCamera._postProcesses;
  15384. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15385. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15386. return false;
  15387. }
  15388. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15389. return true;
  15390. };
  15391. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15392. var postProcesses = this._scene.activeCamera._postProcesses;
  15393. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15394. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15395. return;
  15396. }
  15397. var engine = this._scene.getEngine();
  15398. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15399. if (index < postProcessesTakenIndices.length - 1) {
  15400. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15401. } else {
  15402. if (targetTexture) {
  15403. engine.bindFramebuffer(targetTexture);
  15404. } else {
  15405. engine.restoreDefaultFramebuffer();
  15406. }
  15407. }
  15408. if (doNotPresent) {
  15409. break;
  15410. }
  15411. var pp = postProcesses[postProcessesTakenIndices[index]];
  15412. var effect = pp.apply();
  15413. if (effect) {
  15414. if (pp.onBeforeRender) {
  15415. pp.onBeforeRender(effect);
  15416. }
  15417. // VBOs
  15418. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15419. // Draw order
  15420. engine.draw(true, 0, 6);
  15421. }
  15422. }
  15423. // Restore depth buffer
  15424. engine.setDepthBuffer(true);
  15425. engine.setDepthWrite(true);
  15426. };
  15427. PostProcessManager.prototype.dispose = function () {
  15428. if (this._vertexBuffer) {
  15429. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15430. this._vertexBuffer = null;
  15431. }
  15432. if (this._indexBuffer) {
  15433. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15434. this._indexBuffer = null;
  15435. }
  15436. };
  15437. return PostProcessManager;
  15438. })();
  15439. BABYLON.PostProcessManager = PostProcessManager;
  15440. })(BABYLON || (BABYLON = {}));
  15441. //# sourceMappingURL=babylon.postProcessManager.js.map
  15442. var BABYLON;
  15443. (function (BABYLON) {
  15444. var PassPostProcess = (function (_super) {
  15445. __extends(PassPostProcess, _super);
  15446. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15447. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15448. }
  15449. return PassPostProcess;
  15450. })(BABYLON.PostProcess);
  15451. BABYLON.PassPostProcess = PassPostProcess;
  15452. })(BABYLON || (BABYLON = {}));
  15453. //# sourceMappingURL=babylon.passPostProcess.js.map
  15454. var BABYLON;
  15455. (function (BABYLON) {
  15456. var BlurPostProcess = (function (_super) {
  15457. __extends(BlurPostProcess, _super);
  15458. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15459. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15460. var _this = this;
  15461. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15462. this.direction = direction;
  15463. this.blurWidth = blurWidth;
  15464. this.onApply = function (effect) {
  15465. effect.setFloat2("screenSize", _this.width, _this.height);
  15466. effect.setVector2("direction", _this.direction);
  15467. effect.setFloat("blurWidth", _this.blurWidth);
  15468. };
  15469. }
  15470. return BlurPostProcess;
  15471. })(BABYLON.PostProcess);
  15472. BABYLON.BlurPostProcess = BlurPostProcess;
  15473. })(BABYLON || (BABYLON = {}));
  15474. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15475. var BABYLON;
  15476. (function (BABYLON) {
  15477. var FilterPostProcess = (function (_super) {
  15478. __extends(FilterPostProcess, _super);
  15479. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15480. var _this = this;
  15481. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15482. this.kernelMatrix = kernelMatrix;
  15483. this.onApply = function (effect) {
  15484. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15485. };
  15486. }
  15487. return FilterPostProcess;
  15488. })(BABYLON.PostProcess);
  15489. BABYLON.FilterPostProcess = FilterPostProcess;
  15490. })(BABYLON || (BABYLON = {}));
  15491. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15492. var BABYLON;
  15493. (function (BABYLON) {
  15494. var RefractionPostProcess = (function (_super) {
  15495. __extends(RefractionPostProcess, _super);
  15496. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15497. var _this = this;
  15498. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15499. this.color = color;
  15500. this.depth = depth;
  15501. this.colorLevel = colorLevel;
  15502. this.onActivate = function (cam) {
  15503. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15504. };
  15505. this.onApply = function (effect) {
  15506. effect.setColor3("baseColor", _this.color);
  15507. effect.setFloat("depth", _this.depth);
  15508. effect.setFloat("colorLevel", _this.colorLevel);
  15509. effect.setTexture("refractionSampler", _this._refRexture);
  15510. };
  15511. }
  15512. // Methods
  15513. RefractionPostProcess.prototype.dispose = function (camera) {
  15514. if (this._refRexture) {
  15515. this._refRexture.dispose();
  15516. }
  15517. _super.prototype.dispose.call(this, camera);
  15518. };
  15519. return RefractionPostProcess;
  15520. })(BABYLON.PostProcess);
  15521. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15522. })(BABYLON || (BABYLON = {}));
  15523. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15524. var BABYLON;
  15525. (function (BABYLON) {
  15526. var BlackAndWhitePostProcess = (function (_super) {
  15527. __extends(BlackAndWhitePostProcess, _super);
  15528. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15529. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15530. }
  15531. return BlackAndWhitePostProcess;
  15532. })(BABYLON.PostProcess);
  15533. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15534. })(BABYLON || (BABYLON = {}));
  15535. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15536. var BABYLON;
  15537. (function (BABYLON) {
  15538. var ConvolutionPostProcess = (function (_super) {
  15539. __extends(ConvolutionPostProcess, _super);
  15540. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15541. var _this = this;
  15542. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15543. this.kernel = kernel;
  15544. this.onApply = function (effect) {
  15545. effect.setFloat2("screenSize", _this.width, _this.height);
  15546. effect.setArray("kernel", _this.kernel);
  15547. };
  15548. }
  15549. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15550. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15551. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15552. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15553. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15554. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15555. return ConvolutionPostProcess;
  15556. })(BABYLON.PostProcess);
  15557. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15558. })(BABYLON || (BABYLON = {}));
  15559. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15560. var BABYLON;
  15561. (function (BABYLON) {
  15562. var FxaaPostProcess = (function (_super) {
  15563. __extends(FxaaPostProcess, _super);
  15564. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15565. var _this = this;
  15566. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15567. this.onSizeChanged = function () {
  15568. _this.texelWidth = 1.0 / _this.width;
  15569. _this.texelHeight = 1.0 / _this.height;
  15570. };
  15571. this.onApply = function (effect) {
  15572. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15573. };
  15574. }
  15575. return FxaaPostProcess;
  15576. })(BABYLON.PostProcess);
  15577. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15578. })(BABYLON || (BABYLON = {}));
  15579. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15580. var BABYLON;
  15581. (function (BABYLON) {
  15582. var LensFlare = (function () {
  15583. function LensFlare(size, position, color, imgUrl, system) {
  15584. this.size = size;
  15585. this.position = position;
  15586. this.dispose = function () {
  15587. if (this.texture) {
  15588. this.texture.dispose();
  15589. }
  15590. // Remove from scene
  15591. var index = this._system.lensFlares.indexOf(this);
  15592. this._system.lensFlares.splice(index, 1);
  15593. };
  15594. this.color = color || new BABYLON.Color3(1, 1, 1);
  15595. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15596. this._system = system;
  15597. system.lensFlares.push(this);
  15598. }
  15599. return LensFlare;
  15600. })();
  15601. BABYLON.LensFlare = LensFlare;
  15602. })(BABYLON || (BABYLON = {}));
  15603. //# sourceMappingURL=babylon.lensFlare.js.map
  15604. var BABYLON;
  15605. (function (BABYLON) {
  15606. var LensFlareSystem = (function () {
  15607. function LensFlareSystem(name, emitter, scene) {
  15608. this.name = name;
  15609. this.lensFlares = new Array();
  15610. this.borderLimit = 300;
  15611. this._vertexDeclaration = [2];
  15612. this._vertexStrideSize = 2 * 4;
  15613. this._isEnabled = true;
  15614. this._scene = scene;
  15615. this._emitter = emitter;
  15616. scene.lensFlareSystems.push(this);
  15617. this.meshesSelectionPredicate = function (m) {
  15618. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15619. };
  15620. // VBO
  15621. var vertices = [];
  15622. vertices.push(1, 1);
  15623. vertices.push(-1, 1);
  15624. vertices.push(-1, -1);
  15625. vertices.push(1, -1);
  15626. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15627. // Indices
  15628. var indices = [];
  15629. indices.push(0);
  15630. indices.push(1);
  15631. indices.push(2);
  15632. indices.push(0);
  15633. indices.push(2);
  15634. indices.push(3);
  15635. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15636. // Effects
  15637. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15638. }
  15639. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15640. get: function () {
  15641. return this._isEnabled;
  15642. },
  15643. set: function (value) {
  15644. this._isEnabled = value;
  15645. },
  15646. enumerable: true,
  15647. configurable: true
  15648. });
  15649. LensFlareSystem.prototype.getScene = function () {
  15650. return this._scene;
  15651. };
  15652. LensFlareSystem.prototype.getEmitter = function () {
  15653. return this._emitter;
  15654. };
  15655. LensFlareSystem.prototype.getEmitterPosition = function () {
  15656. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15657. };
  15658. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15659. var position = this.getEmitterPosition();
  15660. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15661. this._positionX = position.x;
  15662. this._positionY = position.y;
  15663. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15664. if (position.z > 0) {
  15665. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15666. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15667. return true;
  15668. }
  15669. }
  15670. return false;
  15671. };
  15672. LensFlareSystem.prototype._isVisible = function () {
  15673. if (!this._isEnabled) {
  15674. return false;
  15675. }
  15676. var emitterPosition = this.getEmitterPosition();
  15677. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15678. var distance = direction.length();
  15679. direction.normalize();
  15680. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15681. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15682. return !pickInfo.hit || pickInfo.distance > distance;
  15683. };
  15684. LensFlareSystem.prototype.render = function () {
  15685. if (!this._effect.isReady())
  15686. return false;
  15687. var engine = this._scene.getEngine();
  15688. var viewport = this._scene.activeCamera.viewport;
  15689. var globalViewport = viewport.toGlobal(engine);
  15690. // Position
  15691. if (!this.computeEffectivePosition(globalViewport)) {
  15692. return false;
  15693. }
  15694. // Visibility
  15695. if (!this._isVisible()) {
  15696. return false;
  15697. }
  15698. // Intensity
  15699. var awayX;
  15700. var awayY;
  15701. if (this._positionX < this.borderLimit + globalViewport.x) {
  15702. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15703. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15704. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15705. } else {
  15706. awayX = 0;
  15707. }
  15708. if (this._positionY < this.borderLimit + globalViewport.y) {
  15709. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15710. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15711. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15712. } else {
  15713. awayY = 0;
  15714. }
  15715. var away = (awayX > awayY) ? awayX : awayY;
  15716. if (away > this.borderLimit) {
  15717. away = this.borderLimit;
  15718. }
  15719. var intensity = 1.0 - (away / this.borderLimit);
  15720. if (intensity < 0) {
  15721. return false;
  15722. }
  15723. if (intensity > 1.0) {
  15724. intensity = 1.0;
  15725. }
  15726. // Position
  15727. var centerX = globalViewport.x + globalViewport.width / 2;
  15728. var centerY = globalViewport.y + globalViewport.height / 2;
  15729. var distX = centerX - this._positionX;
  15730. var distY = centerY - this._positionY;
  15731. // Effects
  15732. engine.enableEffect(this._effect);
  15733. engine.setState(false);
  15734. engine.setDepthBuffer(false);
  15735. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15736. // VBOs
  15737. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15738. for (var index = 0; index < this.lensFlares.length; index++) {
  15739. var flare = this.lensFlares[index];
  15740. var x = centerX - (distX * flare.position);
  15741. var y = centerY - (distY * flare.position);
  15742. var cw = flare.size;
  15743. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15744. var cx = 2 * (x / globalViewport.width) - 1.0;
  15745. var cy = 1.0 - 2 * (y / globalViewport.height);
  15746. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15747. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15748. // Texture
  15749. this._effect.setTexture("textureSampler", flare.texture);
  15750. // Color
  15751. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15752. // Draw order
  15753. engine.draw(true, 0, 6);
  15754. }
  15755. engine.setDepthBuffer(true);
  15756. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15757. return true;
  15758. };
  15759. LensFlareSystem.prototype.dispose = function () {
  15760. if (this._vertexBuffer) {
  15761. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15762. this._vertexBuffer = null;
  15763. }
  15764. if (this._indexBuffer) {
  15765. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15766. this._indexBuffer = null;
  15767. }
  15768. while (this.lensFlares.length) {
  15769. this.lensFlares[0].dispose();
  15770. }
  15771. // Remove from scene
  15772. var index = this._scene.lensFlareSystems.indexOf(this);
  15773. this._scene.lensFlareSystems.splice(index, 1);
  15774. };
  15775. return LensFlareSystem;
  15776. })();
  15777. BABYLON.LensFlareSystem = LensFlareSystem;
  15778. })(BABYLON || (BABYLON = {}));
  15779. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15780. var BABYLON;
  15781. (function (BABYLON) {
  15782. var IntersectionInfo = (function () {
  15783. function IntersectionInfo(bu, bv, distance) {
  15784. this.bu = bu;
  15785. this.bv = bv;
  15786. this.distance = distance;
  15787. this.faceId = 0;
  15788. }
  15789. return IntersectionInfo;
  15790. })();
  15791. BABYLON.IntersectionInfo = IntersectionInfo;
  15792. var PickingInfo = (function () {
  15793. function PickingInfo() {
  15794. this.hit = false;
  15795. this.distance = 0;
  15796. this.pickedPoint = null;
  15797. this.pickedMesh = null;
  15798. this.bu = 0;
  15799. this.bv = 0;
  15800. this.faceId = -1;
  15801. }
  15802. // Methods
  15803. PickingInfo.prototype.getNormal = function () {
  15804. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15805. return null;
  15806. }
  15807. var indices = this.pickedMesh.getIndices();
  15808. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15809. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15810. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15811. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15812. normal0 = normal0.scale(this.bu);
  15813. normal1 = normal1.scale(this.bv);
  15814. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15815. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15816. };
  15817. PickingInfo.prototype.getTextureCoordinates = function () {
  15818. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15819. return null;
  15820. }
  15821. var indices = this.pickedMesh.getIndices();
  15822. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15823. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15824. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15825. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15826. uv0 = uv0.scale(this.bu);
  15827. uv1 = uv1.scale(this.bv);
  15828. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15829. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15830. };
  15831. return PickingInfo;
  15832. })();
  15833. BABYLON.PickingInfo = PickingInfo;
  15834. })(BABYLON || (BABYLON = {}));
  15835. //# sourceMappingURL=babylon.pickingInfo.js.map
  15836. var BABYLON;
  15837. (function (BABYLON) {
  15838. var FilesInput = (function () {
  15839. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15840. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15841. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15842. this.engine = p_engine;
  15843. this.canvas = p_canvas;
  15844. this.currentScene = p_scene;
  15845. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15846. this.progressCallback = p_progressCallback;
  15847. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15848. this.textureLoadingCallback = p_textureLoadingCallback;
  15849. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15850. }
  15851. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15852. var _this = this;
  15853. if (p_elementToMonitor) {
  15854. this.elementToMonitor = p_elementToMonitor;
  15855. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15856. _this.drag(e);
  15857. }, false);
  15858. this.elementToMonitor.addEventListener("dragover", function (e) {
  15859. _this.drag(e);
  15860. }, false);
  15861. this.elementToMonitor.addEventListener("drop", function (e) {
  15862. _this.drop(e);
  15863. }, false);
  15864. }
  15865. };
  15866. FilesInput.prototype.renderFunction = function () {
  15867. if (this.additionnalRenderLoopLogicCallback) {
  15868. this.additionnalRenderLoopLogicCallback();
  15869. }
  15870. if (this.currentScene) {
  15871. if (this.textureLoadingCallback) {
  15872. var remaining = this.currentScene.getWaitingItemsCount();
  15873. if (remaining > 0) {
  15874. this.textureLoadingCallback(remaining);
  15875. }
  15876. }
  15877. this.currentScene.render();
  15878. }
  15879. };
  15880. FilesInput.prototype.drag = function (e) {
  15881. e.stopPropagation();
  15882. e.preventDefault();
  15883. };
  15884. FilesInput.prototype.drop = function (eventDrop) {
  15885. eventDrop.stopPropagation();
  15886. eventDrop.preventDefault();
  15887. this.loadFiles(eventDrop);
  15888. };
  15889. FilesInput.prototype.loadFiles = function (event) {
  15890. var _this = this;
  15891. var that = this;
  15892. if (this.startingProcessingFilesCallback)
  15893. this.startingProcessingFilesCallback();
  15894. var sceneFileToLoad;
  15895. var filesToLoad;
  15896. // Handling data transfer via drag'n'drop
  15897. if (event && event.dataTransfer && event.dataTransfer.files) {
  15898. filesToLoad = event.dataTransfer.files;
  15899. }
  15900. // Handling files from input files
  15901. if (event && event.target && event.target.files) {
  15902. filesToLoad = event.target.files;
  15903. }
  15904. if (filesToLoad && filesToLoad.length > 0) {
  15905. for (var i = 0; i < filesToLoad.length; i++) {
  15906. switch (filesToLoad[i].type) {
  15907. case "image/jpeg":
  15908. case "image/png":
  15909. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15910. break;
  15911. case "image/targa":
  15912. case "image/vnd.ms-dds":
  15913. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15914. break;
  15915. default:
  15916. 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) {
  15917. sceneFileToLoad = filesToLoad[i];
  15918. }
  15919. break;
  15920. }
  15921. }
  15922. // If a ".babylon" file has been provided
  15923. if (sceneFileToLoad) {
  15924. if (this.currentScene) {
  15925. this.engine.stopRenderLoop();
  15926. this.currentScene.dispose();
  15927. }
  15928. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15929. that.currentScene = newScene;
  15930. // Wait for textures and shaders to be ready
  15931. that.currentScene.executeWhenReady(function () {
  15932. // Attach camera to canvas inputs
  15933. if (that.currentScene.activeCamera) {
  15934. that.currentScene.activeCamera.attachControl(that.canvas);
  15935. }
  15936. if (that.sceneLoadedCallback) {
  15937. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15938. }
  15939. that.engine.runRenderLoop(function () {
  15940. that.renderFunction();
  15941. });
  15942. });
  15943. }, function (progress) {
  15944. if (_this.progressCallback) {
  15945. _this.progressCallback(progress);
  15946. }
  15947. });
  15948. } else {
  15949. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15950. }
  15951. }
  15952. };
  15953. FilesInput.FilesTextures = new Array();
  15954. FilesInput.FilesToLoad = new Array();
  15955. return FilesInput;
  15956. })();
  15957. BABYLON.FilesInput = FilesInput;
  15958. })(BABYLON || (BABYLON = {}));
  15959. //# sourceMappingURL=babylon.filesInput.js.map
  15960. var BABYLON;
  15961. (function (BABYLON) {
  15962. var OimoJSPlugin = (function () {
  15963. function OimoJSPlugin() {
  15964. this._registeredMeshes = [];
  15965. /**
  15966. * Update the body position according to the mesh position
  15967. * @param mesh
  15968. */
  15969. this.updateBodyPosition = function (mesh) {
  15970. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15971. var registeredMesh = this._registeredMeshes[index];
  15972. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15973. var body = registeredMesh.body.body;
  15974. mesh.computeWorldMatrix(true);
  15975. var center = mesh.getBoundingInfo().boundingBox.center;
  15976. body.setPosition(center.x, center.y, center.z);
  15977. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15978. return;
  15979. }
  15980. // Case where the parent has been updated
  15981. if (registeredMesh.mesh.parent === mesh) {
  15982. mesh.computeWorldMatrix(true);
  15983. registeredMesh.mesh.computeWorldMatrix(true);
  15984. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15985. var absoluteRotation = mesh.rotation;
  15986. body = registeredMesh.body.body;
  15987. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15988. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15989. return;
  15990. }
  15991. }
  15992. };
  15993. }
  15994. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15995. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15996. };
  15997. OimoJSPlugin.prototype.initialize = function (iterations) {
  15998. this._world = new OIMO.World();
  15999. this._world.clear();
  16000. };
  16001. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16002. this._world.gravity = gravity;
  16003. };
  16004. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16005. var body = null;
  16006. this.unregisterMesh(mesh);
  16007. mesh.computeWorldMatrix(true);
  16008. switch (impostor) {
  16009. case BABYLON.PhysicsEngine.SphereImpostor:
  16010. var bbox = mesh.getBoundingInfo().boundingBox;
  16011. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16012. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16013. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16014. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16015. // The delta between the mesh position and the mesh bounding box center
  16016. var deltaPosition = mesh.position.subtract(bbox.center);
  16017. body = new OIMO.Body({
  16018. type: 'sphere',
  16019. size: [size],
  16020. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16021. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16022. move: options.mass != 0,
  16023. config: [options.mass, options.friction, options.restitution],
  16024. world: this._world
  16025. });
  16026. this._registeredMeshes.push({
  16027. mesh: mesh,
  16028. body: body,
  16029. delta: deltaPosition
  16030. });
  16031. break;
  16032. case BABYLON.PhysicsEngine.PlaneImpostor:
  16033. case BABYLON.PhysicsEngine.BoxImpostor:
  16034. bbox = mesh.getBoundingInfo().boundingBox;
  16035. var min = bbox.minimumWorld;
  16036. var max = bbox.maximumWorld;
  16037. var box = max.subtract(min);
  16038. var sizeX = this._checkWithEpsilon(box.x);
  16039. var sizeY = this._checkWithEpsilon(box.y);
  16040. var sizeZ = this._checkWithEpsilon(box.z);
  16041. // The delta between the mesh position and the mesh boudning box center
  16042. var deltaPosition = mesh.position.subtract(bbox.center);
  16043. body = new OIMO.Body({
  16044. type: 'box',
  16045. size: [sizeX, sizeY, sizeZ],
  16046. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16047. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16048. move: options.mass != 0,
  16049. config: [options.mass, options.friction, options.restitution],
  16050. world: this._world
  16051. });
  16052. this._registeredMeshes.push({
  16053. mesh: mesh,
  16054. body: body,
  16055. delta: deltaPosition
  16056. });
  16057. break;
  16058. }
  16059. return body;
  16060. };
  16061. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16062. var types = [], sizes = [], positions = [], rotations = [];
  16063. var initialMesh = parts[0].mesh;
  16064. for (var index = 0; index < parts.length; index++) {
  16065. var part = parts[index];
  16066. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16067. types.push(bodyParameters.type);
  16068. sizes.push.apply(sizes, bodyParameters.size);
  16069. positions.push.apply(positions, bodyParameters.pos);
  16070. rotations.push.apply(rotations, bodyParameters.rot);
  16071. }
  16072. var body = new OIMO.Body({
  16073. type: types,
  16074. size: sizes,
  16075. pos: positions,
  16076. rot: rotations,
  16077. move: options.mass != 0,
  16078. config: [options.mass, options.friction, options.restitution],
  16079. world: this._world
  16080. });
  16081. this._registeredMeshes.push({
  16082. mesh: initialMesh,
  16083. body: body
  16084. });
  16085. return body;
  16086. };
  16087. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16088. var bodyParameters = null;
  16089. var mesh = part.mesh;
  16090. switch (part.impostor) {
  16091. case BABYLON.PhysicsEngine.SphereImpostor:
  16092. var bbox = mesh.getBoundingInfo().boundingBox;
  16093. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16094. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16095. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16096. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16097. bodyParameters = {
  16098. type: 'sphere',
  16099. /* bug with oimo : sphere needs 3 sizes in this case */
  16100. size: [size, -1, -1],
  16101. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16102. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16103. };
  16104. break;
  16105. case BABYLON.PhysicsEngine.PlaneImpostor:
  16106. case BABYLON.PhysicsEngine.BoxImpostor:
  16107. bbox = mesh.getBoundingInfo().boundingBox;
  16108. var min = bbox.minimumWorld;
  16109. var max = bbox.maximumWorld;
  16110. var box = max.subtract(min);
  16111. var sizeX = this._checkWithEpsilon(box.x);
  16112. var sizeY = this._checkWithEpsilon(box.y);
  16113. var sizeZ = this._checkWithEpsilon(box.z);
  16114. var relativePosition = mesh.position;
  16115. bodyParameters = {
  16116. type: 'box',
  16117. size: [sizeX, sizeY, sizeZ],
  16118. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16119. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16120. };
  16121. break;
  16122. }
  16123. return bodyParameters;
  16124. };
  16125. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16126. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16127. var registeredMesh = this._registeredMeshes[index];
  16128. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16129. if (registeredMesh.body) {
  16130. this._world.removeRigidBody(registeredMesh.body.body);
  16131. this._unbindBody(registeredMesh.body);
  16132. }
  16133. this._registeredMeshes.splice(index, 1);
  16134. return;
  16135. }
  16136. }
  16137. };
  16138. OimoJSPlugin.prototype._unbindBody = function (body) {
  16139. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16140. var registeredMesh = this._registeredMeshes[index];
  16141. if (registeredMesh.body === body) {
  16142. registeredMesh.body = null;
  16143. }
  16144. }
  16145. };
  16146. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16147. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16148. var registeredMesh = this._registeredMeshes[index];
  16149. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16150. // Get object mass to have a behaviour similar to cannon.js
  16151. var mass = registeredMesh.body.body.massInfo.mass;
  16152. // The force is scaled with the mass of object
  16153. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16154. return;
  16155. }
  16156. }
  16157. };
  16158. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16159. var body1 = null, body2 = null;
  16160. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16161. var registeredMesh = this._registeredMeshes[index];
  16162. if (registeredMesh.mesh === mesh1) {
  16163. body1 = registeredMesh.body.body;
  16164. } else if (registeredMesh.mesh === mesh2) {
  16165. body2 = registeredMesh.body.body;
  16166. }
  16167. }
  16168. if (!body1 || !body2) {
  16169. return false;
  16170. }
  16171. if (!options) {
  16172. options = {};
  16173. }
  16174. new OIMO.Link({
  16175. type: options.type,
  16176. body1: body1,
  16177. body2: body2,
  16178. min: options.min,
  16179. max: options.max,
  16180. axe1: options.axe1,
  16181. axe2: options.axe2,
  16182. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16183. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16184. collision: options.collision,
  16185. spring: options.spring,
  16186. world: this._world
  16187. });
  16188. return true;
  16189. };
  16190. OimoJSPlugin.prototype.dispose = function () {
  16191. this._world.clear();
  16192. while (this._registeredMeshes.length) {
  16193. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16194. }
  16195. };
  16196. OimoJSPlugin.prototype.isSupported = function () {
  16197. return OIMO !== undefined;
  16198. };
  16199. OimoJSPlugin.prototype._getLastShape = function (body) {
  16200. var lastShape = body.shapes;
  16201. while (lastShape.next) {
  16202. lastShape = lastShape.next;
  16203. }
  16204. return lastShape;
  16205. };
  16206. OimoJSPlugin.prototype.runOneStep = function (time) {
  16207. this._world.step();
  16208. // Update the position of all registered meshes
  16209. var i = this._registeredMeshes.length;
  16210. var m;
  16211. while (i--) {
  16212. var body = this._registeredMeshes[i].body.body;
  16213. var mesh = this._registeredMeshes[i].mesh;
  16214. var delta = this._registeredMeshes[i].delta;
  16215. if (!body.sleeping) {
  16216. if (body.shapes.next) {
  16217. var parentShape = this._getLastShape(body);
  16218. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16219. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16220. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16221. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16222. if (!mesh.rotationQuaternion) {
  16223. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16224. }
  16225. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16226. mesh.computeWorldMatrix();
  16227. } else {
  16228. m = body.getMatrix();
  16229. mtx = BABYLON.Matrix.FromArray(m);
  16230. // Body position
  16231. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16232. if (!delta) {
  16233. mesh.position.x = bodyX;
  16234. mesh.position.y = bodyY;
  16235. mesh.position.z = bodyZ;
  16236. } else {
  16237. mesh.position.x = bodyX + delta.x;
  16238. mesh.position.y = bodyY + delta.y;
  16239. mesh.position.z = bodyZ + delta.z;
  16240. }
  16241. if (!mesh.rotationQuaternion) {
  16242. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16243. }
  16244. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16245. mesh.computeWorldMatrix();
  16246. }
  16247. }
  16248. }
  16249. };
  16250. return OimoJSPlugin;
  16251. })();
  16252. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16253. })(BABYLON || (BABYLON = {}));
  16254. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16255. var BABYLON;
  16256. (function (BABYLON) {
  16257. var PhysicsEngine = (function () {
  16258. function PhysicsEngine(plugin) {
  16259. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16260. }
  16261. PhysicsEngine.prototype._initialize = function (gravity) {
  16262. this._currentPlugin.initialize();
  16263. this._setGravity(gravity);
  16264. };
  16265. PhysicsEngine.prototype._runOneStep = function (delta) {
  16266. if (delta > 0.1) {
  16267. delta = 0.1;
  16268. } else if (delta <= 0) {
  16269. delta = 1.0 / 60.0;
  16270. }
  16271. this._currentPlugin.runOneStep(delta);
  16272. };
  16273. PhysicsEngine.prototype._setGravity = function (gravity) {
  16274. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16275. this._currentPlugin.setGravity(this.gravity);
  16276. };
  16277. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16278. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16279. };
  16280. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16281. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16282. };
  16283. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16284. this._currentPlugin.unregisterMesh(mesh);
  16285. };
  16286. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16287. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16288. };
  16289. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16290. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16291. };
  16292. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16293. this._currentPlugin.updateBodyPosition(mesh);
  16294. };
  16295. PhysicsEngine.prototype.dispose = function () {
  16296. this._currentPlugin.dispose();
  16297. };
  16298. PhysicsEngine.prototype.isSupported = function () {
  16299. return this._currentPlugin.isSupported();
  16300. };
  16301. PhysicsEngine.NoImpostor = 0;
  16302. PhysicsEngine.SphereImpostor = 1;
  16303. PhysicsEngine.BoxImpostor = 2;
  16304. PhysicsEngine.PlaneImpostor = 3;
  16305. PhysicsEngine.MeshImpostor = 4;
  16306. PhysicsEngine.CapsuleImpostor = 5;
  16307. PhysicsEngine.ConeImpostor = 6;
  16308. PhysicsEngine.CylinderImpostor = 7;
  16309. PhysicsEngine.ConvexHullImpostor = 8;
  16310. PhysicsEngine.Epsilon = 0.001;
  16311. return PhysicsEngine;
  16312. })();
  16313. BABYLON.PhysicsEngine = PhysicsEngine;
  16314. })(BABYLON || (BABYLON = {}));
  16315. //# sourceMappingURL=babylon.physicsEngine.js.map
  16316. var BABYLON;
  16317. (function (BABYLON) {
  16318. var serializeLight = function (light) {
  16319. var serializationObject = {};
  16320. serializationObject.name = light.name;
  16321. serializationObject.id = light.id;
  16322. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16323. if (light instanceof BABYLON.PointLight) {
  16324. serializationObject.type = 0;
  16325. serializationObject.position = light.position.asArray();
  16326. } else if (light instanceof BABYLON.DirectionalLight) {
  16327. serializationObject.type = 1;
  16328. var directionalLight = light;
  16329. serializationObject.position = directionalLight.position.asArray();
  16330. serializationObject.direction = directionalLight.direction.asArray();
  16331. } else if (light instanceof BABYLON.SpotLight) {
  16332. serializationObject.type = 2;
  16333. var spotLight = light;
  16334. serializationObject.position = spotLight.position.asArray();
  16335. serializationObject.direction = spotLight.position.asArray();
  16336. serializationObject.angle = spotLight.angle;
  16337. serializationObject.exponent = spotLight.exponent;
  16338. } else if (light instanceof BABYLON.HemisphericLight) {
  16339. serializationObject.type = 3;
  16340. var hemisphericLight = light;
  16341. serializationObject.direction = hemisphericLight.direction.asArray();
  16342. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16343. }
  16344. if (light.intensity) {
  16345. serializationObject.intensity = light.intensity;
  16346. }
  16347. serializationObject.range = light.range;
  16348. serializationObject.diffuse = light.diffuse.asArray();
  16349. serializationObject.specular = light.specular.asArray();
  16350. return serializationObject;
  16351. };
  16352. var serializeFresnelParameter = function (fresnelParameter) {
  16353. var serializationObject = {};
  16354. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16355. serializationObject.leftColor = fresnelParameter.leftColor;
  16356. serializationObject.rightColor = fresnelParameter.rightColor;
  16357. serializationObject.bias = fresnelParameter.bias;
  16358. serializationObject.power = fresnelParameter.power;
  16359. return serializationObject;
  16360. };
  16361. var serializeCamera = function (camera) {
  16362. var serializationObject = {};
  16363. serializationObject.name = camera.name;
  16364. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16365. serializationObject.id = camera.id;
  16366. serializationObject.position = camera.position.asArray();
  16367. // Parent
  16368. if (camera.parent) {
  16369. serializationObject.parentId = camera.parent.id;
  16370. }
  16371. // Target
  16372. serializationObject.rotation = camera.rotation.asArray();
  16373. // Locked target
  16374. if (camera.lockedTarget && camera.lockedTarget.id) {
  16375. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16376. }
  16377. serializationObject.fov = camera.fov;
  16378. serializationObject.minZ = camera.minZ;
  16379. serializationObject.maxZ = camera.maxZ;
  16380. serializationObject.speed = camera.speed;
  16381. serializationObject.inertia = camera.inertia;
  16382. serializationObject.checkCollisions = camera.checkCollisions;
  16383. serializationObject.applyGravity = camera.applyGravity;
  16384. if (camera.ellipsoid) {
  16385. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16386. }
  16387. // Animations
  16388. appendAnimations(camera, serializationObject);
  16389. // Layer mask
  16390. serializationObject.layerMask = camera.layerMask;
  16391. return serializationObject;
  16392. };
  16393. var appendAnimations = function (source, destination) {
  16394. if (source.animations) {
  16395. destination.animations = [];
  16396. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16397. var animation = source.animations[animationIndex];
  16398. destination.animations.push(serializeAnimation(animation));
  16399. }
  16400. }
  16401. };
  16402. var serializeAnimation = function (animation) {
  16403. var serializationObject = {};
  16404. serializationObject.name = animation.name;
  16405. serializationObject.property = animation.targetProperty;
  16406. serializationObject.framePerSecond = animation.framePerSecond;
  16407. serializationObject.dataType = animation.dataType;
  16408. serializationObject.loopBehavior = animation.loopMode;
  16409. var dataType = animation.dataType;
  16410. serializationObject.keys = [];
  16411. var keys = animation.getKeys();
  16412. for (var index = 0; index < keys.length; index++) {
  16413. var animationKey = keys[index];
  16414. var key = {};
  16415. key.frame = animationKey.frame;
  16416. switch (dataType) {
  16417. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16418. key.values = [animationKey.value];
  16419. break;
  16420. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16421. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16422. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16423. key.values = animationKey.value.asArray();
  16424. break;
  16425. }
  16426. serializationObject.keys.push(key);
  16427. }
  16428. return serializationObject;
  16429. };
  16430. var serializeMultiMaterial = function (material) {
  16431. var serializationObject = {};
  16432. serializationObject.name = material.name;
  16433. serializationObject.id = material.id;
  16434. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16435. serializationObject.materials = [];
  16436. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16437. var subMat = material.subMaterials[matIndex];
  16438. if (subMat) {
  16439. serializationObject.materials.push(subMat.id);
  16440. } else {
  16441. serializationObject.materials.push(null);
  16442. }
  16443. }
  16444. return serializationObject;
  16445. };
  16446. var serializeMaterial = function (material) {
  16447. var serializationObject = {};
  16448. serializationObject.name = material.name;
  16449. serializationObject.ambient = material.ambientColor.asArray();
  16450. serializationObject.diffuse = material.diffuseColor.asArray();
  16451. serializationObject.specular = material.specularColor.asArray();
  16452. serializationObject.specularPower = material.specularPower;
  16453. serializationObject.emissive = material.emissiveColor.asArray();
  16454. serializationObject.alpha = material.alpha;
  16455. serializationObject.id = material.id;
  16456. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16457. serializationObject.backFaceCulling = material.backFaceCulling;
  16458. if (material.diffuseTexture) {
  16459. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16460. }
  16461. if (material.diffuseFresnelParameters) {
  16462. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16463. }
  16464. if (material.ambientTexture) {
  16465. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16466. }
  16467. if (material.opacityTexture) {
  16468. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16469. }
  16470. if (material.opacityFresnelParameters) {
  16471. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16472. }
  16473. if (material.reflectionTexture) {
  16474. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16475. }
  16476. if (material.reflectionFresnelParameters) {
  16477. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16478. }
  16479. if (material.emissiveTexture) {
  16480. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16481. }
  16482. if (material.emissiveFresnelParameters) {
  16483. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16484. }
  16485. if (material.specularTexture) {
  16486. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16487. }
  16488. if (material.bumpTexture) {
  16489. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16490. }
  16491. return serializationObject;
  16492. };
  16493. var serializeTexture = function (texture) {
  16494. var serializationObject = {};
  16495. if (!texture.name) {
  16496. return null;
  16497. }
  16498. if (texture instanceof BABYLON.CubeTexture) {
  16499. serializationObject.name = texture.name;
  16500. serializationObject.hasAlpha = texture.hasAlpha;
  16501. serializationObject.level = texture.level;
  16502. serializationObject.coordinatesMode = texture.coordinatesMode;
  16503. return serializationObject;
  16504. }
  16505. if (texture instanceof BABYLON.MirrorTexture) {
  16506. var mirrorTexture = texture;
  16507. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16508. serializationObject.renderList = [];
  16509. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16510. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16511. }
  16512. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16513. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16514. var renderTargetTexture = texture;
  16515. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16516. serializationObject.renderList = [];
  16517. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16518. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16519. }
  16520. }
  16521. var regularTexture = texture;
  16522. serializationObject.name = texture.name;
  16523. serializationObject.hasAlpha = texture.hasAlpha;
  16524. serializationObject.level = texture.level;
  16525. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16526. serializationObject.coordinatesMode = texture.coordinatesMode;
  16527. serializationObject.uOffset = regularTexture.uOffset;
  16528. serializationObject.vOffset = regularTexture.vOffset;
  16529. serializationObject.uScale = regularTexture.uScale;
  16530. serializationObject.vScale = regularTexture.vScale;
  16531. serializationObject.uAng = regularTexture.uAng;
  16532. serializationObject.vAng = regularTexture.vAng;
  16533. serializationObject.wAng = regularTexture.wAng;
  16534. serializationObject.wrapU = texture.wrapU;
  16535. serializationObject.wrapV = texture.wrapV;
  16536. // Animations
  16537. appendAnimations(texture, serializationObject);
  16538. return serializationObject;
  16539. };
  16540. var serializeSkeleton = function (skeleton) {
  16541. var serializationObject = {};
  16542. serializationObject.name = skeleton.name;
  16543. serializationObject.id = skeleton.id;
  16544. serializationObject.bones = [];
  16545. for (var index = 0; index < skeleton.bones.length; index++) {
  16546. var bone = skeleton.bones[index];
  16547. var serializedBone = {
  16548. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16549. name: bone.name,
  16550. matrix: bone.getLocalMatrix().toArray()
  16551. };
  16552. serializationObject.bones.push(serializedBone);
  16553. if (bone.animations && bone.animations.length > 0) {
  16554. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16555. }
  16556. }
  16557. return serializationObject;
  16558. };
  16559. var serializeParticleSystem = function (particleSystem) {
  16560. var serializationObject = {};
  16561. serializationObject.emitterId = particleSystem.emitter.id;
  16562. serializationObject.capacity = particleSystem.getCapacity();
  16563. if (particleSystem.particleTexture) {
  16564. serializationObject.textureName = particleSystem.particleTexture.name;
  16565. }
  16566. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16567. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16568. serializationObject.minSize = particleSystem.minSize;
  16569. serializationObject.maxSize = particleSystem.maxSize;
  16570. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16571. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16572. serializationObject.emitRate = particleSystem.emitRate;
  16573. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16574. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16575. serializationObject.gravity = particleSystem.gravity.asArray();
  16576. serializationObject.direction1 = particleSystem.direction1.asArray();
  16577. serializationObject.direction2 = particleSystem.direction2.asArray();
  16578. serializationObject.color1 = particleSystem.color1.asArray();
  16579. serializationObject.color2 = particleSystem.color2.asArray();
  16580. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16581. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16582. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16583. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16584. serializationObject.blendMode = particleSystem.blendMode;
  16585. return serializationObject;
  16586. };
  16587. var serializeLensFlareSystem = function (lensFlareSystem) {
  16588. var serializationObject = {};
  16589. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16590. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16591. serializationObject.flares = [];
  16592. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16593. var flare = lensFlareSystem.lensFlares[index];
  16594. serializationObject.flares.push({
  16595. size: flare.size,
  16596. position: flare.position,
  16597. color: flare.color.asArray(),
  16598. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16599. });
  16600. }
  16601. return serializationObject;
  16602. };
  16603. var serializeShadowGenerator = function (light) {
  16604. var serializationObject = {};
  16605. var shadowGenerator = light.getShadowGenerator();
  16606. serializationObject.lightId = light.id;
  16607. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16608. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16609. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16610. serializationObject.renderList = [];
  16611. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16612. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16613. serializationObject.renderList.push(mesh.id);
  16614. }
  16615. return serializationObject;
  16616. };
  16617. var serializedGeometries = [];
  16618. var serializeGeometry = function (geometry, serializationGeometries) {
  16619. if (serializedGeometries[geometry.id]) {
  16620. return;
  16621. }
  16622. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16623. serializationGeometries.boxes.push(serializeBox(geometry));
  16624. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16625. serializationGeometries.spheres.push(serializeSphere(geometry));
  16626. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16627. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16628. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16629. serializationGeometries.toruses.push(serializeTorus(geometry));
  16630. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16631. serializationGeometries.grounds.push(serializeGround(geometry));
  16632. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16633. serializationGeometries.planes.push(serializePlane(geometry));
  16634. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16635. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16636. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16637. throw new Error("Unknow primitive type");
  16638. } else {
  16639. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16640. }
  16641. serializedGeometries[geometry.id] = true;
  16642. };
  16643. var serializeGeometryBase = function (geometry) {
  16644. var serializationObject = {};
  16645. serializationObject.id = geometry.id;
  16646. if (BABYLON.Tags.HasTags(geometry)) {
  16647. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16648. }
  16649. return serializationObject;
  16650. };
  16651. var serializeVertexData = function (vertexData) {
  16652. var serializationObject = serializeGeometryBase(vertexData);
  16653. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16654. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16655. }
  16656. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16657. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16658. }
  16659. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16660. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16661. }
  16662. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16663. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16664. }
  16665. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16666. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16667. }
  16668. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16669. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16670. serializationObject.matricesIndices._isExpanded = true;
  16671. }
  16672. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16673. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16674. }
  16675. serializationObject.indices = vertexData.getIndices();
  16676. return serializationObject;
  16677. };
  16678. var serializePrimitive = function (primitive) {
  16679. var serializationObject = serializeGeometryBase(primitive);
  16680. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16681. return serializationObject;
  16682. };
  16683. var serializeBox = function (box) {
  16684. var serializationObject = serializePrimitive(box);
  16685. serializationObject.size = box.size;
  16686. return serializationObject;
  16687. };
  16688. var serializeSphere = function (sphere) {
  16689. var serializationObject = serializePrimitive(sphere);
  16690. serializationObject.segments = sphere.segments;
  16691. serializationObject.diameter = sphere.diameter;
  16692. return serializationObject;
  16693. };
  16694. var serializeCylinder = function (cylinder) {
  16695. var serializationObject = serializePrimitive(cylinder);
  16696. serializationObject.height = cylinder.height;
  16697. serializationObject.diameterTop = cylinder.diameterTop;
  16698. serializationObject.diameterBottom = cylinder.diameterBottom;
  16699. serializationObject.tessellation = cylinder.tessellation;
  16700. return serializationObject;
  16701. };
  16702. var serializeTorus = function (torus) {
  16703. var serializationObject = serializePrimitive(torus);
  16704. serializationObject.diameter = torus.diameter;
  16705. serializationObject.thickness = torus.thickness;
  16706. serializationObject.tessellation = torus.tessellation;
  16707. return serializationObject;
  16708. };
  16709. var serializeGround = function (ground) {
  16710. var serializationObject = serializePrimitive(ground);
  16711. serializationObject.width = ground.width;
  16712. serializationObject.height = ground.height;
  16713. serializationObject.subdivisions = ground.subdivisions;
  16714. return serializationObject;
  16715. };
  16716. var serializePlane = function (plane) {
  16717. var serializationObject = serializePrimitive(plane);
  16718. serializationObject.size = plane.size;
  16719. return serializationObject;
  16720. };
  16721. var serializeTorusKnot = function (torusKnot) {
  16722. var serializationObject = serializePrimitive(torusKnot);
  16723. serializationObject.radius = torusKnot.radius;
  16724. serializationObject.tube = torusKnot.tube;
  16725. serializationObject.radialSegments = torusKnot.radialSegments;
  16726. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16727. serializationObject.p = torusKnot.p;
  16728. serializationObject.q = torusKnot.q;
  16729. return serializationObject;
  16730. };
  16731. var serializeMesh = function (mesh, serializationScene) {
  16732. var serializationObject = {};
  16733. serializationObject.name = mesh.name;
  16734. serializationObject.id = mesh.id;
  16735. if (BABYLON.Tags.HasTags(mesh)) {
  16736. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16737. }
  16738. serializationObject.position = mesh.position.asArray();
  16739. if (mesh.rotationQuaternion) {
  16740. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16741. } else if (mesh.rotation) {
  16742. serializationObject.rotation = mesh.rotation.asArray();
  16743. }
  16744. serializationObject.scaling = mesh.scaling.asArray();
  16745. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16746. serializationObject.isEnabled = mesh.isEnabled();
  16747. serializationObject.isVisible = mesh.isVisible;
  16748. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16749. serializationObject.pickable = mesh.isPickable;
  16750. serializationObject.receiveShadows = mesh.receiveShadows;
  16751. serializationObject.billboardMode = mesh.billboardMode;
  16752. serializationObject.visibility = mesh.visibility;
  16753. serializationObject.checkCollisions = mesh.checkCollisions;
  16754. // Parent
  16755. if (mesh.parent) {
  16756. serializationObject.parentId = mesh.parent.id;
  16757. }
  16758. // Geometry
  16759. var geometry = mesh._geometry;
  16760. if (geometry) {
  16761. var geometryId = geometry.id;
  16762. serializationObject.geometryId = geometryId;
  16763. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16764. // 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
  16765. serializeGeometry(geometry, serializationScene.geometries);
  16766. }
  16767. // SubMeshes
  16768. serializationObject.subMeshes = [];
  16769. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16770. var subMesh = mesh.subMeshes[subIndex];
  16771. serializationObject.subMeshes.push({
  16772. materialIndex: subMesh.materialIndex,
  16773. verticesStart: subMesh.verticesStart,
  16774. verticesCount: subMesh.verticesCount,
  16775. indexStart: subMesh.indexStart,
  16776. indexCount: subMesh.indexCount
  16777. });
  16778. }
  16779. }
  16780. // Material
  16781. if (mesh.material) {
  16782. serializationObject.materialId = mesh.material.id;
  16783. } else {
  16784. mesh.material = null;
  16785. }
  16786. // Skeleton
  16787. if (mesh.skeleton) {
  16788. serializationObject.skeletonId = mesh.skeleton.id;
  16789. }
  16790. // Physics
  16791. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16792. serializationObject.physicsMass = mesh.getPhysicsMass();
  16793. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16794. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16795. switch (mesh.getPhysicsImpostor()) {
  16796. case BABYLON.PhysicsEngine.BoxImpostor:
  16797. serializationObject.physicsImpostor = 1;
  16798. break;
  16799. case BABYLON.PhysicsEngine.SphereImpostor:
  16800. serializationObject.physicsImpostor = 2;
  16801. break;
  16802. }
  16803. }
  16804. // Instances
  16805. serializationObject.instances = [];
  16806. for (var index = 0; index < mesh.instances.length; index++) {
  16807. var instance = mesh.instances[index];
  16808. var serializationInstance = {
  16809. name: instance.name,
  16810. position: instance.position,
  16811. rotation: instance.rotation,
  16812. rotationQuaternion: instance.rotationQuaternion,
  16813. scaling: instance.scaling
  16814. };
  16815. serializationObject.instances.push(serializationInstance);
  16816. // Animations
  16817. appendAnimations(instance, serializationInstance);
  16818. }
  16819. // Animations
  16820. appendAnimations(mesh, serializationObject);
  16821. // Layer mask
  16822. serializationObject.layerMask = mesh.layerMask;
  16823. return serializationObject;
  16824. };
  16825. var SceneSerializer = (function () {
  16826. function SceneSerializer() {
  16827. }
  16828. SceneSerializer.Serialize = function (scene) {
  16829. var serializationObject = {};
  16830. // Scene
  16831. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16832. serializationObject.autoClear = scene.autoClear;
  16833. serializationObject.clearColor = scene.clearColor.asArray();
  16834. serializationObject.ambientColor = scene.ambientColor.asArray();
  16835. serializationObject.gravity = scene.gravity.asArray();
  16836. // Fog
  16837. if (scene.fogMode && scene.fogMode !== 0) {
  16838. serializationObject.fogMode = scene.fogMode;
  16839. serializationObject.fogColor = scene.fogColor.asArray();
  16840. serializationObject.fogStart = scene.fogStart;
  16841. serializationObject.fogEnd = scene.fogEnd;
  16842. serializationObject.fogDensity = scene.fogDensity;
  16843. }
  16844. // Lights
  16845. serializationObject.lights = [];
  16846. for (var index = 0; index < scene.lights.length; index++) {
  16847. var light = scene.lights[index];
  16848. serializationObject.lights.push(serializeLight(light));
  16849. }
  16850. // Cameras
  16851. serializationObject.cameras = [];
  16852. for (index = 0; index < scene.cameras.length; index++) {
  16853. var camera = scene.cameras[index];
  16854. if (camera instanceof BABYLON.FreeCamera) {
  16855. serializationObject.cameras.push(serializeCamera(camera));
  16856. }
  16857. }
  16858. if (scene.activeCamera) {
  16859. serializationObject.activeCameraID = scene.activeCamera.id;
  16860. }
  16861. // Materials
  16862. serializationObject.materials = [];
  16863. serializationObject.multiMaterials = [];
  16864. for (index = 0; index < scene.materials.length; index++) {
  16865. var material = scene.materials[index];
  16866. if (material instanceof BABYLON.StandardMaterial) {
  16867. serializationObject.materials.push(serializeMaterial(material));
  16868. } else if (material instanceof BABYLON.MultiMaterial) {
  16869. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16870. }
  16871. }
  16872. // Skeletons
  16873. serializationObject.skeletons = [];
  16874. for (index = 0; index < scene.skeletons.length; index++) {
  16875. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16876. }
  16877. // Geometries
  16878. serializationObject.geometries = {};
  16879. serializationObject.geometries.boxes = [];
  16880. serializationObject.geometries.spheres = [];
  16881. serializationObject.geometries.cylinders = [];
  16882. serializationObject.geometries.toruses = [];
  16883. serializationObject.geometries.grounds = [];
  16884. serializationObject.geometries.planes = [];
  16885. serializationObject.geometries.torusKnots = [];
  16886. serializationObject.geometries.vertexData = [];
  16887. serializedGeometries = [];
  16888. var geometries = scene.getGeometries();
  16889. for (var index = 0; index < geometries.length; index++) {
  16890. var geometry = geometries[index];
  16891. if (geometry.isReady()) {
  16892. serializeGeometry(geometry, serializationObject.geometries);
  16893. }
  16894. }
  16895. // Meshes
  16896. serializationObject.meshes = [];
  16897. for (index = 0; index < scene.meshes.length; index++) {
  16898. var abstractMesh = scene.meshes[index];
  16899. if (abstractMesh instanceof BABYLON.Mesh) {
  16900. var mesh = abstractMesh;
  16901. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16902. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16903. }
  16904. }
  16905. }
  16906. // Particles Systems
  16907. serializationObject.particleSystems = [];
  16908. for (index = 0; index < scene.particleSystems.length; index++) {
  16909. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16910. }
  16911. // Lens flares
  16912. serializationObject.lensFlareSystems = [];
  16913. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16914. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16915. }
  16916. // Shadows
  16917. serializationObject.shadowGenerators = [];
  16918. for (index = 0; index < scene.lights.length; index++) {
  16919. light = scene.lights[index];
  16920. if (light.getShadowGenerator()) {
  16921. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16922. }
  16923. }
  16924. return serializationObject;
  16925. };
  16926. return SceneSerializer;
  16927. })();
  16928. BABYLON.SceneSerializer = SceneSerializer;
  16929. })(BABYLON || (BABYLON = {}));
  16930. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16931. var BABYLON;
  16932. (function (BABYLON) {
  16933. var SceneLoader = (function () {
  16934. function SceneLoader() {
  16935. }
  16936. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16937. get: function () {
  16938. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16939. },
  16940. set: function (value) {
  16941. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16947. get: function () {
  16948. return SceneLoader._ShowLoadingScreen;
  16949. },
  16950. set: function (value) {
  16951. SceneLoader._ShowLoadingScreen = value;
  16952. },
  16953. enumerable: true,
  16954. configurable: true
  16955. });
  16956. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16957. var dotPosition = sceneFilename.lastIndexOf(".");
  16958. var queryStringPosition = sceneFilename.indexOf("?");
  16959. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16960. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16961. var plugin = this._registeredPlugins[index];
  16962. if (plugin.extensions.indexOf(extension) !== -1) {
  16963. return plugin;
  16964. }
  16965. }
  16966. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16967. };
  16968. // Public functions
  16969. SceneLoader.RegisterPlugin = function (plugin) {
  16970. plugin.extensions = plugin.extensions.toLowerCase();
  16971. SceneLoader._registeredPlugins.push(plugin);
  16972. };
  16973. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16974. var manifestChecked = function (success) {
  16975. scene.database = database;
  16976. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16977. var importMeshFromData = function (data) {
  16978. var meshes = [];
  16979. var particleSystems = [];
  16980. var skeletons = [];
  16981. try {
  16982. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16983. if (onerror) {
  16984. onerror(scene, 'unable to load the scene');
  16985. }
  16986. return;
  16987. }
  16988. } catch (e) {
  16989. if (onerror) {
  16990. onerror(scene, e);
  16991. }
  16992. return;
  16993. }
  16994. if (onsuccess) {
  16995. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16996. onsuccess(meshes, particleSystems, skeletons);
  16997. }
  16998. };
  16999. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17000. // Direct load
  17001. importMeshFromData(sceneFilename.substr(5));
  17002. return;
  17003. }
  17004. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17005. importMeshFromData(data);
  17006. }, progressCallBack, database);
  17007. };
  17008. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17009. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17010. };
  17011. /**
  17012. * Load a scene
  17013. * @param rootUrl a string that defines the root url for scene and resources
  17014. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17015. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17016. */
  17017. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17018. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17019. };
  17020. /**
  17021. * Append a scene
  17022. * @param rootUrl a string that defines the root url for scene and resources
  17023. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17024. * @param scene is the instance of BABYLON.Scene to append to
  17025. */
  17026. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17027. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17028. var database;
  17029. if (SceneLoader.ShowLoadingScreen) {
  17030. scene.getEngine().displayLoadingUI();
  17031. }
  17032. var loadSceneFromData = function (data) {
  17033. scene.database = database;
  17034. if (!plugin.load(scene, data, rootUrl)) {
  17035. if (onerror) {
  17036. onerror(scene);
  17037. }
  17038. scene.getEngine().hideLoadingUI();
  17039. return;
  17040. }
  17041. if (onsuccess) {
  17042. onsuccess(scene);
  17043. }
  17044. if (SceneLoader.ShowLoadingScreen) {
  17045. scene.executeWhenReady(function () {
  17046. scene.getEngine().hideLoadingUI();
  17047. });
  17048. }
  17049. };
  17050. var manifestChecked = function (success) {
  17051. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17052. };
  17053. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17054. // Direct load
  17055. loadSceneFromData(sceneFilename.substr(5));
  17056. return;
  17057. }
  17058. if (rootUrl.indexOf("file:") === -1) {
  17059. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17060. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17061. } else {
  17062. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17063. }
  17064. };
  17065. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17066. SceneLoader._ShowLoadingScreen = true;
  17067. SceneLoader._registeredPlugins = new Array();
  17068. return SceneLoader;
  17069. })();
  17070. BABYLON.SceneLoader = SceneLoader;
  17071. ;
  17072. })(BABYLON || (BABYLON = {}));
  17073. //# sourceMappingURL=babylon.sceneLoader.js.map
  17074. var BABYLON;
  17075. (function (BABYLON) {
  17076. (function (Internals) {
  17077. var checkColors4 = function (colors, count) {
  17078. // Check if color3 was used
  17079. if (colors.length === count * 3) {
  17080. var colors4 = [];
  17081. for (var index = 0; index < colors.length; index += 3) {
  17082. var newIndex = (index / 3) * 4;
  17083. colors4[newIndex] = colors[index];
  17084. colors4[newIndex + 1] = colors[index + 1];
  17085. colors4[newIndex + 2] = colors[index + 2];
  17086. colors4[newIndex + 3] = 1.0;
  17087. }
  17088. return colors4;
  17089. }
  17090. return colors;
  17091. };
  17092. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17093. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17094. texture.name = parsedTexture.name;
  17095. texture.hasAlpha = parsedTexture.hasAlpha;
  17096. texture.level = parsedTexture.level;
  17097. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17098. return texture;
  17099. };
  17100. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17101. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17102. return null;
  17103. }
  17104. if (parsedTexture.isCube) {
  17105. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17106. }
  17107. var texture;
  17108. if (parsedTexture.mirrorPlane) {
  17109. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17110. texture._waitingRenderList = parsedTexture.renderList;
  17111. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17112. } else if (parsedTexture.isRenderTarget) {
  17113. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17114. texture._waitingRenderList = parsedTexture.renderList;
  17115. } else {
  17116. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17117. }
  17118. texture.name = parsedTexture.name;
  17119. texture.hasAlpha = parsedTexture.hasAlpha;
  17120. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17121. texture.level = parsedTexture.level;
  17122. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17123. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17124. texture.uOffset = parsedTexture.uOffset;
  17125. texture.vOffset = parsedTexture.vOffset;
  17126. texture.uScale = parsedTexture.uScale;
  17127. texture.vScale = parsedTexture.vScale;
  17128. texture.uAng = parsedTexture.uAng;
  17129. texture.vAng = parsedTexture.vAng;
  17130. texture.wAng = parsedTexture.wAng;
  17131. texture.wrapU = parsedTexture.wrapU;
  17132. texture.wrapV = parsedTexture.wrapV;
  17133. // Animations
  17134. if (parsedTexture.animations) {
  17135. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17136. var parsedAnimation = parsedTexture.animations[animationIndex];
  17137. texture.animations.push(parseAnimation(parsedAnimation));
  17138. }
  17139. }
  17140. return texture;
  17141. };
  17142. var parseSkeleton = function (parsedSkeleton, scene) {
  17143. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17144. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17145. var parsedBone = parsedSkeleton.bones[index];
  17146. var parentBone = null;
  17147. if (parsedBone.parentBoneIndex > -1) {
  17148. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17149. }
  17150. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17151. if (parsedBone.animation) {
  17152. bone.animations.push(parseAnimation(parsedBone.animation));
  17153. }
  17154. }
  17155. return skeleton;
  17156. };
  17157. var parseFresnelParameters = function (parsedFresnelParameters) {
  17158. var fresnelParameters = new BABYLON.FresnelParameters();
  17159. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17160. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17161. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17162. fresnelParameters.bias = parsedFresnelParameters.bias;
  17163. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17164. return fresnelParameters;
  17165. };
  17166. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17167. var material;
  17168. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17169. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17170. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17171. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17172. material.specularPower = parsedMaterial.specularPower;
  17173. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17174. material.alpha = parsedMaterial.alpha;
  17175. material.id = parsedMaterial.id;
  17176. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17177. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17178. material.wireframe = parsedMaterial.wireframe;
  17179. if (parsedMaterial.diffuseTexture) {
  17180. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17181. }
  17182. if (parsedMaterial.diffuseFresnelParameters) {
  17183. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17184. }
  17185. if (parsedMaterial.ambientTexture) {
  17186. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17187. }
  17188. if (parsedMaterial.opacityTexture) {
  17189. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17190. }
  17191. if (parsedMaterial.opacityFresnelParameters) {
  17192. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17193. }
  17194. if (parsedMaterial.reflectionTexture) {
  17195. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17196. }
  17197. if (parsedMaterial.reflectionFresnelParameters) {
  17198. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17199. }
  17200. if (parsedMaterial.emissiveTexture) {
  17201. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17202. }
  17203. if (parsedMaterial.emissiveFresnelParameters) {
  17204. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17205. }
  17206. if (parsedMaterial.specularTexture) {
  17207. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17208. }
  17209. if (parsedMaterial.bumpTexture) {
  17210. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17211. }
  17212. return material;
  17213. };
  17214. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17215. for (var index = 0; index < parsedData.materials.length; index++) {
  17216. var parsedMaterial = parsedData.materials[index];
  17217. if (parsedMaterial.id === id) {
  17218. return parseMaterial(parsedMaterial, scene, rootUrl);
  17219. }
  17220. }
  17221. return null;
  17222. };
  17223. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17224. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17225. multiMaterial.id = parsedMultiMaterial.id;
  17226. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17227. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17228. var subMatId = parsedMultiMaterial.materials[matIndex];
  17229. if (subMatId) {
  17230. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17231. } else {
  17232. multiMaterial.subMaterials.push(null);
  17233. }
  17234. }
  17235. return multiMaterial;
  17236. };
  17237. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17238. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17239. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17240. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17241. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17242. var parsedFlare = parsedLensFlareSystem.flares[index];
  17243. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17244. }
  17245. return lensFlareSystem;
  17246. };
  17247. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17248. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17249. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17250. if (parsedParticleSystem.textureName) {
  17251. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17252. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17253. }
  17254. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17255. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17256. particleSystem.minSize = parsedParticleSystem.minSize;
  17257. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17258. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17259. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17260. particleSystem.emitter = emitter;
  17261. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17262. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17263. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17264. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17265. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17266. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17267. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17268. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17269. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17270. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17271. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17272. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17273. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17274. particleSystem.start();
  17275. return particleSystem;
  17276. };
  17277. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17278. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17279. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17280. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17281. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17282. shadowGenerator.getShadowMap().renderList.push(mesh);
  17283. }
  17284. if (parsedShadowGenerator.usePoissonSampling) {
  17285. shadowGenerator.usePoissonSampling = true;
  17286. } else {
  17287. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17288. }
  17289. return shadowGenerator;
  17290. };
  17291. var parseAnimation = function (parsedAnimation) {
  17292. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17293. var dataType = parsedAnimation.dataType;
  17294. var keys = [];
  17295. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17296. var key = parsedAnimation.keys[index];
  17297. var data;
  17298. switch (dataType) {
  17299. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17300. data = key.values[0];
  17301. break;
  17302. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17303. data = BABYLON.Quaternion.FromArray(key.values);
  17304. break;
  17305. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17306. data = BABYLON.Matrix.FromArray(key.values);
  17307. break;
  17308. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17309. default:
  17310. data = BABYLON.Vector3.FromArray(key.values);
  17311. break;
  17312. }
  17313. keys.push({
  17314. frame: key.frame,
  17315. value: data
  17316. });
  17317. }
  17318. animation.setKeys(keys);
  17319. return animation;
  17320. };
  17321. var parseLight = function (parsedLight, scene) {
  17322. var light;
  17323. switch (parsedLight.type) {
  17324. case 0:
  17325. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17326. break;
  17327. case 1:
  17328. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17329. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17330. break;
  17331. case 2:
  17332. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17333. break;
  17334. case 3:
  17335. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17336. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17337. break;
  17338. }
  17339. light.id = parsedLight.id;
  17340. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17341. if (parsedLight.intensity !== undefined) {
  17342. light.intensity = parsedLight.intensity;
  17343. }
  17344. if (parsedLight.range) {
  17345. light.range = parsedLight.range;
  17346. }
  17347. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17348. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17349. if (parsedLight.excludedMeshesIds) {
  17350. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17351. }
  17352. // Parent
  17353. if (parsedLight.parentId) {
  17354. light._waitingParentId = parsedLight.parentId;
  17355. }
  17356. if (parsedLight.includedOnlyMeshesIds) {
  17357. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17358. }
  17359. // Animations
  17360. if (parsedLight.animations) {
  17361. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17362. var parsedAnimation = parsedLight.animations[animationIndex];
  17363. light.animations.push(parseAnimation(parsedAnimation));
  17364. }
  17365. }
  17366. if (parsedLight.autoAnimate) {
  17367. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17368. }
  17369. };
  17370. var parseCamera = function (parsedCamera, scene) {
  17371. var camera;
  17372. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17373. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17374. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17375. var alpha = parsedCamera.alpha;
  17376. var beta = parsedCamera.beta;
  17377. var radius = parsedCamera.radius;
  17378. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17379. var eye_space = parsedCamera.eye_space;
  17380. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17381. } else {
  17382. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17383. }
  17384. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17385. var eye_space = parsedCamera.eye_space;
  17386. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17387. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17388. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17389. } else if (parsedCamera.type === "FollowCamera") {
  17390. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17391. camera.heightOffset = parsedCamera.heightOffset;
  17392. camera.radius = parsedCamera.radius;
  17393. camera.rotationOffset = parsedCamera.rotationOffset;
  17394. if (lockedTargetMesh)
  17395. camera.target = lockedTargetMesh;
  17396. } else if (parsedCamera.type === "GamepadCamera") {
  17397. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17398. } else if (parsedCamera.type === "OculusCamera") {
  17399. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17400. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17401. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17402. } else if (parsedCamera.type === "TouchCamera") {
  17403. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17404. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17405. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17406. } else if (parsedCamera.type === "WebVRCamera") {
  17407. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17408. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17409. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17410. } else {
  17411. // Free Camera is the default value
  17412. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17413. }
  17414. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17415. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17416. camera.lockedTarget = lockedTargetMesh;
  17417. }
  17418. camera.id = parsedCamera.id;
  17419. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17420. // Parent
  17421. if (parsedCamera.parentId) {
  17422. camera._waitingParentId = parsedCamera.parentId;
  17423. }
  17424. // Target
  17425. if (parsedCamera.target) {
  17426. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17427. } else {
  17428. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17429. }
  17430. camera.fov = parsedCamera.fov;
  17431. camera.minZ = parsedCamera.minZ;
  17432. camera.maxZ = parsedCamera.maxZ;
  17433. camera.speed = parsedCamera.speed;
  17434. camera.inertia = parsedCamera.inertia;
  17435. camera.checkCollisions = parsedCamera.checkCollisions;
  17436. camera.applyGravity = parsedCamera.applyGravity;
  17437. if (parsedCamera.ellipsoid) {
  17438. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17439. }
  17440. // Animations
  17441. if (parsedCamera.animations) {
  17442. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17443. var parsedAnimation = parsedCamera.animations[animationIndex];
  17444. camera.animations.push(parseAnimation(parsedAnimation));
  17445. }
  17446. }
  17447. if (parsedCamera.autoAnimate) {
  17448. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17449. }
  17450. // Layer Mask
  17451. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17452. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17453. } else {
  17454. camera.layerMask = 0xFFFFFFFF;
  17455. }
  17456. return camera;
  17457. };
  17458. var parseGeometry = function (parsedGeometry, scene) {
  17459. var id = parsedGeometry.id;
  17460. return scene.getGeometryByID(id);
  17461. };
  17462. var parseBox = function (parsedBox, scene) {
  17463. if (parseGeometry(parsedBox, scene)) {
  17464. return null;
  17465. }
  17466. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17467. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17468. scene.pushGeometry(box, true);
  17469. return box;
  17470. };
  17471. var parseSphere = function (parsedSphere, scene) {
  17472. if (parseGeometry(parsedSphere, scene)) {
  17473. return null;
  17474. }
  17475. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17476. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17477. scene.pushGeometry(sphere, true);
  17478. return sphere;
  17479. };
  17480. var parseCylinder = function (parsedCylinder, scene) {
  17481. if (parseGeometry(parsedCylinder, scene)) {
  17482. return null;
  17483. }
  17484. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17485. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17486. scene.pushGeometry(cylinder, true);
  17487. return cylinder;
  17488. };
  17489. var parseTorus = function (parsedTorus, scene) {
  17490. if (parseGeometry(parsedTorus, scene)) {
  17491. return null;
  17492. }
  17493. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17494. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17495. scene.pushGeometry(torus, true);
  17496. return torus;
  17497. };
  17498. var parseGround = function (parsedGround, scene) {
  17499. if (parseGeometry(parsedGround, scene)) {
  17500. return null;
  17501. }
  17502. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17503. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17504. scene.pushGeometry(ground, true);
  17505. return ground;
  17506. };
  17507. var parsePlane = function (parsedPlane, scene) {
  17508. if (parseGeometry(parsedPlane, scene)) {
  17509. return null;
  17510. }
  17511. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17512. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17513. scene.pushGeometry(plane, true);
  17514. return plane;
  17515. };
  17516. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17517. if (parseGeometry(parsedTorusKnot, scene)) {
  17518. return null;
  17519. }
  17520. 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);
  17521. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17522. scene.pushGeometry(torusKnot, true);
  17523. return torusKnot;
  17524. };
  17525. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17526. if (parseGeometry(parsedVertexData, scene)) {
  17527. return null;
  17528. }
  17529. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17530. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17531. if (parsedVertexData.delayLoadingFile) {
  17532. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17533. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17534. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17535. geometry._delayInfo = [];
  17536. if (parsedVertexData.hasUVs) {
  17537. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17538. }
  17539. if (parsedVertexData.hasUVs2) {
  17540. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17541. }
  17542. if (parsedVertexData.hasColors) {
  17543. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17544. }
  17545. if (parsedVertexData.hasMatricesIndices) {
  17546. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17547. }
  17548. if (parsedVertexData.hasMatricesWeights) {
  17549. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17550. }
  17551. geometry._delayLoadingFunction = importVertexData;
  17552. } else {
  17553. importVertexData(parsedVertexData, geometry);
  17554. }
  17555. scene.pushGeometry(geometry, true);
  17556. return geometry;
  17557. };
  17558. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17559. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17560. mesh.id = parsedMesh.id;
  17561. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17562. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17563. if (parsedMesh.rotationQuaternion) {
  17564. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17565. } else if (parsedMesh.rotation) {
  17566. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17567. }
  17568. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17569. if (parsedMesh.localMatrix) {
  17570. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17571. } else if (parsedMesh.pivotMatrix) {
  17572. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17573. }
  17574. mesh.setEnabled(parsedMesh.isEnabled);
  17575. mesh.isVisible = parsedMesh.isVisible;
  17576. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17577. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17578. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17579. if (parsedMesh.applyFog !== undefined) {
  17580. mesh.applyFog = parsedMesh.applyFog;
  17581. }
  17582. if (parsedMesh.pickable !== undefined) {
  17583. mesh.isPickable = parsedMesh.pickable;
  17584. }
  17585. if (parsedMesh.alphaIndex !== undefined) {
  17586. mesh.alphaIndex = parsedMesh.alphaIndex;
  17587. }
  17588. mesh.receiveShadows = parsedMesh.receiveShadows;
  17589. mesh.billboardMode = parsedMesh.billboardMode;
  17590. if (parsedMesh.visibility !== undefined) {
  17591. mesh.visibility = parsedMesh.visibility;
  17592. }
  17593. mesh.checkCollisions = parsedMesh.checkCollisions;
  17594. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17595. // Parent
  17596. if (parsedMesh.parentId) {
  17597. mesh._waitingParentId = parsedMesh.parentId;
  17598. }
  17599. // Geometry
  17600. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17601. if (parsedMesh.delayLoadingFile) {
  17602. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17603. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17604. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17605. if (parsedMesh._binaryInfo) {
  17606. mesh._binaryInfo = parsedMesh._binaryInfo;
  17607. }
  17608. mesh._delayInfo = [];
  17609. if (parsedMesh.hasUVs) {
  17610. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17611. }
  17612. if (parsedMesh.hasUVs2) {
  17613. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17614. }
  17615. if (parsedMesh.hasColors) {
  17616. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17617. }
  17618. if (parsedMesh.hasMatricesIndices) {
  17619. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17620. }
  17621. if (parsedMesh.hasMatricesWeights) {
  17622. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17623. }
  17624. mesh._delayLoadingFunction = importGeometry;
  17625. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17626. mesh._checkDelayState();
  17627. }
  17628. } else {
  17629. importGeometry(parsedMesh, mesh);
  17630. }
  17631. // Material
  17632. if (parsedMesh.materialId) {
  17633. mesh.setMaterialByID(parsedMesh.materialId);
  17634. } else {
  17635. mesh.material = null;
  17636. }
  17637. // Skeleton
  17638. if (parsedMesh.skeletonId > -1) {
  17639. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17640. }
  17641. // Physics
  17642. if (parsedMesh.physicsImpostor) {
  17643. if (!scene.isPhysicsEnabled()) {
  17644. scene.enablePhysics();
  17645. }
  17646. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17647. }
  17648. // Animations
  17649. if (parsedMesh.animations) {
  17650. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17651. var parsedAnimation = parsedMesh.animations[animationIndex];
  17652. mesh.animations.push(parseAnimation(parsedAnimation));
  17653. }
  17654. }
  17655. if (parsedMesh.autoAnimate) {
  17656. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17657. }
  17658. // Layer Mask
  17659. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17660. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17661. } else {
  17662. mesh.layerMask = 0xFFFFFFFF;
  17663. }
  17664. // Instances
  17665. if (parsedMesh.instances) {
  17666. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17667. var parsedInstance = parsedMesh.instances[index];
  17668. var instance = mesh.createInstance(parsedInstance.name);
  17669. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17670. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17671. if (parsedInstance.rotationQuaternion) {
  17672. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17673. } else if (parsedInstance.rotation) {
  17674. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17675. }
  17676. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17677. instance.checkCollisions = mesh.checkCollisions;
  17678. if (parsedMesh.animations) {
  17679. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17680. parsedAnimation = parsedMesh.animations[animationIndex];
  17681. instance.animations.push(parseAnimation(parsedAnimation));
  17682. }
  17683. }
  17684. }
  17685. }
  17686. return mesh;
  17687. };
  17688. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17689. names = (names instanceof Array) ? names : [names];
  17690. for (var i in names) {
  17691. if (mesh.name === names[i]) {
  17692. hierarchyIds.push(mesh.id);
  17693. return true;
  17694. }
  17695. }
  17696. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17697. hierarchyIds.push(mesh.id);
  17698. return true;
  17699. }
  17700. return false;
  17701. };
  17702. var importVertexData = function (parsedVertexData, geometry) {
  17703. var vertexData = new BABYLON.VertexData();
  17704. // positions
  17705. var positions = parsedVertexData.positions;
  17706. if (positions) {
  17707. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17708. }
  17709. // normals
  17710. var normals = parsedVertexData.normals;
  17711. if (normals) {
  17712. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17713. }
  17714. // uvs
  17715. var uvs = parsedVertexData.uvs;
  17716. if (uvs) {
  17717. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17718. }
  17719. // uv2s
  17720. var uv2s = parsedVertexData.uv2s;
  17721. if (uv2s) {
  17722. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17723. }
  17724. // colors
  17725. var colors = parsedVertexData.colors;
  17726. if (colors) {
  17727. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17728. }
  17729. // matricesIndices
  17730. var matricesIndices = parsedVertexData.matricesIndices;
  17731. if (matricesIndices) {
  17732. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17733. }
  17734. // matricesWeights
  17735. var matricesWeights = parsedVertexData.matricesWeights;
  17736. if (matricesWeights) {
  17737. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17738. }
  17739. // indices
  17740. var indices = parsedVertexData.indices;
  17741. if (indices) {
  17742. vertexData.indices = indices;
  17743. }
  17744. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17745. };
  17746. var importGeometry = function (parsedGeometry, mesh) {
  17747. var scene = mesh.getScene();
  17748. // Geometry
  17749. var geometryId = parsedGeometry.geometryId;
  17750. if (geometryId) {
  17751. var geometry = scene.getGeometryByID(geometryId);
  17752. if (geometry) {
  17753. geometry.applyToMesh(mesh);
  17754. }
  17755. } else if (parsedGeometry instanceof ArrayBuffer) {
  17756. var binaryInfo = mesh._binaryInfo;
  17757. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17758. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17759. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17760. }
  17761. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17762. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17763. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17764. }
  17765. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17766. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17767. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17768. }
  17769. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17770. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17771. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17772. }
  17773. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17774. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17775. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17776. }
  17777. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17778. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17779. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17780. }
  17781. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17782. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17783. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17784. }
  17785. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17786. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17787. mesh.setIndices(indicesData);
  17788. }
  17789. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17790. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17791. mesh.subMeshes = [];
  17792. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17793. var materialIndex = subMeshesData[(i * 5) + 0];
  17794. var verticesStart = subMeshesData[(i * 5) + 1];
  17795. var verticesCount = subMeshesData[(i * 5) + 2];
  17796. var indexStart = subMeshesData[(i * 5) + 3];
  17797. var indexCount = subMeshesData[(i * 5) + 4];
  17798. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17799. }
  17800. }
  17801. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17802. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17803. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17804. if (parsedGeometry.uvs) {
  17805. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17806. }
  17807. if (parsedGeometry.uvs2) {
  17808. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17809. }
  17810. if (parsedGeometry.colors) {
  17811. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17812. }
  17813. if (parsedGeometry.matricesIndices) {
  17814. if (!parsedGeometry.matricesIndices._isExpanded) {
  17815. var floatIndices = [];
  17816. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17817. var matricesIndex = parsedGeometry.matricesIndices[i];
  17818. floatIndices.push(matricesIndex & 0x000000FF);
  17819. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17820. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17821. floatIndices.push(matricesIndex >> 24);
  17822. }
  17823. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17824. } else {
  17825. delete parsedGeometry.matricesIndices._isExpanded;
  17826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17827. }
  17828. }
  17829. if (parsedGeometry.matricesWeights) {
  17830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17831. }
  17832. mesh.setIndices(parsedGeometry.indices);
  17833. // SubMeshes
  17834. if (parsedGeometry.subMeshes) {
  17835. mesh.subMeshes = [];
  17836. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17837. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17838. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17839. }
  17840. }
  17841. }
  17842. // Flat shading
  17843. if (mesh._shouldGenerateFlatShading) {
  17844. mesh.convertToFlatShadedMesh();
  17845. delete mesh._shouldGenerateFlatShading;
  17846. }
  17847. // Update
  17848. mesh.computeWorldMatrix(true);
  17849. // Octree
  17850. if (scene._selectionOctree) {
  17851. scene._selectionOctree.addMesh(mesh);
  17852. }
  17853. };
  17854. BABYLON.SceneLoader.RegisterPlugin({
  17855. extensions: ".babylon",
  17856. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17857. var parsedData = JSON.parse(data);
  17858. var loadedSkeletonsIds = [];
  17859. var loadedMaterialsIds = [];
  17860. var hierarchyIds = [];
  17861. for (var index = 0; index < parsedData.meshes.length; index++) {
  17862. var parsedMesh = parsedData.meshes[index];
  17863. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17864. if (meshesNames instanceof Array) {
  17865. // Remove found mesh name from list.
  17866. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17867. }
  17868. // Material ?
  17869. if (parsedMesh.materialId) {
  17870. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17871. if (!materialFound) {
  17872. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17873. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17874. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17875. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17876. var subMatId = parsedMultiMaterial.materials[matIndex];
  17877. loadedMaterialsIds.push(subMatId);
  17878. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17879. }
  17880. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17881. parseMultiMaterial(parsedMultiMaterial, scene);
  17882. materialFound = true;
  17883. break;
  17884. }
  17885. }
  17886. }
  17887. if (!materialFound) {
  17888. loadedMaterialsIds.push(parsedMesh.materialId);
  17889. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17890. }
  17891. }
  17892. // Skeleton ?
  17893. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17894. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17895. if (!skeletonAlreadyLoaded) {
  17896. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17897. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17898. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17899. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17900. loadedSkeletonsIds.push(parsedSkeleton.id);
  17901. }
  17902. }
  17903. }
  17904. }
  17905. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17906. meshes.push(mesh);
  17907. }
  17908. }
  17909. for (index = 0; index < scene.meshes.length; index++) {
  17910. var currentMesh = scene.meshes[index];
  17911. if (currentMesh._waitingParentId) {
  17912. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17913. currentMesh._waitingParentId = undefined;
  17914. }
  17915. }
  17916. // Particles
  17917. if (parsedData.particleSystems) {
  17918. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17919. var parsedParticleSystem = parsedData.particleSystems[index];
  17920. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17921. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17922. }
  17923. }
  17924. }
  17925. return true;
  17926. },
  17927. load: function (scene, data, rootUrl) {
  17928. var parsedData = JSON.parse(data);
  17929. // Scene
  17930. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17931. scene.autoClear = parsedData.autoClear;
  17932. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17933. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17934. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17935. // Fog
  17936. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17937. scene.fogMode = parsedData.fogMode;
  17938. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17939. scene.fogStart = parsedData.fogStart;
  17940. scene.fogEnd = parsedData.fogEnd;
  17941. scene.fogDensity = parsedData.fogDensity;
  17942. }
  17943. for (var index = 0; index < parsedData.lights.length; index++) {
  17944. var parsedLight = parsedData.lights[index];
  17945. parseLight(parsedLight, scene);
  17946. }
  17947. // Materials
  17948. if (parsedData.materials) {
  17949. for (index = 0; index < parsedData.materials.length; index++) {
  17950. var parsedMaterial = parsedData.materials[index];
  17951. parseMaterial(parsedMaterial, scene, rootUrl);
  17952. }
  17953. }
  17954. if (parsedData.multiMaterials) {
  17955. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17956. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17957. parseMultiMaterial(parsedMultiMaterial, scene);
  17958. }
  17959. }
  17960. // Skeletons
  17961. if (parsedData.skeletons) {
  17962. for (index = 0; index < parsedData.skeletons.length; index++) {
  17963. var parsedSkeleton = parsedData.skeletons[index];
  17964. parseSkeleton(parsedSkeleton, scene);
  17965. }
  17966. }
  17967. // Geometries
  17968. var geometries = parsedData.geometries;
  17969. if (geometries) {
  17970. // Boxes
  17971. var boxes = geometries.boxes;
  17972. if (boxes) {
  17973. for (index = 0; index < boxes.length; index++) {
  17974. var parsedBox = boxes[index];
  17975. parseBox(parsedBox, scene);
  17976. }
  17977. }
  17978. // Spheres
  17979. var spheres = geometries.spheres;
  17980. if (spheres) {
  17981. for (index = 0; index < spheres.length; index++) {
  17982. var parsedSphere = spheres[index];
  17983. parseSphere(parsedSphere, scene);
  17984. }
  17985. }
  17986. // Cylinders
  17987. var cylinders = geometries.cylinders;
  17988. if (cylinders) {
  17989. for (index = 0; index < cylinders.length; index++) {
  17990. var parsedCylinder = cylinders[index];
  17991. parseCylinder(parsedCylinder, scene);
  17992. }
  17993. }
  17994. // Toruses
  17995. var toruses = geometries.toruses;
  17996. if (toruses) {
  17997. for (index = 0; index < toruses.length; index++) {
  17998. var parsedTorus = toruses[index];
  17999. parseTorus(parsedTorus, scene);
  18000. }
  18001. }
  18002. // Grounds
  18003. var grounds = geometries.grounds;
  18004. if (grounds) {
  18005. for (index = 0; index < grounds.length; index++) {
  18006. var parsedGround = grounds[index];
  18007. parseGround(parsedGround, scene);
  18008. }
  18009. }
  18010. // Planes
  18011. var planes = geometries.planes;
  18012. if (planes) {
  18013. for (index = 0; index < planes.length; index++) {
  18014. var parsedPlane = planes[index];
  18015. parsePlane(parsedPlane, scene);
  18016. }
  18017. }
  18018. // TorusKnots
  18019. var torusKnots = geometries.torusKnots;
  18020. if (torusKnots) {
  18021. for (index = 0; index < torusKnots.length; index++) {
  18022. var parsedTorusKnot = torusKnots[index];
  18023. parseTorusKnot(parsedTorusKnot, scene);
  18024. }
  18025. }
  18026. // VertexData
  18027. var vertexData = geometries.vertexData;
  18028. if (vertexData) {
  18029. for (index = 0; index < vertexData.length; index++) {
  18030. var parsedVertexData = vertexData[index];
  18031. parseVertexData(parsedVertexData, scene, rootUrl);
  18032. }
  18033. }
  18034. }
  18035. for (index = 0; index < parsedData.meshes.length; index++) {
  18036. var parsedMesh = parsedData.meshes[index];
  18037. parseMesh(parsedMesh, scene, rootUrl);
  18038. }
  18039. for (index = 0; index < parsedData.cameras.length; index++) {
  18040. var parsedCamera = parsedData.cameras[index];
  18041. parseCamera(parsedCamera, scene);
  18042. }
  18043. if (parsedData.activeCameraID) {
  18044. scene.setActiveCameraByID(parsedData.activeCameraID);
  18045. }
  18046. for (index = 0; index < scene.cameras.length; index++) {
  18047. var camera = scene.cameras[index];
  18048. if (camera._waitingParentId) {
  18049. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18050. camera._waitingParentId = undefined;
  18051. }
  18052. }
  18053. for (index = 0; index < scene.lights.length; index++) {
  18054. var light = scene.lights[index];
  18055. if (light._waitingParentId) {
  18056. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18057. light._waitingParentId = undefined;
  18058. }
  18059. }
  18060. for (index = 0; index < scene.meshes.length; index++) {
  18061. var mesh = scene.meshes[index];
  18062. if (mesh._waitingParentId) {
  18063. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18064. mesh._waitingParentId = undefined;
  18065. }
  18066. }
  18067. // Particles Systems
  18068. if (parsedData.particleSystems) {
  18069. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18070. var parsedParticleSystem = parsedData.particleSystems[index];
  18071. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18072. }
  18073. }
  18074. // Lens flares
  18075. if (parsedData.lensFlareSystems) {
  18076. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18077. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18078. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18079. }
  18080. }
  18081. // Shadows
  18082. if (parsedData.shadowGenerators) {
  18083. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18084. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18085. parseShadowGenerator(parsedShadowGenerator, scene);
  18086. }
  18087. }
  18088. // Finish
  18089. return true;
  18090. }
  18091. });
  18092. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18093. var Internals = BABYLON.Internals;
  18094. })(BABYLON || (BABYLON = {}));
  18095. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18096. var BABYLON;
  18097. (function (BABYLON) {
  18098. // Unique ID when we import meshes from Babylon to CSG
  18099. var currentCSGMeshId = 0;
  18100. // # class Vertex
  18101. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18102. // one to provide additional features like texture coordinates and vertex
  18103. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18104. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18105. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18106. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18107. // is not used anywhere else.
  18108. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18109. var Vertex = (function () {
  18110. function Vertex(pos, normal, uv) {
  18111. this.pos = pos;
  18112. this.normal = normal;
  18113. this.uv = uv;
  18114. }
  18115. Vertex.prototype.clone = function () {
  18116. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18117. };
  18118. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18119. // orientation of a polygon is flipped.
  18120. Vertex.prototype.flip = function () {
  18121. this.normal = this.normal.scale(-1);
  18122. };
  18123. // Create a new vertex between this vertex and `other` by linearly
  18124. // interpolating all properties using a parameter of `t`. Subclasses should
  18125. // override this to interpolate additional properties.
  18126. Vertex.prototype.interpolate = function (other, t) {
  18127. 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));
  18128. };
  18129. return Vertex;
  18130. })();
  18131. // # class Plane
  18132. // Represents a plane in 3D space.
  18133. var Plane = (function () {
  18134. function Plane(normal, w) {
  18135. this.normal = normal;
  18136. this.w = w;
  18137. }
  18138. Plane.FromPoints = function (a, b, c) {
  18139. var v0 = c.subtract(a);
  18140. var v1 = b.subtract(a);
  18141. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18142. return null;
  18143. }
  18144. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18145. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18146. };
  18147. Plane.prototype.clone = function () {
  18148. return new Plane(this.normal.clone(), this.w);
  18149. };
  18150. Plane.prototype.flip = function () {
  18151. this.normal.scaleInPlace(-1);
  18152. this.w = -this.w;
  18153. };
  18154. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18155. // fragments in the appropriate lists. Coplanar polygons go into either
  18156. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18157. // respect to this plane. Polygons in front or in back of this plane go into
  18158. // either `front` or `back`.
  18159. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18160. var COPLANAR = 0;
  18161. var FRONT = 1;
  18162. var BACK = 2;
  18163. var SPANNING = 3;
  18164. // Classify each point as well as the entire polygon into one of the above
  18165. // four classes.
  18166. var polygonType = 0;
  18167. var types = [];
  18168. for (var i = 0; i < polygon.vertices.length; i++) {
  18169. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18170. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18171. polygonType |= type;
  18172. types.push(type);
  18173. }
  18174. switch (polygonType) {
  18175. case COPLANAR:
  18176. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18177. break;
  18178. case FRONT:
  18179. front.push(polygon);
  18180. break;
  18181. case BACK:
  18182. back.push(polygon);
  18183. break;
  18184. case SPANNING:
  18185. var f = [], b = [];
  18186. for (i = 0; i < polygon.vertices.length; i++) {
  18187. var j = (i + 1) % polygon.vertices.length;
  18188. var ti = types[i], tj = types[j];
  18189. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18190. if (ti != BACK)
  18191. f.push(vi);
  18192. if (ti != FRONT)
  18193. b.push(ti != BACK ? vi.clone() : vi);
  18194. if ((ti | tj) == SPANNING) {
  18195. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18196. var v = vi.interpolate(vj, t);
  18197. f.push(v);
  18198. b.push(v.clone());
  18199. }
  18200. }
  18201. if (f.length >= 3) {
  18202. var poly = new Polygon(f, polygon.shared);
  18203. if (poly.plane)
  18204. front.push(poly);
  18205. }
  18206. if (b.length >= 3) {
  18207. poly = new Polygon(b, polygon.shared);
  18208. if (poly.plane)
  18209. back.push(poly);
  18210. }
  18211. break;
  18212. }
  18213. };
  18214. Plane.EPSILON = 1e-5;
  18215. return Plane;
  18216. })();
  18217. // # class Polygon
  18218. // Represents a convex polygon. The vertices used to initialize a polygon must
  18219. // be coplanar and form a convex loop.
  18220. //
  18221. // Each convex polygon has a `shared` property, which is shared between all
  18222. // polygons that are clones of each other or were split from the same polygon.
  18223. // This can be used to define per-polygon properties (such as surface color).
  18224. var Polygon = (function () {
  18225. function Polygon(vertices, shared) {
  18226. this.vertices = vertices;
  18227. this.shared = shared;
  18228. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18229. }
  18230. Polygon.prototype.clone = function () {
  18231. var vertices = this.vertices.map(function (v) {
  18232. return v.clone();
  18233. });
  18234. return new Polygon(vertices, this.shared);
  18235. };
  18236. Polygon.prototype.flip = function () {
  18237. this.vertices.reverse().map(function (v) {
  18238. v.flip();
  18239. });
  18240. this.plane.flip();
  18241. };
  18242. return Polygon;
  18243. })();
  18244. // # class Node
  18245. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18246. // by picking a polygon to split along. That polygon (and all other coplanar
  18247. // polygons) are added directly to that node and the other polygons are added to
  18248. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18249. // no distinction between internal and leaf nodes.
  18250. var Node = (function () {
  18251. function Node(polygons) {
  18252. this.plane = null;
  18253. this.front = null;
  18254. this.back = null;
  18255. this.polygons = [];
  18256. if (polygons) {
  18257. this.build(polygons);
  18258. }
  18259. }
  18260. Node.prototype.clone = function () {
  18261. var node = new Node();
  18262. node.plane = this.plane && this.plane.clone();
  18263. node.front = this.front && this.front.clone();
  18264. node.back = this.back && this.back.clone();
  18265. node.polygons = this.polygons.map(function (p) {
  18266. return p.clone();
  18267. });
  18268. return node;
  18269. };
  18270. // Convert solid space to empty space and empty space to solid space.
  18271. Node.prototype.invert = function () {
  18272. for (var i = 0; i < this.polygons.length; i++) {
  18273. this.polygons[i].flip();
  18274. }
  18275. if (this.plane) {
  18276. this.plane.flip();
  18277. }
  18278. if (this.front) {
  18279. this.front.invert();
  18280. }
  18281. if (this.back) {
  18282. this.back.invert();
  18283. }
  18284. var temp = this.front;
  18285. this.front = this.back;
  18286. this.back = temp;
  18287. };
  18288. // Recursively remove all polygons in `polygons` that are inside this BSP
  18289. // tree.
  18290. Node.prototype.clipPolygons = function (polygons) {
  18291. if (!this.plane)
  18292. return polygons.slice();
  18293. var front = [], back = [];
  18294. for (var i = 0; i < polygons.length; i++) {
  18295. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18296. }
  18297. if (this.front) {
  18298. front = this.front.clipPolygons(front);
  18299. }
  18300. if (this.back) {
  18301. back = this.back.clipPolygons(back);
  18302. } else {
  18303. back = [];
  18304. }
  18305. return front.concat(back);
  18306. };
  18307. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18308. // `bsp`.
  18309. Node.prototype.clipTo = function (bsp) {
  18310. this.polygons = bsp.clipPolygons(this.polygons);
  18311. if (this.front)
  18312. this.front.clipTo(bsp);
  18313. if (this.back)
  18314. this.back.clipTo(bsp);
  18315. };
  18316. // Return a list of all polygons in this BSP tree.
  18317. Node.prototype.allPolygons = function () {
  18318. var polygons = this.polygons.slice();
  18319. if (this.front)
  18320. polygons = polygons.concat(this.front.allPolygons());
  18321. if (this.back)
  18322. polygons = polygons.concat(this.back.allPolygons());
  18323. return polygons;
  18324. };
  18325. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18326. // new polygons are filtered down to the bottom of the tree and become new
  18327. // nodes there. Each set of polygons is partitioned using the first polygon
  18328. // (no heuristic is used to pick a good split).
  18329. Node.prototype.build = function (polygons) {
  18330. if (!polygons.length)
  18331. return;
  18332. if (!this.plane)
  18333. this.plane = polygons[0].plane.clone();
  18334. var front = [], back = [];
  18335. for (var i = 0; i < polygons.length; i++) {
  18336. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18337. }
  18338. if (front.length) {
  18339. if (!this.front)
  18340. this.front = new Node();
  18341. this.front.build(front);
  18342. }
  18343. if (back.length) {
  18344. if (!this.back)
  18345. this.back = new Node();
  18346. this.back.build(back);
  18347. }
  18348. };
  18349. return Node;
  18350. })();
  18351. var CSG = (function () {
  18352. function CSG() {
  18353. this.polygons = new Array();
  18354. }
  18355. // Convert BABYLON.Mesh to BABYLON.CSG
  18356. CSG.FromMesh = function (mesh) {
  18357. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18358. if (mesh instanceof BABYLON.Mesh) {
  18359. mesh.computeWorldMatrix(true);
  18360. var matrix = mesh.getWorldMatrix();
  18361. var meshPosition = mesh.position.clone();
  18362. var meshRotation = mesh.rotation.clone();
  18363. var meshScaling = mesh.scaling.clone();
  18364. } else {
  18365. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18366. }
  18367. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18368. var subMeshes = mesh.subMeshes;
  18369. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18370. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18371. vertices = [];
  18372. for (var j = 0; j < 3; j++) {
  18373. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18374. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18375. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18376. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18377. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18378. vertex = new Vertex(position, normal, uv);
  18379. vertices.push(vertex);
  18380. }
  18381. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18382. // To handle the case of degenerated triangle
  18383. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18384. if (polygon.plane)
  18385. polygons.push(polygon);
  18386. }
  18387. }
  18388. var csg = CSG.FromPolygons(polygons);
  18389. csg.matrix = matrix;
  18390. csg.position = meshPosition;
  18391. csg.rotation = meshRotation;
  18392. csg.scaling = meshScaling;
  18393. currentCSGMeshId++;
  18394. return csg;
  18395. };
  18396. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18397. CSG.FromPolygons = function (polygons) {
  18398. var csg = new BABYLON.CSG();
  18399. csg.polygons = polygons;
  18400. return csg;
  18401. };
  18402. CSG.prototype.clone = function () {
  18403. var csg = new BABYLON.CSG();
  18404. csg.polygons = this.polygons.map(function (p) {
  18405. return p.clone();
  18406. });
  18407. csg.copyTransformAttributes(this);
  18408. return csg;
  18409. };
  18410. CSG.prototype.toPolygons = function () {
  18411. return this.polygons;
  18412. };
  18413. CSG.prototype.union = function (csg) {
  18414. var a = new Node(this.clone().polygons);
  18415. var b = new Node(csg.clone().polygons);
  18416. a.clipTo(b);
  18417. b.clipTo(a);
  18418. b.invert();
  18419. b.clipTo(a);
  18420. b.invert();
  18421. a.build(b.allPolygons());
  18422. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18423. };
  18424. CSG.prototype.unionInPlace = function (csg) {
  18425. var a = new Node(this.polygons);
  18426. var b = new Node(csg.polygons);
  18427. a.clipTo(b);
  18428. b.clipTo(a);
  18429. b.invert();
  18430. b.clipTo(a);
  18431. b.invert();
  18432. a.build(b.allPolygons());
  18433. this.polygons = a.allPolygons();
  18434. };
  18435. CSG.prototype.subtract = function (csg) {
  18436. var a = new Node(this.clone().polygons);
  18437. var b = new Node(csg.clone().polygons);
  18438. a.invert();
  18439. a.clipTo(b);
  18440. b.clipTo(a);
  18441. b.invert();
  18442. b.clipTo(a);
  18443. b.invert();
  18444. a.build(b.allPolygons());
  18445. a.invert();
  18446. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18447. };
  18448. CSG.prototype.subtractInPlace = function (csg) {
  18449. var a = new Node(this.polygons);
  18450. var b = new Node(csg.polygons);
  18451. a.invert();
  18452. a.clipTo(b);
  18453. b.clipTo(a);
  18454. b.invert();
  18455. b.clipTo(a);
  18456. b.invert();
  18457. a.build(b.allPolygons());
  18458. a.invert();
  18459. this.polygons = a.allPolygons();
  18460. };
  18461. CSG.prototype.intersect = function (csg) {
  18462. var a = new Node(this.clone().polygons);
  18463. var b = new Node(csg.clone().polygons);
  18464. a.invert();
  18465. b.clipTo(a);
  18466. b.invert();
  18467. a.clipTo(b);
  18468. b.clipTo(a);
  18469. a.build(b.allPolygons());
  18470. a.invert();
  18471. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18472. };
  18473. CSG.prototype.intersectInPlace = function (csg) {
  18474. var a = new Node(this.polygons);
  18475. var b = new Node(csg.polygons);
  18476. a.invert();
  18477. b.clipTo(a);
  18478. b.invert();
  18479. a.clipTo(b);
  18480. b.clipTo(a);
  18481. a.build(b.allPolygons());
  18482. a.invert();
  18483. this.polygons = a.allPolygons();
  18484. };
  18485. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18486. // not modified.
  18487. CSG.prototype.inverse = function () {
  18488. var csg = this.clone();
  18489. csg.inverseInPlace();
  18490. return csg;
  18491. };
  18492. CSG.prototype.inverseInPlace = function () {
  18493. this.polygons.map(function (p) {
  18494. p.flip();
  18495. });
  18496. };
  18497. // This is used to keep meshes transformations so they can be restored
  18498. // when we build back a Babylon Mesh
  18499. // NB : All CSG operations are performed in world coordinates
  18500. CSG.prototype.copyTransformAttributes = function (csg) {
  18501. this.matrix = csg.matrix;
  18502. this.position = csg.position;
  18503. this.rotation = csg.rotation;
  18504. this.scaling = csg.scaling;
  18505. return this;
  18506. };
  18507. // Build Raw mesh from CSG
  18508. // Coordinates here are in world space
  18509. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18510. var matrix = this.matrix.clone();
  18511. matrix.invert();
  18512. 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;
  18513. if (keepSubMeshes) {
  18514. // Sort Polygons, since subMeshes are indices range
  18515. polygons.sort(function (a, b) {
  18516. if (a.shared.meshId === b.shared.meshId) {
  18517. return a.shared.subMeshId - b.shared.subMeshId;
  18518. } else {
  18519. return a.shared.meshId - b.shared.meshId;
  18520. }
  18521. });
  18522. }
  18523. for (var i = 0, il = polygons.length; i < il; i++) {
  18524. polygon = polygons[i];
  18525. // Building SubMeshes
  18526. if (!subMesh_dict[polygon.shared.meshId]) {
  18527. subMesh_dict[polygon.shared.meshId] = {};
  18528. }
  18529. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18530. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18531. indexStart: +Infinity,
  18532. indexEnd: -Infinity,
  18533. materialIndex: polygon.shared.materialIndex
  18534. };
  18535. }
  18536. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18537. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18538. polygonIndices[0] = 0;
  18539. polygonIndices[1] = j - 1;
  18540. polygonIndices[2] = j;
  18541. for (var k = 0; k < 3; k++) {
  18542. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18543. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18544. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18545. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18546. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18547. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18548. // Check if 2 points can be merged
  18549. 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)) {
  18550. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18551. uvs.push(uv.x, uv.y);
  18552. normals.push(normal.x, normal.y, normal.z);
  18553. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18554. }
  18555. indices.push(vertex_idx);
  18556. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18557. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18558. currentIndex++;
  18559. }
  18560. }
  18561. }
  18562. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18563. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18564. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18565. mesh.setIndices(indices);
  18566. if (keepSubMeshes) {
  18567. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18568. var materialIndexOffset = 0, materialMaxIndex;
  18569. mesh.subMeshes.length = 0;
  18570. for (var m in subMesh_dict) {
  18571. materialMaxIndex = -1;
  18572. for (var sm in subMesh_dict[m]) {
  18573. subMesh_obj = subMesh_dict[m][sm];
  18574. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18575. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18576. }
  18577. materialIndexOffset += ++materialMaxIndex;
  18578. }
  18579. }
  18580. return mesh;
  18581. };
  18582. // Build Mesh from CSG taking material and transforms into account
  18583. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18584. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18585. mesh.material = material;
  18586. mesh.position.copyFrom(this.position);
  18587. mesh.rotation.copyFrom(this.rotation);
  18588. mesh.scaling.copyFrom(this.scaling);
  18589. mesh.computeWorldMatrix(true);
  18590. return mesh;
  18591. };
  18592. return CSG;
  18593. })();
  18594. BABYLON.CSG = CSG;
  18595. })(BABYLON || (BABYLON = {}));
  18596. //# sourceMappingURL=babylon.csg.js.map
  18597. var BABYLON;
  18598. (function (BABYLON) {
  18599. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18600. __extends(OculusDistortionCorrectionPostProcess, _super);
  18601. //ANY
  18602. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18603. var _this = this;
  18604. _super.call(this, name, "oculusDistortionCorrection", [
  18605. 'LensCenter',
  18606. 'Scale',
  18607. 'ScaleIn',
  18608. 'HmdWarpParam'
  18609. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18610. this._isRightEye = isRightEye;
  18611. this._distortionFactors = cameraSettings.DistortionK;
  18612. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18613. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18614. this.onSizeChanged = function () {
  18615. _this.aspectRatio = _this.width * .5 / _this.height;
  18616. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18617. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18618. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18619. };
  18620. this.onApply = function (effect) {
  18621. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18622. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18623. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18624. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18625. };
  18626. }
  18627. return OculusDistortionCorrectionPostProcess;
  18628. })(BABYLON.PostProcess);
  18629. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18630. })(BABYLON || (BABYLON = {}));
  18631. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18632. // Mainly based on these 2 articles :
  18633. // 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
  18634. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18635. var BABYLON;
  18636. (function (BABYLON) {
  18637. (function (JoystickAxis) {
  18638. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18639. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18640. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18641. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18642. var JoystickAxis = BABYLON.JoystickAxis;
  18643. var VirtualJoystick = (function () {
  18644. function VirtualJoystick(leftJoystick) {
  18645. var _this = this;
  18646. if (leftJoystick) {
  18647. this._leftJoystick = true;
  18648. } else {
  18649. this._leftJoystick = false;
  18650. }
  18651. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18652. VirtualJoystick._globalJoystickIndex++;
  18653. // By default left & right arrow keys are moving the X
  18654. // and up & down keys are moving the Y
  18655. this._axisTargetedByLeftAndRight = 0 /* X */;
  18656. this._axisTargetedByUpAndDown = 1 /* Y */;
  18657. this.reverseLeftRight = false;
  18658. this.reverseUpDown = false;
  18659. // collections of pointers
  18660. this._touches = new BABYLON.VirtualJoystick.Collection();
  18661. this.deltaPosition = BABYLON.Vector3.Zero();
  18662. this._joystickSensibility = 25;
  18663. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18664. this._rotationSpeed = 25;
  18665. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18666. this._rotateOnAxisRelativeToMesh = false;
  18667. // injecting a canvas element on top of the canvas 3D game
  18668. if (!VirtualJoystick.vjCanvas) {
  18669. window.addEventListener("resize", function () {
  18670. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18671. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18672. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18673. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18674. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18675. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18676. }, false);
  18677. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18678. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18679. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18680. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18681. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18682. VirtualJoystick.vjCanvas.style.width = "100%";
  18683. VirtualJoystick.vjCanvas.style.height = "100%";
  18684. VirtualJoystick.vjCanvas.style.position = "absolute";
  18685. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18686. VirtualJoystick.vjCanvas.style.top = "0px";
  18687. VirtualJoystick.vjCanvas.style.left = "0px";
  18688. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18689. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18690. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18691. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18692. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18693. document.body.appendChild(VirtualJoystick.vjCanvas);
  18694. }
  18695. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18696. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18697. this.pressed = false;
  18698. // default joystick color
  18699. this._joystickColor = "cyan";
  18700. this._joystickPointerID = -1;
  18701. // current joystick position
  18702. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18703. // origin joystick position
  18704. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18705. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18706. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18707. _this._onPointerDown(evt);
  18708. }, false);
  18709. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18710. _this._onPointerMove(evt);
  18711. }, false);
  18712. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18713. _this._onPointerUp(evt);
  18714. }, false);
  18715. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18716. _this._onPointerUp(evt);
  18717. }, false);
  18718. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18719. evt.preventDefault(); // Disables system menu
  18720. }, false);
  18721. requestAnimationFrame(function () {
  18722. _this._drawVirtualJoystick();
  18723. });
  18724. }
  18725. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18726. this._joystickSensibility = newJoystickSensibility;
  18727. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18728. };
  18729. VirtualJoystick.prototype._onPointerDown = function (e) {
  18730. var positionOnScreenCondition;
  18731. e.preventDefault();
  18732. if (this._leftJoystick === true) {
  18733. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18734. } else {
  18735. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18736. }
  18737. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18738. // First contact will be dedicated to the virtual joystick
  18739. this._joystickPointerID = e.pointerId;
  18740. this._joystickPointerStartPos.x = e.clientX;
  18741. this._joystickPointerStartPos.y = e.clientY;
  18742. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18743. this._deltaJoystickVector.x = 0;
  18744. this._deltaJoystickVector.y = 0;
  18745. this.pressed = true;
  18746. this._touches.add(e.pointerId.toString(), e);
  18747. } else {
  18748. // You can only trigger the action buttons with a joystick declared
  18749. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18750. this._action();
  18751. this._touches.add(e.pointerId.toString(), e);
  18752. }
  18753. }
  18754. };
  18755. VirtualJoystick.prototype._onPointerMove = function (e) {
  18756. // If the current pointer is the one associated to the joystick (first touch contact)
  18757. if (this._joystickPointerID == e.pointerId) {
  18758. this._joystickPointerPos.x = e.clientX;
  18759. this._joystickPointerPos.y = e.clientY;
  18760. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18761. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18762. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18763. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18764. switch (this._axisTargetedByLeftAndRight) {
  18765. case 0 /* X */:
  18766. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18767. break;
  18768. case 1 /* Y */:
  18769. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18770. break;
  18771. case 2 /* Z */:
  18772. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18773. break;
  18774. }
  18775. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18776. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18777. switch (this._axisTargetedByUpAndDown) {
  18778. case 0 /* X */:
  18779. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18780. break;
  18781. case 1 /* Y */:
  18782. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18783. break;
  18784. case 2 /* Z */:
  18785. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18786. break;
  18787. }
  18788. } else {
  18789. if (this._touches.item(e.pointerId.toString())) {
  18790. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18791. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18792. }
  18793. }
  18794. };
  18795. VirtualJoystick.prototype._onPointerUp = function (e) {
  18796. this._clearCanvas();
  18797. if (this._joystickPointerID == e.pointerId) {
  18798. this._joystickPointerID = -1;
  18799. this.pressed = false;
  18800. }
  18801. this._deltaJoystickVector.x = 0;
  18802. this._deltaJoystickVector.y = 0;
  18803. this._touches.remove(e.pointerId.toString());
  18804. };
  18805. /**
  18806. * Change the color of the virtual joystick
  18807. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18808. */
  18809. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18810. this._joystickColor = newColor;
  18811. };
  18812. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18813. this._action = action;
  18814. };
  18815. // Define which axis you'd like to control for left & right
  18816. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18817. switch (axis) {
  18818. case 0 /* X */:
  18819. case 1 /* Y */:
  18820. case 2 /* Z */:
  18821. this._axisTargetedByLeftAndRight = axis;
  18822. break;
  18823. default:
  18824. this._axisTargetedByLeftAndRight = 0 /* X */;
  18825. break;
  18826. }
  18827. };
  18828. // Define which axis you'd like to control for up & down
  18829. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18830. switch (axis) {
  18831. case 0 /* X */:
  18832. case 1 /* Y */:
  18833. case 2 /* Z */:
  18834. this._axisTargetedByUpAndDown = axis;
  18835. break;
  18836. default:
  18837. this._axisTargetedByUpAndDown = 1 /* Y */;
  18838. break;
  18839. }
  18840. };
  18841. VirtualJoystick.prototype._clearCanvas = function () {
  18842. if (this._leftJoystick) {
  18843. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18844. } else {
  18845. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18846. }
  18847. };
  18848. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18849. var _this = this;
  18850. if (this.pressed) {
  18851. this._clearCanvas();
  18852. this._touches.forEach(function (touch) {
  18853. if (touch.pointerId === _this._joystickPointerID) {
  18854. VirtualJoystick.vjCanvasContext.beginPath();
  18855. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18856. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18857. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18858. VirtualJoystick.vjCanvasContext.stroke();
  18859. VirtualJoystick.vjCanvasContext.beginPath();
  18860. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18861. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18862. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18863. VirtualJoystick.vjCanvasContext.stroke();
  18864. VirtualJoystick.vjCanvasContext.beginPath();
  18865. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18866. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18867. VirtualJoystick.vjCanvasContext.stroke();
  18868. } else {
  18869. VirtualJoystick.vjCanvasContext.beginPath();
  18870. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18871. VirtualJoystick.vjCanvasContext.beginPath();
  18872. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18873. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18874. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18875. VirtualJoystick.vjCanvasContext.stroke();
  18876. }
  18877. ;
  18878. });
  18879. }
  18880. requestAnimationFrame(function () {
  18881. _this._drawVirtualJoystick();
  18882. });
  18883. };
  18884. VirtualJoystick.prototype.releaseCanvas = function () {
  18885. if (VirtualJoystick.vjCanvas) {
  18886. document.body.removeChild(VirtualJoystick.vjCanvas);
  18887. VirtualJoystick.vjCanvas = null;
  18888. }
  18889. };
  18890. VirtualJoystick._globalJoystickIndex = 0;
  18891. return VirtualJoystick;
  18892. })();
  18893. BABYLON.VirtualJoystick = VirtualJoystick;
  18894. })(BABYLON || (BABYLON = {}));
  18895. var BABYLON;
  18896. (function (BABYLON) {
  18897. (function (VirtualJoystick) {
  18898. var Collection = (function () {
  18899. function Collection() {
  18900. this._count = 0;
  18901. this._collection = new Array();
  18902. }
  18903. Collection.prototype.Count = function () {
  18904. return this._count;
  18905. };
  18906. Collection.prototype.add = function (key, item) {
  18907. if (this._collection[key] != undefined) {
  18908. return undefined;
  18909. }
  18910. this._collection[key] = item;
  18911. return ++this._count;
  18912. };
  18913. Collection.prototype.remove = function (key) {
  18914. if (this._collection[key] == undefined) {
  18915. return undefined;
  18916. }
  18917. delete this._collection[key];
  18918. return --this._count;
  18919. };
  18920. Collection.prototype.item = function (key) {
  18921. return this._collection[key];
  18922. };
  18923. Collection.prototype.forEach = function (block) {
  18924. var key;
  18925. for (key in this._collection) {
  18926. if (this._collection.hasOwnProperty(key)) {
  18927. block(this._collection[key]);
  18928. }
  18929. }
  18930. };
  18931. return Collection;
  18932. })();
  18933. VirtualJoystick.Collection = Collection;
  18934. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18935. var VirtualJoystick = BABYLON.VirtualJoystick;
  18936. })(BABYLON || (BABYLON = {}));
  18937. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18938. var BABYLON;
  18939. (function (BABYLON) {
  18940. var OculusRiftDevKit2013_Metric = {
  18941. HResolution: 1280,
  18942. VResolution: 800,
  18943. HScreenSize: 0.149759993,
  18944. VScreenSize: 0.0935999975,
  18945. VScreenCenter: 0.0467999987,
  18946. EyeToScreenDistance: 0.0410000011,
  18947. LensSeparationDistance: 0.0635000020,
  18948. InterpupillaryDistance: 0.0640000030,
  18949. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18950. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18951. PostProcessScaleFactor: 1.714605507808412,
  18952. LensCenterOffset: 0.151976421
  18953. };
  18954. var _OculusInnerCamera = (function (_super) {
  18955. __extends(_OculusInnerCamera, _super);
  18956. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18957. _super.call(this, name, position, scene);
  18958. this._workMatrix = new BABYLON.Matrix();
  18959. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18960. // Constants
  18961. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18962. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18963. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18964. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18965. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18966. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18967. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18968. // Postprocess
  18969. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18970. }
  18971. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  18972. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18973. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18974. return this._projectionMatrix;
  18975. };
  18976. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18977. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18978. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18979. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18980. // Computing target and final matrix
  18981. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18982. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18983. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18984. return this._viewMatrix;
  18985. };
  18986. return _OculusInnerCamera;
  18987. })(BABYLON.FreeCamera);
  18988. var OculusCamera = (function (_super) {
  18989. __extends(OculusCamera, _super);
  18990. function OculusCamera(name, position, scene) {
  18991. _super.call(this, name, position, scene);
  18992. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18993. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18994. this.subCameras.push(this._leftCamera);
  18995. this.subCameras.push(this._rightCamera);
  18996. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18997. }
  18998. OculusCamera.prototype._update = function () {
  18999. this._leftCamera.position.copyFrom(this.position);
  19000. this._rightCamera.position.copyFrom(this.position);
  19001. this._updateCamera(this._leftCamera);
  19002. this._updateCamera(this._rightCamera);
  19003. _super.prototype._update.call(this);
  19004. };
  19005. OculusCamera.prototype._updateCamera = function (camera) {
  19006. camera.minZ = this.minZ;
  19007. camera.maxZ = this.maxZ;
  19008. camera.rotation.x = this.rotation.x;
  19009. camera.rotation.y = this.rotation.y;
  19010. camera.rotation.z = this.rotation.z;
  19011. };
  19012. // Oculus events
  19013. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19014. var yaw = evt.alpha / 180 * Math.PI;
  19015. var pitch = evt.beta / 180 * Math.PI;
  19016. var roll = evt.gamma / 180 * Math.PI;
  19017. if (!this._offsetOrientation) {
  19018. this._offsetOrientation = {
  19019. yaw: yaw,
  19020. pitch: pitch,
  19021. roll: roll
  19022. };
  19023. return;
  19024. } else {
  19025. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19026. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19027. this.rotation.z += this._offsetOrientation.roll - roll;
  19028. this._offsetOrientation.yaw = yaw;
  19029. this._offsetOrientation.pitch = pitch;
  19030. this._offsetOrientation.roll = roll;
  19031. }
  19032. };
  19033. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19034. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19035. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19036. };
  19037. OculusCamera.prototype.detachControl = function (element) {
  19038. _super.prototype.detachControl.call(this, element);
  19039. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19040. };
  19041. return OculusCamera;
  19042. })(BABYLON.FreeCamera);
  19043. BABYLON.OculusCamera = OculusCamera;
  19044. })(BABYLON || (BABYLON = {}));
  19045. //# sourceMappingURL=babylon.oculusCamera.js.map
  19046. var BABYLON;
  19047. (function (BABYLON) {
  19048. var OculusRiftDevKit2013_Metric = {
  19049. HResolution: 1280,
  19050. VResolution: 800,
  19051. HScreenSize: 0.149759993,
  19052. VScreenSize: 0.0935999975,
  19053. VScreenCenter: 0.0467999987,
  19054. EyeToScreenDistance: 0.0410000011,
  19055. LensSeparationDistance: 0.0635000020,
  19056. InterpupillaryDistance: 0.0640000030,
  19057. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19058. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19059. PostProcessScaleFactor: 1.714605507808412,
  19060. LensCenterOffset: 0.151976421
  19061. };
  19062. var _OculusInnerGamepadCamera = (function (_super) {
  19063. __extends(_OculusInnerGamepadCamera, _super);
  19064. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19065. _super.call(this, name, position, scene);
  19066. this._workMatrix = new BABYLON.Matrix();
  19067. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19068. // Constants
  19069. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19070. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19071. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19072. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19073. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19074. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19075. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19076. // Postprocess
  19077. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19078. }
  19079. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19080. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19081. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19082. return this._projectionMatrix;
  19083. };
  19084. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19085. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19086. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19087. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19088. // Computing target and final matrix
  19089. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19090. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19091. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19092. return this._viewMatrix;
  19093. };
  19094. return _OculusInnerGamepadCamera;
  19095. })(BABYLON.FreeCamera);
  19096. var OculusGamepadCamera = (function (_super) {
  19097. __extends(OculusGamepadCamera, _super);
  19098. function OculusGamepadCamera(name, position, scene) {
  19099. var _this = this;
  19100. _super.call(this, name, position, scene);
  19101. this.angularSensibility = 200;
  19102. this.moveSensibility = 75;
  19103. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19104. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19105. this.subCameras.push(this._leftCamera);
  19106. this.subCameras.push(this._rightCamera);
  19107. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19108. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19109. _this._onNewGameConnected(gamepad);
  19110. });
  19111. }
  19112. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19113. // Only the first gamepad can control the camera
  19114. if (gamepad.index === 0) {
  19115. this._gamepad = gamepad;
  19116. }
  19117. };
  19118. OculusGamepadCamera.prototype._update = function () {
  19119. this._leftCamera.position.copyFrom(this.position);
  19120. this._rightCamera.position.copyFrom(this.position);
  19121. this._updateCamera(this._leftCamera);
  19122. this._updateCamera(this._rightCamera);
  19123. _super.prototype._update.call(this);
  19124. };
  19125. OculusGamepadCamera.prototype._checkInputs = function () {
  19126. if (!this._gamepad) {
  19127. return;
  19128. }
  19129. var LSValues = this._gamepad.leftStick;
  19130. var normalizedLX = LSValues.x / this.moveSensibility;
  19131. var normalizedLY = LSValues.y / this.moveSensibility;
  19132. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19133. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19134. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19135. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19136. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19137. };
  19138. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19139. camera.minZ = this.minZ;
  19140. camera.maxZ = this.maxZ;
  19141. camera.rotation.x = this.rotation.x;
  19142. camera.rotation.y = this.rotation.y;
  19143. camera.rotation.z = this.rotation.z;
  19144. };
  19145. // Oculus events
  19146. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19147. var yaw = evt.alpha / 180 * Math.PI;
  19148. var pitch = evt.beta / 180 * Math.PI;
  19149. var roll = evt.gamma / 180 * Math.PI;
  19150. if (!this._offsetOrientation) {
  19151. this._offsetOrientation = {
  19152. yaw: yaw,
  19153. pitch: pitch,
  19154. roll: roll
  19155. };
  19156. return;
  19157. } else {
  19158. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19159. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19160. this.rotation.z += this._offsetOrientation.roll - roll;
  19161. this._offsetOrientation.yaw = yaw;
  19162. this._offsetOrientation.pitch = pitch;
  19163. this._offsetOrientation.roll = roll;
  19164. }
  19165. };
  19166. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19167. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19168. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19169. };
  19170. OculusGamepadCamera.prototype.detachControl = function (element) {
  19171. _super.prototype.detachControl.call(this, element);
  19172. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19173. };
  19174. OculusGamepadCamera.prototype.dispose = function () {
  19175. this._gamepads.dispose();
  19176. _super.prototype.dispose.call(this);
  19177. };
  19178. return OculusGamepadCamera;
  19179. })(BABYLON.FreeCamera);
  19180. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19181. })(BABYLON || (BABYLON = {}));
  19182. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19183. var BABYLON;
  19184. (function (BABYLON) {
  19185. // We're mainly based on the logic defined into the FreeCamera code
  19186. var VirtualJoysticksCamera = (function (_super) {
  19187. __extends(VirtualJoysticksCamera, _super);
  19188. function VirtualJoysticksCamera(name, position, scene) {
  19189. _super.call(this, name, position, scene);
  19190. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19191. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19192. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19193. this._leftjoystick.setJoystickSensibility(0.15);
  19194. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19195. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19196. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19197. this._rightjoystick.reverseUpDown = true;
  19198. this._rightjoystick.setJoystickSensibility(0.05);
  19199. this._rightjoystick.setJoystickColor("yellow");
  19200. }
  19201. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19202. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19203. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19204. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19205. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19206. if (!this._leftjoystick.pressed) {
  19207. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19208. }
  19209. if (!this._rightjoystick.pressed) {
  19210. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19211. }
  19212. };
  19213. VirtualJoysticksCamera.prototype.dispose = function () {
  19214. this._leftjoystick.releaseCanvas();
  19215. _super.prototype.dispose.call(this);
  19216. };
  19217. return VirtualJoysticksCamera;
  19218. })(BABYLON.FreeCamera);
  19219. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19220. })(BABYLON || (BABYLON = {}));
  19221. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19222. var BABYLON;
  19223. (function (BABYLON) {
  19224. var ShaderMaterial = (function (_super) {
  19225. __extends(ShaderMaterial, _super);
  19226. function ShaderMaterial(name, scene, shaderPath, options) {
  19227. _super.call(this, name, scene);
  19228. this._textures = new Array();
  19229. this._floats = new Array();
  19230. this._floatsArrays = {};
  19231. this._colors3 = new Array();
  19232. this._colors4 = new Array();
  19233. this._vectors2 = new Array();
  19234. this._vectors3 = new Array();
  19235. this._matrices = new Array();
  19236. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19237. this._shaderPath = shaderPath;
  19238. options.needAlphaBlending = options.needAlphaBlending || false;
  19239. options.needAlphaTesting = options.needAlphaTesting || false;
  19240. options.attributes = options.attributes || ["position", "normal", "uv"];
  19241. options.uniforms = options.uniforms || ["worldViewProjection"];
  19242. options.samplers = options.samplers || [];
  19243. this._options = options;
  19244. }
  19245. ShaderMaterial.prototype.needAlphaBlending = function () {
  19246. return this._options.needAlphaBlending;
  19247. };
  19248. ShaderMaterial.prototype.needAlphaTesting = function () {
  19249. return this._options.needAlphaTesting;
  19250. };
  19251. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19252. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19253. this._options.uniforms.push(uniformName);
  19254. }
  19255. };
  19256. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19257. if (this._options.samplers.indexOf(name) === -1) {
  19258. this._options.samplers.push(name);
  19259. }
  19260. this._textures[name] = texture;
  19261. return this;
  19262. };
  19263. ShaderMaterial.prototype.setFloat = function (name, value) {
  19264. this._checkUniform(name);
  19265. this._floats[name] = value;
  19266. return this;
  19267. };
  19268. ShaderMaterial.prototype.setFloats = function (name, value) {
  19269. this._checkUniform(name);
  19270. this._floatsArrays[name] = value;
  19271. return this;
  19272. };
  19273. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19274. this._checkUniform(name);
  19275. this._colors3[name] = value;
  19276. return this;
  19277. };
  19278. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19279. this._checkUniform(name);
  19280. this._colors4[name] = value;
  19281. return this;
  19282. };
  19283. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19284. this._checkUniform(name);
  19285. this._vectors2[name] = value;
  19286. return this;
  19287. };
  19288. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19289. this._checkUniform(name);
  19290. this._vectors3[name] = value;
  19291. return this;
  19292. };
  19293. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19294. this._checkUniform(name);
  19295. this._matrices[name] = value;
  19296. return this;
  19297. };
  19298. ShaderMaterial.prototype.isReady = function () {
  19299. var scene = this.getScene();
  19300. var engine = scene.getEngine();
  19301. if (!this.checkReadyOnEveryCall) {
  19302. if (this._renderId === scene.getRenderId()) {
  19303. return true;
  19304. }
  19305. }
  19306. var previousEffect = this._effect;
  19307. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19308. if (!this._effect.isReady()) {
  19309. return false;
  19310. }
  19311. if (previousEffect !== this._effect) {
  19312. scene.resetCachedMaterial();
  19313. }
  19314. this._renderId = scene.getRenderId();
  19315. return true;
  19316. };
  19317. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19318. var scene = this.getScene();
  19319. if (this._options.uniforms.indexOf("world") !== -1) {
  19320. this._effect.setMatrix("world", world);
  19321. }
  19322. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19323. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19324. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19325. }
  19326. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19327. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19328. }
  19329. };
  19330. ShaderMaterial.prototype.bind = function (world) {
  19331. // Std values
  19332. this.bindOnlyWorldMatrix(world);
  19333. if (this.getScene().getCachedMaterial() !== this) {
  19334. if (this._options.uniforms.indexOf("view") !== -1) {
  19335. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19336. }
  19337. if (this._options.uniforms.indexOf("projection") !== -1) {
  19338. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19339. }
  19340. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19341. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19342. }
  19343. for (var name in this._textures) {
  19344. this._effect.setTexture(name, this._textures[name]);
  19345. }
  19346. for (name in this._floats) {
  19347. this._effect.setFloat(name, this._floats[name]);
  19348. }
  19349. for (name in this._floatsArrays) {
  19350. this._effect.setArray(name, this._floatsArrays[name]);
  19351. }
  19352. for (name in this._colors3) {
  19353. this._effect.setColor3(name, this._colors3[name]);
  19354. }
  19355. for (name in this._colors4) {
  19356. var color = this._colors4[name];
  19357. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19358. }
  19359. for (name in this._vectors2) {
  19360. this._effect.setVector2(name, this._vectors2[name]);
  19361. }
  19362. for (name in this._vectors3) {
  19363. this._effect.setVector3(name, this._vectors3[name]);
  19364. }
  19365. for (name in this._matrices) {
  19366. this._effect.setMatrix(name, this._matrices[name]);
  19367. }
  19368. }
  19369. _super.prototype.bind.call(this, world, null);
  19370. };
  19371. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19372. for (var name in this._textures) {
  19373. this._textures[name].dispose();
  19374. }
  19375. this._textures = [];
  19376. _super.prototype.dispose.call(this, forceDisposeEffect);
  19377. };
  19378. return ShaderMaterial;
  19379. })(BABYLON.Material);
  19380. BABYLON.ShaderMaterial = ShaderMaterial;
  19381. })(BABYLON || (BABYLON = {}));
  19382. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19383. var BABYLON;
  19384. (function (BABYLON) {
  19385. var VertexData = (function () {
  19386. function VertexData() {
  19387. }
  19388. VertexData.prototype.set = function (data, kind) {
  19389. switch (kind) {
  19390. case BABYLON.VertexBuffer.PositionKind:
  19391. this.positions = data;
  19392. break;
  19393. case BABYLON.VertexBuffer.NormalKind:
  19394. this.normals = data;
  19395. break;
  19396. case BABYLON.VertexBuffer.UVKind:
  19397. this.uvs = data;
  19398. break;
  19399. case BABYLON.VertexBuffer.UV2Kind:
  19400. this.uv2s = data;
  19401. break;
  19402. case BABYLON.VertexBuffer.ColorKind:
  19403. this.colors = data;
  19404. break;
  19405. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19406. this.matricesIndices = data;
  19407. break;
  19408. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19409. this.matricesWeights = data;
  19410. break;
  19411. }
  19412. };
  19413. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19414. this._applyTo(mesh, updatable);
  19415. };
  19416. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19417. this._applyTo(geometry, updatable);
  19418. };
  19419. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19420. this._update(mesh);
  19421. };
  19422. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19423. this._update(geometry);
  19424. };
  19425. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19426. if (this.positions) {
  19427. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19428. }
  19429. if (this.normals) {
  19430. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19431. }
  19432. if (this.uvs) {
  19433. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19434. }
  19435. if (this.uv2s) {
  19436. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19437. }
  19438. if (this.colors) {
  19439. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19440. }
  19441. if (this.matricesIndices) {
  19442. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19443. }
  19444. if (this.matricesWeights) {
  19445. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19446. }
  19447. if (this.indices) {
  19448. meshOrGeometry.setIndices(this.indices);
  19449. }
  19450. };
  19451. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19452. if (this.positions) {
  19453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19454. }
  19455. if (this.normals) {
  19456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19457. }
  19458. if (this.uvs) {
  19459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19460. }
  19461. if (this.uv2s) {
  19462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19463. }
  19464. if (this.colors) {
  19465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19466. }
  19467. if (this.matricesIndices) {
  19468. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19469. }
  19470. if (this.matricesWeights) {
  19471. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19472. }
  19473. if (this.indices) {
  19474. meshOrGeometry.setIndices(this.indices);
  19475. }
  19476. };
  19477. VertexData.prototype.transform = function (matrix) {
  19478. var transformed = BABYLON.Vector3.Zero();
  19479. if (this.positions) {
  19480. var position = BABYLON.Vector3.Zero();
  19481. for (var index = 0; index < this.positions.length; index += 3) {
  19482. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19483. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19484. this.positions[index] = transformed.x;
  19485. this.positions[index + 1] = transformed.y;
  19486. this.positions[index + 2] = transformed.z;
  19487. }
  19488. }
  19489. if (this.normals) {
  19490. var normal = BABYLON.Vector3.Zero();
  19491. for (index = 0; index < this.normals.length; index += 3) {
  19492. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19493. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19494. this.normals[index] = transformed.x;
  19495. this.normals[index + 1] = transformed.y;
  19496. this.normals[index + 2] = transformed.z;
  19497. }
  19498. }
  19499. };
  19500. VertexData.prototype.merge = function (other) {
  19501. if (other.indices) {
  19502. if (!this.indices) {
  19503. this.indices = [];
  19504. }
  19505. var offset = this.positions ? this.positions.length / 3 : 0;
  19506. for (var index = 0; index < other.indices.length; index++) {
  19507. this.indices.push(other.indices[index] + offset);
  19508. }
  19509. }
  19510. if (other.positions) {
  19511. if (!this.positions) {
  19512. this.positions = [];
  19513. }
  19514. for (index = 0; index < other.positions.length; index++) {
  19515. this.positions.push(other.positions[index]);
  19516. }
  19517. }
  19518. if (other.normals) {
  19519. if (!this.normals) {
  19520. this.normals = [];
  19521. }
  19522. for (index = 0; index < other.normals.length; index++) {
  19523. this.normals.push(other.normals[index]);
  19524. }
  19525. }
  19526. if (other.uvs) {
  19527. if (!this.uvs) {
  19528. this.uvs = [];
  19529. }
  19530. for (index = 0; index < other.uvs.length; index++) {
  19531. this.uvs.push(other.uvs[index]);
  19532. }
  19533. }
  19534. if (other.uv2s) {
  19535. if (!this.uv2s) {
  19536. this.uv2s = [];
  19537. }
  19538. for (index = 0; index < other.uv2s.length; index++) {
  19539. this.uv2s.push(other.uv2s[index]);
  19540. }
  19541. }
  19542. if (other.matricesIndices) {
  19543. if (!this.matricesIndices) {
  19544. this.matricesIndices = [];
  19545. }
  19546. for (index = 0; index < other.matricesIndices.length; index++) {
  19547. this.matricesIndices.push(other.matricesIndices[index]);
  19548. }
  19549. }
  19550. if (other.matricesWeights) {
  19551. if (!this.matricesWeights) {
  19552. this.matricesWeights = [];
  19553. }
  19554. for (index = 0; index < other.matricesWeights.length; index++) {
  19555. this.matricesWeights.push(other.matricesWeights[index]);
  19556. }
  19557. }
  19558. if (other.colors) {
  19559. if (!this.colors) {
  19560. this.colors = [];
  19561. }
  19562. for (index = 0; index < other.colors.length; index++) {
  19563. this.colors.push(other.colors[index]);
  19564. }
  19565. }
  19566. };
  19567. // Statics
  19568. VertexData.ExtractFromMesh = function (mesh) {
  19569. return VertexData._ExtractFrom(mesh);
  19570. };
  19571. VertexData.ExtractFromGeometry = function (geometry) {
  19572. return VertexData._ExtractFrom(geometry);
  19573. };
  19574. VertexData._ExtractFrom = function (meshOrGeometry) {
  19575. var result = new BABYLON.VertexData();
  19576. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19577. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19578. }
  19579. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19580. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19581. }
  19582. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19583. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19584. }
  19585. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19586. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19587. }
  19588. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19589. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19590. }
  19591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19592. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19593. }
  19594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19595. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19596. }
  19597. result.indices = meshOrGeometry.getIndices();
  19598. return result;
  19599. };
  19600. VertexData.CreateBox = function (size) {
  19601. var normalsSource = [
  19602. new BABYLON.Vector3(0, 0, 1),
  19603. new BABYLON.Vector3(0, 0, -1),
  19604. new BABYLON.Vector3(1, 0, 0),
  19605. new BABYLON.Vector3(-1, 0, 0),
  19606. new BABYLON.Vector3(0, 1, 0),
  19607. new BABYLON.Vector3(0, -1, 0)
  19608. ];
  19609. var indices = [];
  19610. var positions = [];
  19611. var normals = [];
  19612. var uvs = [];
  19613. size = size || 1;
  19614. for (var index = 0; index < normalsSource.length; index++) {
  19615. var normal = normalsSource[index];
  19616. // Get two vectors perpendicular to the face normal and to each other.
  19617. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19618. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19619. // Six indices (two triangles) per face.
  19620. var verticesLength = positions.length / 3;
  19621. indices.push(verticesLength);
  19622. indices.push(verticesLength + 1);
  19623. indices.push(verticesLength + 2);
  19624. indices.push(verticesLength);
  19625. indices.push(verticesLength + 2);
  19626. indices.push(verticesLength + 3);
  19627. // Four vertices per face.
  19628. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19629. positions.push(vertex.x, vertex.y, vertex.z);
  19630. normals.push(normal.x, normal.y, normal.z);
  19631. uvs.push(1.0, 1.0);
  19632. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19633. positions.push(vertex.x, vertex.y, vertex.z);
  19634. normals.push(normal.x, normal.y, normal.z);
  19635. uvs.push(0.0, 1.0);
  19636. vertex = normal.add(side1).add(side2).scale(size / 2);
  19637. positions.push(vertex.x, vertex.y, vertex.z);
  19638. normals.push(normal.x, normal.y, normal.z);
  19639. uvs.push(0.0, 0.0);
  19640. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19641. positions.push(vertex.x, vertex.y, vertex.z);
  19642. normals.push(normal.x, normal.y, normal.z);
  19643. uvs.push(1.0, 0.0);
  19644. }
  19645. // Result
  19646. var vertexData = new BABYLON.VertexData();
  19647. vertexData.indices = indices;
  19648. vertexData.positions = positions;
  19649. vertexData.normals = normals;
  19650. vertexData.uvs = uvs;
  19651. return vertexData;
  19652. };
  19653. VertexData.CreateSphere = function (segments, diameter) {
  19654. segments = segments || 32;
  19655. diameter = diameter || 1;
  19656. var radius = diameter / 2;
  19657. var totalZRotationSteps = 2 + segments;
  19658. var totalYRotationSteps = 2 * totalZRotationSteps;
  19659. var indices = [];
  19660. var positions = [];
  19661. var normals = [];
  19662. var uvs = [];
  19663. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19664. var normalizedZ = zRotationStep / totalZRotationSteps;
  19665. var angleZ = (normalizedZ * Math.PI);
  19666. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19667. var normalizedY = yRotationStep / totalYRotationSteps;
  19668. var angleY = normalizedY * Math.PI * 2;
  19669. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19670. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19671. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19672. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19673. var vertex = complete.scale(radius);
  19674. var normal = BABYLON.Vector3.Normalize(vertex);
  19675. positions.push(vertex.x, vertex.y, vertex.z);
  19676. normals.push(normal.x, normal.y, normal.z);
  19677. uvs.push(normalizedZ, normalizedY);
  19678. }
  19679. if (zRotationStep > 0) {
  19680. var verticesCount = positions.length / 3;
  19681. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19682. indices.push((firstIndex));
  19683. indices.push((firstIndex + 1));
  19684. indices.push(firstIndex + totalYRotationSteps + 1);
  19685. indices.push((firstIndex + totalYRotationSteps + 1));
  19686. indices.push((firstIndex + 1));
  19687. indices.push((firstIndex + totalYRotationSteps + 2));
  19688. }
  19689. }
  19690. }
  19691. // Result
  19692. var vertexData = new BABYLON.VertexData();
  19693. vertexData.indices = indices;
  19694. vertexData.positions = positions;
  19695. vertexData.normals = normals;
  19696. vertexData.uvs = uvs;
  19697. return vertexData;
  19698. };
  19699. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19700. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19701. var radiusTop = diameterTop / 2;
  19702. var radiusBottom = diameterBottom / 2;
  19703. var indices = [];
  19704. var positions = [];
  19705. var normals = [];
  19706. var uvs = [];
  19707. height = height || 1;
  19708. diameterTop = diameterTop || 0.5;
  19709. diameterBottom = diameterBottom || 1;
  19710. tessellation = tessellation || 16;
  19711. subdivisions = subdivisions || 1;
  19712. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19713. var getCircleVector = function (i) {
  19714. var angle = (i * 2.0 * Math.PI / tessellation);
  19715. var dx = Math.cos(angle);
  19716. var dz = Math.sin(angle);
  19717. return new BABYLON.Vector3(dx, 0, dz);
  19718. };
  19719. var createCylinderCap = function (isTop) {
  19720. var radius = isTop ? radiusTop : radiusBottom;
  19721. if (radius == 0) {
  19722. return;
  19723. }
  19724. var vbase = positions.length / 3;
  19725. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19726. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19727. if (!isTop) {
  19728. offset.scaleInPlace(-1);
  19729. textureScale.x = -textureScale.x;
  19730. }
  19731. for (i = 0; i < tessellation; i++) {
  19732. var circleVector = getCircleVector(i);
  19733. var position = circleVector.scale(radius).add(offset);
  19734. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19735. positions.push(position.x, position.y, position.z);
  19736. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19737. }
  19738. for (var i = 0; i < tessellation - 2; i++) {
  19739. if (!isTop) {
  19740. indices.push(vbase);
  19741. indices.push(vbase + (i + 2) % tessellation);
  19742. indices.push(vbase + (i + 1) % tessellation);
  19743. } else {
  19744. indices.push(vbase);
  19745. indices.push(vbase + (i + 1) % tessellation);
  19746. indices.push(vbase + (i + 2) % tessellation);
  19747. }
  19748. }
  19749. };
  19750. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19751. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19752. var stride = tessellation + 1;
  19753. for (var i = 0; i <= tessellation; i++) {
  19754. var circleVector = getCircleVector(i);
  19755. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19756. var position, radius = radiusBottom;
  19757. for (var s = 0; s <= subdivisions; s++) {
  19758. // Update variables
  19759. position = circleVector.scale(radius);
  19760. position.addInPlace(base.add(offset.scale(s)));
  19761. textureCoordinate.y += 1 / subdivisions;
  19762. radius += (radiusTop - radiusBottom) / subdivisions;
  19763. // Push in arrays
  19764. positions.push(position.x, position.y, position.z);
  19765. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19766. }
  19767. }
  19768. subdivisions += 1;
  19769. for (var s = 0; s < subdivisions - 1; s++) {
  19770. for (var i = 0; i <= tessellation; i++) {
  19771. indices.push(i * subdivisions + s);
  19772. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19773. indices.push(i * subdivisions + (s + 1));
  19774. indices.push(i * subdivisions + (s + 1));
  19775. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19776. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19777. }
  19778. }
  19779. // Create flat triangle fan caps to seal the top and bottom.
  19780. createCylinderCap(true);
  19781. createCylinderCap(false);
  19782. // Normals
  19783. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19784. // Result
  19785. var vertexData = new BABYLON.VertexData();
  19786. vertexData.indices = indices;
  19787. vertexData.positions = positions;
  19788. vertexData.normals = normals;
  19789. vertexData.uvs = uvs;
  19790. return vertexData;
  19791. };
  19792. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19793. var indices = [];
  19794. var positions = [];
  19795. var normals = [];
  19796. var uvs = [];
  19797. diameter = diameter || 1;
  19798. thickness = thickness || 0.5;
  19799. tessellation = tessellation || 16;
  19800. var stride = tessellation + 1;
  19801. for (var i = 0; i <= tessellation; i++) {
  19802. var u = i / tessellation;
  19803. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19804. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19805. for (var j = 0; j <= tessellation; j++) {
  19806. var v = 1 - j / tessellation;
  19807. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19808. var dx = Math.cos(innerAngle);
  19809. var dy = Math.sin(innerAngle);
  19810. // Create a vertex.
  19811. var normal = new BABYLON.Vector3(dx, dy, 0);
  19812. var position = normal.scale(thickness / 2);
  19813. var textureCoordinate = new BABYLON.Vector2(u, v);
  19814. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19815. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19816. positions.push(position.x, position.y, position.z);
  19817. normals.push(normal.x, normal.y, normal.z);
  19818. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19819. // And create indices for two triangles.
  19820. var nextI = (i + 1) % stride;
  19821. var nextJ = (j + 1) % stride;
  19822. indices.push(i * stride + j);
  19823. indices.push(i * stride + nextJ);
  19824. indices.push(nextI * stride + j);
  19825. indices.push(i * stride + nextJ);
  19826. indices.push(nextI * stride + nextJ);
  19827. indices.push(nextI * stride + j);
  19828. }
  19829. }
  19830. // Result
  19831. var vertexData = new BABYLON.VertexData();
  19832. vertexData.indices = indices;
  19833. vertexData.positions = positions;
  19834. vertexData.normals = normals;
  19835. vertexData.uvs = uvs;
  19836. return vertexData;
  19837. };
  19838. VertexData.CreateLines = function (points) {
  19839. var indices = [];
  19840. var positions = [];
  19841. for (var index = 0; index < points.length; index++) {
  19842. positions.push(points[index].x, points[index].y, points[index].z);
  19843. if (index > 0) {
  19844. indices.push(index - 1);
  19845. indices.push(index);
  19846. }
  19847. }
  19848. // Result
  19849. var vertexData = new BABYLON.VertexData();
  19850. vertexData.indices = indices;
  19851. vertexData.positions = positions;
  19852. return vertexData;
  19853. };
  19854. VertexData.CreateGround = function (width, height, subdivisions) {
  19855. var indices = [];
  19856. var positions = [];
  19857. var normals = [];
  19858. var uvs = [];
  19859. var row, col;
  19860. width = width || 1;
  19861. height = height || 1;
  19862. subdivisions = subdivisions || 1;
  19863. for (row = 0; row <= subdivisions; row++) {
  19864. for (col = 0; col <= subdivisions; col++) {
  19865. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19866. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19867. positions.push(position.x, position.y, position.z);
  19868. normals.push(normal.x, normal.y, normal.z);
  19869. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19870. }
  19871. }
  19872. for (row = 0; row < subdivisions; row++) {
  19873. for (col = 0; col < subdivisions; col++) {
  19874. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19875. indices.push(col + 1 + row * (subdivisions + 1));
  19876. indices.push(col + row * (subdivisions + 1));
  19877. indices.push(col + (row + 1) * (subdivisions + 1));
  19878. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19879. indices.push(col + row * (subdivisions + 1));
  19880. }
  19881. }
  19882. // Result
  19883. var vertexData = new BABYLON.VertexData();
  19884. vertexData.indices = indices;
  19885. vertexData.positions = positions;
  19886. vertexData.normals = normals;
  19887. vertexData.uvs = uvs;
  19888. return vertexData;
  19889. };
  19890. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19891. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19892. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19893. var indices = [];
  19894. var positions = [];
  19895. var normals = [];
  19896. var uvs = [];
  19897. var row, col, tileRow, tileCol;
  19898. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19899. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19900. precision.w = (precision.w < 1) ? 1 : precision.w;
  19901. precision.h = (precision.h < 1) ? 1 : precision.h;
  19902. var tileSize = {
  19903. 'w': (xmax - xmin) / subdivisions.w,
  19904. 'h': (zmax - zmin) / subdivisions.h
  19905. };
  19906. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19907. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19908. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19909. }
  19910. }
  19911. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19912. // Indices
  19913. var base = positions.length / 3;
  19914. var rowLength = precision.w + 1;
  19915. for (row = 0; row < precision.h; row++) {
  19916. for (col = 0; col < precision.w; col++) {
  19917. var square = [
  19918. base + col + row * rowLength,
  19919. base + (col + 1) + row * rowLength,
  19920. base + (col + 1) + (row + 1) * rowLength,
  19921. base + col + (row + 1) * rowLength
  19922. ];
  19923. indices.push(square[1]);
  19924. indices.push(square[2]);
  19925. indices.push(square[3]);
  19926. indices.push(square[0]);
  19927. indices.push(square[1]);
  19928. indices.push(square[3]);
  19929. }
  19930. }
  19931. // Position, normals and uvs
  19932. var position = BABYLON.Vector3.Zero();
  19933. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19934. for (row = 0; row <= precision.h; row++) {
  19935. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19936. for (col = 0; col <= precision.w; col++) {
  19937. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19938. position.y = 0;
  19939. positions.push(position.x, position.y, position.z);
  19940. normals.push(normal.x, normal.y, normal.z);
  19941. uvs.push(col / precision.w, row / precision.h);
  19942. }
  19943. }
  19944. }
  19945. // Result
  19946. var vertexData = new BABYLON.VertexData();
  19947. vertexData.indices = indices;
  19948. vertexData.positions = positions;
  19949. vertexData.normals = normals;
  19950. vertexData.uvs = uvs;
  19951. return vertexData;
  19952. };
  19953. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19954. var indices = [];
  19955. var positions = [];
  19956. var normals = [];
  19957. var uvs = [];
  19958. var row, col;
  19959. for (row = 0; row <= subdivisions; row++) {
  19960. for (col = 0; col <= subdivisions; col++) {
  19961. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19962. // Compute height
  19963. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19964. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  19965. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  19966. var r = buffer[pos] / 255.0;
  19967. var g = buffer[pos + 1] / 255.0;
  19968. var b = buffer[pos + 2] / 255.0;
  19969. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19970. position.y = minHeight + (maxHeight - minHeight) * gradient;
  19971. // Add vertex
  19972. positions.push(position.x, position.y, position.z);
  19973. normals.push(0, 0, 0);
  19974. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19975. }
  19976. }
  19977. for (row = 0; row < subdivisions; row++) {
  19978. for (col = 0; col < subdivisions; col++) {
  19979. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19980. indices.push(col + 1 + row * (subdivisions + 1));
  19981. indices.push(col + row * (subdivisions + 1));
  19982. indices.push(col + (row + 1) * (subdivisions + 1));
  19983. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19984. indices.push(col + row * (subdivisions + 1));
  19985. }
  19986. }
  19987. // Normals
  19988. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19989. // Result
  19990. var vertexData = new BABYLON.VertexData();
  19991. vertexData.indices = indices;
  19992. vertexData.positions = positions;
  19993. vertexData.normals = normals;
  19994. vertexData.uvs = uvs;
  19995. return vertexData;
  19996. };
  19997. VertexData.CreatePlane = function (size) {
  19998. var indices = [];
  19999. var positions = [];
  20000. var normals = [];
  20001. var uvs = [];
  20002. size = size || 1;
  20003. // Vertices
  20004. var halfSize = size / 2.0;
  20005. positions.push(-halfSize, -halfSize, 0);
  20006. normals.push(0, 0, -1.0);
  20007. uvs.push(0.0, 0.0);
  20008. positions.push(halfSize, -halfSize, 0);
  20009. normals.push(0, 0, -1.0);
  20010. uvs.push(1.0, 0.0);
  20011. positions.push(halfSize, halfSize, 0);
  20012. normals.push(0, 0, -1.0);
  20013. uvs.push(1.0, 1.0);
  20014. positions.push(-halfSize, halfSize, 0);
  20015. normals.push(0, 0, -1.0);
  20016. uvs.push(0.0, 1.0);
  20017. // Indices
  20018. indices.push(0);
  20019. indices.push(1);
  20020. indices.push(2);
  20021. indices.push(0);
  20022. indices.push(2);
  20023. indices.push(3);
  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. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20033. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20034. var indices = [];
  20035. var positions = [];
  20036. var normals = [];
  20037. var uvs = [];
  20038. radius = radius || 2;
  20039. tube = tube || 0.5;
  20040. radialSegments = radialSegments || 32;
  20041. tubularSegments = tubularSegments || 32;
  20042. p = p || 2;
  20043. q = q || 3;
  20044. // Helper
  20045. var getPos = function (angle) {
  20046. var cu = Math.cos(angle);
  20047. var su = Math.sin(angle);
  20048. var quOverP = q / p * angle;
  20049. var cs = Math.cos(quOverP);
  20050. var tx = radius * (2 + cs) * 0.5 * cu;
  20051. var ty = radius * (2 + cs) * su * 0.5;
  20052. var tz = radius * Math.sin(quOverP) * 0.5;
  20053. return new BABYLON.Vector3(tx, ty, tz);
  20054. };
  20055. for (var i = 0; i <= radialSegments; i++) {
  20056. var modI = i % radialSegments;
  20057. var u = modI / radialSegments * 2 * p * Math.PI;
  20058. var p1 = getPos(u);
  20059. var p2 = getPos(u + 0.01);
  20060. var tang = p2.subtract(p1);
  20061. var n = p2.add(p1);
  20062. var bitan = BABYLON.Vector3.Cross(tang, n);
  20063. n = BABYLON.Vector3.Cross(bitan, tang);
  20064. bitan.normalize();
  20065. n.normalize();
  20066. for (var j = 0; j < tubularSegments; j++) {
  20067. var modJ = j % tubularSegments;
  20068. var v = modJ / tubularSegments * 2 * Math.PI;
  20069. var cx = -tube * Math.cos(v);
  20070. var cy = tube * Math.sin(v);
  20071. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20072. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20073. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20074. uvs.push(i / radialSegments);
  20075. uvs.push(j / tubularSegments);
  20076. }
  20077. }
  20078. for (i = 0; i < radialSegments; i++) {
  20079. for (j = 0; j < tubularSegments; j++) {
  20080. var jNext = (j + 1) % tubularSegments;
  20081. var a = i * tubularSegments + j;
  20082. var b = (i + 1) * tubularSegments + j;
  20083. var c = (i + 1) * tubularSegments + jNext;
  20084. var d = i * tubularSegments + jNext;
  20085. indices.push(d);
  20086. indices.push(b);
  20087. indices.push(a);
  20088. indices.push(d);
  20089. indices.push(c);
  20090. indices.push(b);
  20091. }
  20092. }
  20093. // Normals
  20094. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20095. // Result
  20096. var vertexData = new BABYLON.VertexData();
  20097. vertexData.indices = indices;
  20098. vertexData.positions = positions;
  20099. vertexData.normals = normals;
  20100. vertexData.uvs = uvs;
  20101. return vertexData;
  20102. };
  20103. // Tools
  20104. VertexData.ComputeNormals = function (positions, indices, normals) {
  20105. var positionVectors = [];
  20106. var facesOfVertices = [];
  20107. var index;
  20108. for (index = 0; index < positions.length; index += 3) {
  20109. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20110. positionVectors.push(vector3);
  20111. facesOfVertices.push([]);
  20112. }
  20113. // Compute normals
  20114. var facesNormals = [];
  20115. for (index = 0; index < indices.length / 3; index++) {
  20116. var i1 = indices[index * 3];
  20117. var i2 = indices[index * 3 + 1];
  20118. var i3 = indices[index * 3 + 2];
  20119. var p1 = positionVectors[i1];
  20120. var p2 = positionVectors[i2];
  20121. var p3 = positionVectors[i3];
  20122. var p1p2 = p1.subtract(p2);
  20123. var p3p2 = p3.subtract(p2);
  20124. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20125. facesOfVertices[i1].push(index);
  20126. facesOfVertices[i2].push(index);
  20127. facesOfVertices[i3].push(index);
  20128. }
  20129. for (index = 0; index < positionVectors.length; index++) {
  20130. var faces = facesOfVertices[index];
  20131. var normal = BABYLON.Vector3.Zero();
  20132. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20133. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20134. }
  20135. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20136. normals[index * 3] = normal.x;
  20137. normals[index * 3 + 1] = normal.y;
  20138. normals[index * 3 + 2] = normal.z;
  20139. }
  20140. };
  20141. return VertexData;
  20142. })();
  20143. BABYLON.VertexData = VertexData;
  20144. })(BABYLON || (BABYLON = {}));
  20145. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20146. var BABYLON;
  20147. (function (BABYLON) {
  20148. var buildCamera = function (that, name) {
  20149. that._leftCamera.isIntermediate = true;
  20150. that.subCameras.push(that._leftCamera);
  20151. that.subCameras.push(that._rightCamera);
  20152. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20153. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20154. that._anaglyphPostProcess.onApply = function (effect) {
  20155. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20156. };
  20157. that._update();
  20158. };
  20159. var AnaglyphArcRotateCamera = (function (_super) {
  20160. __extends(AnaglyphArcRotateCamera, _super);
  20161. // ANY
  20162. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20163. _super.call(this, name, alpha, beta, radius, target, scene);
  20164. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20165. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20166. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20167. buildCamera(this, name);
  20168. }
  20169. AnaglyphArcRotateCamera.prototype._update = function () {
  20170. this._updateCamera(this._leftCamera);
  20171. this._updateCamera(this._rightCamera);
  20172. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20173. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20174. _super.prototype._update.call(this);
  20175. };
  20176. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20177. camera.beta = this.beta;
  20178. camera.radius = this.radius;
  20179. camera.minZ = this.minZ;
  20180. camera.maxZ = this.maxZ;
  20181. camera.fov = this.fov;
  20182. camera.target = this.target;
  20183. };
  20184. return AnaglyphArcRotateCamera;
  20185. })(BABYLON.ArcRotateCamera);
  20186. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20187. var AnaglyphFreeCamera = (function (_super) {
  20188. __extends(AnaglyphFreeCamera, _super);
  20189. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20190. _super.call(this, name, position, scene);
  20191. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20192. this._transformMatrix = new BABYLON.Matrix();
  20193. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20194. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20195. buildCamera(this, name);
  20196. }
  20197. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20198. var target = this.getTarget();
  20199. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20200. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20201. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20202. };
  20203. AnaglyphFreeCamera.prototype._update = function () {
  20204. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20205. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20206. this._updateCamera(this._leftCamera);
  20207. this._updateCamera(this._rightCamera);
  20208. _super.prototype._update.call(this);
  20209. };
  20210. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20211. camera.minZ = this.minZ;
  20212. camera.maxZ = this.maxZ;
  20213. camera.fov = this.fov;
  20214. camera.viewport = this.viewport;
  20215. camera.setTarget(this.getTarget());
  20216. };
  20217. return AnaglyphFreeCamera;
  20218. })(BABYLON.FreeCamera);
  20219. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20220. })(BABYLON || (BABYLON = {}));
  20221. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20222. var BABYLON;
  20223. (function (BABYLON) {
  20224. var AnaglyphPostProcess = (function (_super) {
  20225. __extends(AnaglyphPostProcess, _super);
  20226. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20227. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20228. }
  20229. return AnaglyphPostProcess;
  20230. })(BABYLON.PostProcess);
  20231. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20232. })(BABYLON || (BABYLON = {}));
  20233. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20234. var BABYLON;
  20235. (function (BABYLON) {
  20236. var Tags = (function () {
  20237. function Tags() {
  20238. }
  20239. Tags.EnableFor = function (obj) {
  20240. obj._tags = obj._tags || {};
  20241. obj.hasTags = function () {
  20242. return Tags.HasTags(obj);
  20243. };
  20244. obj.addTags = function (tagsString) {
  20245. return Tags.AddTagsTo(obj, tagsString);
  20246. };
  20247. obj.removeTags = function (tagsString) {
  20248. return Tags.RemoveTagsFrom(obj, tagsString);
  20249. };
  20250. obj.matchesTagsQuery = function (tagsQuery) {
  20251. return Tags.MatchesQuery(obj, tagsQuery);
  20252. };
  20253. };
  20254. Tags.DisableFor = function (obj) {
  20255. delete obj._tags;
  20256. delete obj.hasTags;
  20257. delete obj.addTags;
  20258. delete obj.removeTags;
  20259. delete obj.matchesTagsQuery;
  20260. };
  20261. Tags.HasTags = function (obj) {
  20262. if (!obj._tags) {
  20263. return false;
  20264. }
  20265. return !BABYLON.Tools.IsEmpty(obj._tags);
  20266. };
  20267. Tags.GetTags = function (obj) {
  20268. if (!obj._tags) {
  20269. return null;
  20270. }
  20271. return obj._tags;
  20272. };
  20273. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20274. // a tag cannot start with '||', '&&', and '!'
  20275. // it cannot contain whitespaces
  20276. Tags.AddTagsTo = function (obj, tagsString) {
  20277. if (!tagsString) {
  20278. return;
  20279. }
  20280. var tags = tagsString.split(" ");
  20281. for (var t in tags) {
  20282. Tags._AddTagTo(obj, tags[t]);
  20283. }
  20284. };
  20285. Tags._AddTagTo = function (obj, tag) {
  20286. tag = tag.trim();
  20287. if (tag === "" || tag === "true" || tag === "false") {
  20288. return;
  20289. }
  20290. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20291. return;
  20292. }
  20293. Tags.EnableFor(obj);
  20294. obj._tags[tag] = true;
  20295. };
  20296. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20297. if (!Tags.HasTags(obj)) {
  20298. return;
  20299. }
  20300. var tags = tagsString.split(" ");
  20301. for (var t in tags) {
  20302. Tags._RemoveTagFrom(obj, tags[t]);
  20303. }
  20304. };
  20305. Tags._RemoveTagFrom = function (obj, tag) {
  20306. delete obj._tags[tag];
  20307. };
  20308. Tags.MatchesQuery = function (obj, tagsQuery) {
  20309. if (tagsQuery === undefined) {
  20310. return true;
  20311. }
  20312. if (tagsQuery === "") {
  20313. return Tags.HasTags(obj);
  20314. }
  20315. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20316. return Tags.HasTags(obj) && obj._tags[r];
  20317. });
  20318. };
  20319. return Tags;
  20320. })();
  20321. BABYLON.Tags = Tags;
  20322. })(BABYLON || (BABYLON = {}));
  20323. //# sourceMappingURL=babylon.tags.js.map
  20324. var BABYLON;
  20325. (function (BABYLON) {
  20326. (function (Internals) {
  20327. var AndOrNotEvaluator = (function () {
  20328. function AndOrNotEvaluator() {
  20329. }
  20330. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20331. if (!query.match(/\([^\(\)]*\)/g)) {
  20332. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20333. } else {
  20334. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20335. // remove parenthesis
  20336. r = r.slice(1, r.length - 1);
  20337. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20338. });
  20339. }
  20340. if (query === "true") {
  20341. return true;
  20342. }
  20343. if (query === "false") {
  20344. return false;
  20345. }
  20346. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20347. };
  20348. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20349. evaluateCallback = evaluateCallback || (function (r) {
  20350. return r === "true" ? true : false;
  20351. });
  20352. var result;
  20353. var or = parenthesisContent.split("||");
  20354. for (var i in or) {
  20355. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20356. var and = ori.split("&&");
  20357. if (and.length > 1) {
  20358. for (var j = 0; j < and.length; ++j) {
  20359. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20360. if (andj !== "true" && andj !== "false") {
  20361. if (andj[0] === "!") {
  20362. result = !evaluateCallback(andj.substring(1));
  20363. } else {
  20364. result = evaluateCallback(andj);
  20365. }
  20366. } else {
  20367. result = andj === "true" ? true : false;
  20368. }
  20369. if (!result) {
  20370. ori = "false";
  20371. break;
  20372. }
  20373. }
  20374. }
  20375. if (result || ori === "true") {
  20376. result = true;
  20377. break;
  20378. }
  20379. // result equals false (or undefined)
  20380. if (ori !== "true" && ori !== "false") {
  20381. if (ori[0] === "!") {
  20382. result = !evaluateCallback(ori.substring(1));
  20383. } else {
  20384. result = evaluateCallback(ori);
  20385. }
  20386. } else {
  20387. result = ori === "true" ? true : false;
  20388. }
  20389. }
  20390. // the whole parenthesis scope is replaced by 'true' or 'false'
  20391. return result ? "true" : "false";
  20392. };
  20393. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20394. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20395. // remove whitespaces
  20396. r = r.replace(/[\s]/g, function () {
  20397. return "";
  20398. });
  20399. return r.length % 2 ? "!" : "";
  20400. });
  20401. booleanString = booleanString.trim();
  20402. if (booleanString === "!true") {
  20403. booleanString = "false";
  20404. } else if (booleanString === "!false") {
  20405. booleanString = "true";
  20406. }
  20407. return booleanString;
  20408. };
  20409. return AndOrNotEvaluator;
  20410. })();
  20411. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20412. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20413. var Internals = BABYLON.Internals;
  20414. })(BABYLON || (BABYLON = {}));
  20415. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20416. var BABYLON;
  20417. (function (BABYLON) {
  20418. var PostProcessRenderPass = (function () {
  20419. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20420. this._enabled = true;
  20421. this._refCount = 0;
  20422. this._name = name;
  20423. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20424. this.setRenderList(renderList);
  20425. this._renderTexture.onBeforeRender = beforeRender;
  20426. this._renderTexture.onAfterRender = afterRender;
  20427. this._scene = scene;
  20428. this._renderList = renderList;
  20429. }
  20430. // private
  20431. PostProcessRenderPass.prototype._incRefCount = function () {
  20432. if (this._refCount === 0) {
  20433. this._scene.customRenderTargets.push(this._renderTexture);
  20434. }
  20435. return ++this._refCount;
  20436. };
  20437. PostProcessRenderPass.prototype._decRefCount = function () {
  20438. this._refCount--;
  20439. if (this._refCount <= 0) {
  20440. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20441. }
  20442. return this._refCount;
  20443. };
  20444. PostProcessRenderPass.prototype._update = function () {
  20445. this.setRenderList(this._renderList);
  20446. };
  20447. // public
  20448. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20449. this._renderTexture.renderList = renderList;
  20450. };
  20451. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20452. return this._renderTexture;
  20453. };
  20454. return PostProcessRenderPass;
  20455. })();
  20456. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20457. })(BABYLON || (BABYLON = {}));
  20458. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20459. var BABYLON;
  20460. (function (BABYLON) {
  20461. var PostProcessRenderEffect = (function () {
  20462. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20463. this._engine = engine;
  20464. this._name = name;
  20465. this._singleInstance = singleInstance || true;
  20466. this._getPostProcess = getPostProcess;
  20467. this._cameras = [];
  20468. this._indicesForCamera = [];
  20469. this._postProcesses = {};
  20470. this._renderPasses = {};
  20471. this._renderEffectAsPasses = {};
  20472. }
  20473. PostProcessRenderEffect.prototype._update = function () {
  20474. for (var renderPassName in this._renderPasses) {
  20475. this._renderPasses[renderPassName]._update();
  20476. }
  20477. };
  20478. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20479. this._renderPasses[renderPass._name] = renderPass;
  20480. this._linkParameters();
  20481. };
  20482. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20483. delete this._renderPasses[renderPass._name];
  20484. this._linkParameters();
  20485. };
  20486. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20487. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20488. this._linkParameters();
  20489. };
  20490. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20491. for (var renderPassName in this._renderPasses) {
  20492. if (renderPassName === passName) {
  20493. return this._renderPasses[passName];
  20494. }
  20495. }
  20496. };
  20497. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20498. this._renderPasses = {};
  20499. this._linkParameters();
  20500. };
  20501. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20502. var cameraKey;
  20503. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20504. for (var i = 0; i < _cam.length; i++) {
  20505. var camera = _cam[i];
  20506. var cameraName = camera.name;
  20507. if (this._singleInstance) {
  20508. cameraKey = 0;
  20509. } else {
  20510. cameraKey = cameraName;
  20511. }
  20512. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20513. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20514. if (!this._indicesForCamera[cameraName]) {
  20515. this._indicesForCamera[cameraName] = [];
  20516. }
  20517. this._indicesForCamera[cameraName].push(index);
  20518. if (this._cameras.indexOf(camera) === -1) {
  20519. this._cameras[cameraName] = camera;
  20520. }
  20521. for (var passName in this._renderPasses) {
  20522. this._renderPasses[passName]._incRefCount();
  20523. }
  20524. }
  20525. this._linkParameters();
  20526. };
  20527. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20528. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20529. for (var i = 0; i < _cam.length; i++) {
  20530. var camera = _cam[i];
  20531. var cameraName = camera.name;
  20532. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20533. var index = this._cameras.indexOf(cameraName);
  20534. this._indicesForCamera.splice(index, 1);
  20535. this._cameras.splice(index, 1);
  20536. for (var passName in this._renderPasses) {
  20537. this._renderPasses[passName]._decRefCount();
  20538. }
  20539. }
  20540. };
  20541. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20542. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20543. for (var i = 0; i < _cam.length; i++) {
  20544. var camera = _cam[i];
  20545. var cameraName = camera.name;
  20546. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20547. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20548. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20549. }
  20550. }
  20551. for (var passName in this._renderPasses) {
  20552. this._renderPasses[passName]._incRefCount();
  20553. }
  20554. }
  20555. };
  20556. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20557. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20558. for (var i = 0; i < _cam.length; i++) {
  20559. var camera = _cam[i];
  20560. var cameraName = camera.Name;
  20561. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20562. for (var passName in this._renderPasses) {
  20563. this._renderPasses[passName]._decRefCount();
  20564. }
  20565. }
  20566. };
  20567. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20568. if (this._singleInstance) {
  20569. return this._postProcesses[0];
  20570. } else {
  20571. return this._postProcesses[camera.name];
  20572. }
  20573. };
  20574. PostProcessRenderEffect.prototype._linkParameters = function () {
  20575. var _this = this;
  20576. for (var index in this._postProcesses) {
  20577. if (this.applyParameters) {
  20578. this.applyParameters(this._postProcesses[index]);
  20579. }
  20580. this._postProcesses[index].onBeforeRender = function (effect) {
  20581. _this._linkTextures(effect);
  20582. };
  20583. }
  20584. };
  20585. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20586. for (var renderPassName in this._renderPasses) {
  20587. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20588. }
  20589. for (var renderEffectName in this._renderEffectAsPasses) {
  20590. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20591. }
  20592. };
  20593. return PostProcessRenderEffect;
  20594. })();
  20595. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20596. })(BABYLON || (BABYLON = {}));
  20597. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20598. var BABYLON;
  20599. (function (BABYLON) {
  20600. var PostProcessRenderPipeline = (function () {
  20601. function PostProcessRenderPipeline(engine, name) {
  20602. this._engine = engine;
  20603. this._name = name;
  20604. this._renderEffects = {};
  20605. this._renderEffectsForIsolatedPass = {};
  20606. this._cameras = [];
  20607. }
  20608. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20609. this._renderEffects[renderEffect._name] = renderEffect;
  20610. };
  20611. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20612. var renderEffects = this._renderEffects[renderEffectName];
  20613. if (!renderEffects) {
  20614. return;
  20615. }
  20616. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20617. };
  20618. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20619. var renderEffects = this._renderEffects[renderEffectName];
  20620. if (!renderEffects) {
  20621. return;
  20622. }
  20623. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20624. };
  20625. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20626. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20627. var indicesToDelete = [];
  20628. for (var i = 0; i < _cam.length; i++) {
  20629. var camera = _cam[i];
  20630. var cameraName = camera.name;
  20631. if (this._cameras.indexOf(camera) === -1) {
  20632. this._cameras[cameraName] = camera;
  20633. } else if (unique) {
  20634. indicesToDelete.push(i);
  20635. }
  20636. }
  20637. for (var i = 0; i < indicesToDelete.length; i++) {
  20638. cameras.splice(indicesToDelete[i], 1);
  20639. }
  20640. for (var renderEffectName in this._renderEffects) {
  20641. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20642. }
  20643. };
  20644. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20646. for (var renderEffectName in this._renderEffects) {
  20647. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20648. }
  20649. for (var i = 0; i < _cam.length; i++) {
  20650. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20651. }
  20652. };
  20653. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20654. var _this = this;
  20655. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20656. var pass = null;
  20657. for (var renderEffectName in this._renderEffects) {
  20658. pass = this._renderEffects[renderEffectName].getPass(passName);
  20659. if (pass != null) {
  20660. break;
  20661. }
  20662. }
  20663. if (pass === null) {
  20664. return;
  20665. }
  20666. for (var renderEffectName in this._renderEffects) {
  20667. this._renderEffects[renderEffectName]._disable(_cam);
  20668. }
  20669. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20670. for (var i = 0; i < _cam.length; i++) {
  20671. var camera = _cam[i];
  20672. var cameraName = camera.name;
  20673. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20674. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20675. });
  20676. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20677. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20678. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20679. }
  20680. };
  20681. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20682. var _this = this;
  20683. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20684. for (var i = 0; i < _cam.length; i++) {
  20685. var camera = _cam[i];
  20686. var cameraName = camera.name;
  20687. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20688. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20689. });
  20690. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20691. }
  20692. for (var renderEffectName in this._renderEffects) {
  20693. this._renderEffects[renderEffectName]._enable(_cam);
  20694. }
  20695. };
  20696. PostProcessRenderPipeline.prototype._update = function () {
  20697. for (var renderEffectName in this._renderEffects) {
  20698. this._renderEffects[renderEffectName]._update();
  20699. }
  20700. for (var i = 0; i < this._cameras.length; i++) {
  20701. var cameraName = this._cameras[i].name;
  20702. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20703. this._renderEffectsForIsolatedPass[cameraName]._update();
  20704. }
  20705. }
  20706. };
  20707. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20708. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20709. return PostProcessRenderPipeline;
  20710. })();
  20711. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20712. })(BABYLON || (BABYLON = {}));
  20713. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20714. var BABYLON;
  20715. (function (BABYLON) {
  20716. var PostProcessRenderPipelineManager = (function () {
  20717. function PostProcessRenderPipelineManager() {
  20718. this._renderPipelines = {};
  20719. }
  20720. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20721. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20722. };
  20723. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20724. var renderPipeline = this._renderPipelines[renderPipelineName];
  20725. if (!renderPipeline) {
  20726. return;
  20727. }
  20728. renderPipeline._attachCameras(cameras, unique);
  20729. };
  20730. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20731. var renderPipeline = this._renderPipelines[renderPipelineName];
  20732. if (!renderPipeline) {
  20733. return;
  20734. }
  20735. renderPipeline._detachCameras(cameras);
  20736. };
  20737. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20738. var renderPipeline = this._renderPipelines[renderPipelineName];
  20739. if (!renderPipeline) {
  20740. return;
  20741. }
  20742. renderPipeline._enableEffect(renderEffectName, cameras);
  20743. };
  20744. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20745. var renderPipeline = this._renderPipelines[renderPipelineName];
  20746. if (!renderPipeline) {
  20747. return;
  20748. }
  20749. renderPipeline._disableEffect(renderEffectName, cameras);
  20750. };
  20751. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20752. var renderPipeline = this._renderPipelines[renderPipelineName];
  20753. if (!renderPipeline) {
  20754. return;
  20755. }
  20756. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20757. };
  20758. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20759. var renderPipeline = this._renderPipelines[renderPipelineName];
  20760. if (!renderPipeline) {
  20761. return;
  20762. }
  20763. renderPipeline._disableDisplayOnlyPass(cameras);
  20764. };
  20765. PostProcessRenderPipelineManager.prototype.update = function () {
  20766. for (var renderPipelineName in this._renderPipelines) {
  20767. this._renderPipelines[renderPipelineName]._update();
  20768. }
  20769. };
  20770. return PostProcessRenderPipelineManager;
  20771. })();
  20772. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20773. })(BABYLON || (BABYLON = {}));
  20774. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20775. var BABYLON;
  20776. (function (BABYLON) {
  20777. var DisplayPassPostProcess = (function (_super) {
  20778. __extends(DisplayPassPostProcess, _super);
  20779. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20780. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20781. }
  20782. return DisplayPassPostProcess;
  20783. })(BABYLON.PostProcess);
  20784. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20785. })(BABYLON || (BABYLON = {}));
  20786. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20787. var BABYLON;
  20788. (function (BABYLON) {
  20789. var BoundingBoxRenderer = (function () {
  20790. function BoundingBoxRenderer(scene) {
  20791. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20792. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20793. this.showBackLines = true;
  20794. this.renderList = new BABYLON.SmartArray(32);
  20795. this._scene = scene;
  20796. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20797. attributes: ["position"],
  20798. uniforms: ["worldViewProjection", "color"]
  20799. });
  20800. var engine = this._scene.getEngine();
  20801. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20802. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20803. 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]);
  20804. }
  20805. BoundingBoxRenderer.prototype.reset = function () {
  20806. this.renderList.reset();
  20807. };
  20808. BoundingBoxRenderer.prototype.render = function () {
  20809. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20810. return;
  20811. }
  20812. var engine = this._scene.getEngine();
  20813. engine.setDepthWrite(false);
  20814. this._colorShader._preBind();
  20815. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20816. var boundingBox = this.renderList.data[boundingBoxIndex];
  20817. var min = boundingBox.minimum;
  20818. var max = boundingBox.maximum;
  20819. var diff = max.subtract(min);
  20820. var median = min.add(diff.scale(0.5));
  20821. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20822. // VBOs
  20823. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20824. if (this.showBackLines) {
  20825. // Back
  20826. engine.setDepthFunctionToGreaterOrEqual();
  20827. this._scene.resetCachedMaterial();
  20828. this._colorShader.setColor4("color", this.backColor.toColor4());
  20829. this._colorShader.bind(worldMatrix);
  20830. // Draw order
  20831. engine.draw(false, 0, 24);
  20832. }
  20833. // Front
  20834. engine.setDepthFunctionToLess();
  20835. this._scene.resetCachedMaterial();
  20836. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20837. this._colorShader.bind(worldMatrix);
  20838. // Draw order
  20839. engine.draw(false, 0, 24);
  20840. }
  20841. this._colorShader.unbind();
  20842. engine.setDepthFunctionToLessOrEqual();
  20843. engine.setDepthWrite(true);
  20844. };
  20845. BoundingBoxRenderer.prototype.dispose = function () {
  20846. this._colorShader.dispose();
  20847. this._vb.dispose();
  20848. this._scene.getEngine()._releaseBuffer(this._ib);
  20849. };
  20850. return BoundingBoxRenderer;
  20851. })();
  20852. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20853. })(BABYLON || (BABYLON = {}));
  20854. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20855. /**
  20856. * Based on jsTGALoader - Javascript loader for TGA file
  20857. * By Vincent Thibault
  20858. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20859. */
  20860. var BABYLON;
  20861. (function (BABYLON) {
  20862. (function (Internals) {
  20863. var TGATools = (function () {
  20864. function TGATools() {
  20865. }
  20866. TGATools.GetTGAHeader = function (data) {
  20867. var offset = 0;
  20868. var header = {
  20869. id_length: data[offset++],
  20870. colormap_type: data[offset++],
  20871. image_type: data[offset++],
  20872. colormap_index: data[offset++] | data[offset++] << 8,
  20873. colormap_length: data[offset++] | data[offset++] << 8,
  20874. colormap_size: data[offset++],
  20875. origin: [
  20876. data[offset++] | data[offset++] << 8,
  20877. data[offset++] | data[offset++] << 8
  20878. ],
  20879. width: data[offset++] | data[offset++] << 8,
  20880. height: data[offset++] | data[offset++] << 8,
  20881. pixel_size: data[offset++],
  20882. flags: data[offset++]
  20883. };
  20884. return header;
  20885. };
  20886. TGATools.UploadContent = function (gl, data) {
  20887. // Not enough data to contain header ?
  20888. if (data.length < 19) {
  20889. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20890. return;
  20891. }
  20892. // Read Header
  20893. var offset = 18;
  20894. var header = TGATools.GetTGAHeader(data);
  20895. // Assume it's a valid Targa file.
  20896. if (header.id_length + offset > data.length) {
  20897. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20898. return;
  20899. }
  20900. // Skip not needed data
  20901. offset += header.id_length;
  20902. var use_rle = false;
  20903. var use_pal = false;
  20904. var use_rgb = false;
  20905. var use_grey = false;
  20906. switch (header.image_type) {
  20907. case TGATools._TYPE_RLE_INDEXED:
  20908. use_rle = true;
  20909. case TGATools._TYPE_INDEXED:
  20910. use_pal = true;
  20911. break;
  20912. case TGATools._TYPE_RLE_RGB:
  20913. use_rle = true;
  20914. case TGATools._TYPE_RGB:
  20915. use_rgb = true;
  20916. break;
  20917. case TGATools._TYPE_RLE_GREY:
  20918. use_rle = true;
  20919. case TGATools._TYPE_GREY:
  20920. use_grey = true;
  20921. break;
  20922. }
  20923. var pixel_data;
  20924. var numAlphaBits = header.flags & 0xf;
  20925. var pixel_size = header.pixel_size >> 3;
  20926. var pixel_total = header.width * header.height * pixel_size;
  20927. // Read palettes
  20928. var palettes;
  20929. if (use_pal) {
  20930. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20931. }
  20932. // Read LRE
  20933. if (use_rle) {
  20934. pixel_data = new Uint8Array(pixel_total);
  20935. var c, count, i;
  20936. var localOffset = 0;
  20937. var pixels = new Uint8Array(pixel_size);
  20938. while (offset < pixel_total && localOffset < pixel_total) {
  20939. c = data[offset++];
  20940. count = (c & 0x7f) + 1;
  20941. // RLE pixels
  20942. if (c & 0x80) {
  20943. for (i = 0; i < pixel_size; ++i) {
  20944. pixels[i] = data[offset++];
  20945. }
  20946. for (i = 0; i < count; ++i) {
  20947. pixel_data.set(pixels, localOffset + i * pixel_size);
  20948. }
  20949. localOffset += pixel_size * count;
  20950. } else {
  20951. count *= pixel_size;
  20952. for (i = 0; i < count; ++i) {
  20953. pixel_data[localOffset + i] = data[offset++];
  20954. }
  20955. localOffset += count;
  20956. }
  20957. }
  20958. } else {
  20959. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20960. }
  20961. // Load to texture
  20962. var x_start, y_start, x_step, y_step, y_end, x_end;
  20963. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20964. default:
  20965. case TGATools._ORIGIN_UL:
  20966. x_start = 0;
  20967. x_step = 1;
  20968. x_end = header.width;
  20969. y_start = 0;
  20970. y_step = 1;
  20971. y_end = header.height;
  20972. break;
  20973. case TGATools._ORIGIN_BL:
  20974. x_start = 0;
  20975. x_step = 1;
  20976. x_end = header.width;
  20977. y_start = header.height - 1;
  20978. y_step = -1;
  20979. y_end = -1;
  20980. break;
  20981. case TGATools._ORIGIN_UR:
  20982. x_start = header.width - 1;
  20983. x_step = -1;
  20984. x_end = -1;
  20985. y_start = 0;
  20986. y_step = 1;
  20987. y_end = header.height;
  20988. break;
  20989. case TGATools._ORIGIN_BR:
  20990. x_start = header.width - 1;
  20991. x_step = -1;
  20992. x_end = -1;
  20993. y_start = header.height - 1;
  20994. y_step = -1;
  20995. y_end = -1;
  20996. break;
  20997. }
  20998. // Load the specify method
  20999. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21000. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21001. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21002. };
  21003. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21004. var image = pixel_data, colormap = palettes;
  21005. var width = header.width, height = header.height;
  21006. var color, i = 0, x, y;
  21007. var imageData = new Uint8Array(width * height * 4);
  21008. for (y = y_start; y !== y_end; y += y_step) {
  21009. for (x = x_start; x !== x_end; x += x_step, i++) {
  21010. color = image[i];
  21011. imageData[(x + width * y) * 4 + 3] = 255;
  21012. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21013. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21014. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21015. }
  21016. }
  21017. return imageData;
  21018. };
  21019. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21020. var image = pixel_data;
  21021. var width = header.width, height = header.height;
  21022. var color, i = 0, x, y;
  21023. var imageData = new Uint8Array(width * height * 4);
  21024. for (y = y_start; y !== y_end; y += y_step) {
  21025. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21026. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21027. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21028. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21029. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21030. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21031. }
  21032. }
  21033. return imageData;
  21034. };
  21035. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21036. var image = pixel_data;
  21037. var width = header.width, height = header.height;
  21038. var i = 0, x, y;
  21039. var imageData = new Uint8Array(width * height * 4);
  21040. for (y = y_start; y !== y_end; y += y_step) {
  21041. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21042. imageData[(x + width * y) * 4 + 3] = 255;
  21043. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21044. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21045. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21046. }
  21047. }
  21048. return imageData;
  21049. };
  21050. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21051. var image = pixel_data;
  21052. var width = header.width, height = header.height;
  21053. var i = 0, x, y;
  21054. var imageData = new Uint8Array(width * height * 4);
  21055. for (y = y_start; y !== y_end; y += y_step) {
  21056. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21057. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21058. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21059. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21060. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21061. }
  21062. }
  21063. return imageData;
  21064. };
  21065. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21066. var image = pixel_data;
  21067. var width = header.width, height = header.height;
  21068. var color, i = 0, x, y;
  21069. var imageData = new Uint8Array(width * height * 4);
  21070. for (y = y_start; y !== y_end; y += y_step) {
  21071. for (x = x_start; x !== x_end; x += x_step, i++) {
  21072. color = image[i];
  21073. imageData[(x + width * y) * 4 + 0] = color;
  21074. imageData[(x + width * y) * 4 + 1] = color;
  21075. imageData[(x + width * y) * 4 + 2] = color;
  21076. imageData[(x + width * y) * 4 + 3] = 255;
  21077. }
  21078. }
  21079. return imageData;
  21080. };
  21081. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21082. var image = pixel_data;
  21083. var width = header.width, height = header.height;
  21084. var i = 0, x, y;
  21085. var imageData = new Uint8Array(width * height * 4);
  21086. for (y = y_start; y !== y_end; y += y_step) {
  21087. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21088. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21089. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21090. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21091. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21092. }
  21093. }
  21094. return imageData;
  21095. };
  21096. TGATools._TYPE_NO_DATA = 0;
  21097. TGATools._TYPE_INDEXED = 1;
  21098. TGATools._TYPE_RGB = 2;
  21099. TGATools._TYPE_GREY = 3;
  21100. TGATools._TYPE_RLE_INDEXED = 9;
  21101. TGATools._TYPE_RLE_RGB = 10;
  21102. TGATools._TYPE_RLE_GREY = 11;
  21103. TGATools._ORIGIN_MASK = 0x30;
  21104. TGATools._ORIGIN_SHIFT = 0x04;
  21105. TGATools._ORIGIN_BL = 0x00;
  21106. TGATools._ORIGIN_BR = 0x01;
  21107. TGATools._ORIGIN_UL = 0x02;
  21108. TGATools._ORIGIN_UR = 0x03;
  21109. return TGATools;
  21110. })();
  21111. Internals.TGATools = TGATools;
  21112. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21113. var Internals = BABYLON.Internals;
  21114. })(BABYLON || (BABYLON = {}));
  21115. //# sourceMappingURL=babylon.tools.tga.js.map
  21116. var BABYLON;
  21117. (function (BABYLON) {
  21118. (function (Internals) {
  21119. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21120. // All values and structures referenced from:
  21121. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21122. var DDS_MAGIC = 0x20534444;
  21123. 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;
  21124. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21125. 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;
  21126. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21127. function FourCCToInt32(value) {
  21128. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21129. }
  21130. function Int32ToFourCC(value) {
  21131. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21132. }
  21133. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21134. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21135. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21136. var headerLengthInt = 31;
  21137. // Offsets into the header array
  21138. var off_magic = 0;
  21139. var off_size = 1;
  21140. var off_flags = 2;
  21141. var off_height = 3;
  21142. var off_width = 4;
  21143. var off_mipmapCount = 7;
  21144. var off_pfFlags = 20;
  21145. var off_pfFourCC = 21;
  21146. var off_RGBbpp = 22;
  21147. var off_RMask = 23;
  21148. var off_GMask = 24;
  21149. var off_BMask = 25;
  21150. var off_AMask = 26;
  21151. var off_caps1 = 27;
  21152. var off_caps2 = 28;
  21153. ;
  21154. var DDSTools = (function () {
  21155. function DDSTools() {
  21156. }
  21157. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21158. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21159. var mipmapCount = 1;
  21160. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21161. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21162. }
  21163. return {
  21164. width: header[off_width],
  21165. height: header[off_height],
  21166. mipmapCount: mipmapCount,
  21167. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21168. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21169. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21170. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21171. };
  21172. };
  21173. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21174. var byteArray = new Uint8Array(dataLength);
  21175. var srcData = new Uint8Array(arrayBuffer);
  21176. var index = 0;
  21177. for (var y = height - 1; y >= 0; y--) {
  21178. for (var x = 0; x < width; x++) {
  21179. var srcPos = dataOffset + (x + y * width) * 4;
  21180. byteArray[index + 2] = srcData[srcPos];
  21181. byteArray[index + 1] = srcData[srcPos + 1];
  21182. byteArray[index] = srcData[srcPos + 2];
  21183. byteArray[index + 3] = srcData[srcPos + 3];
  21184. index += 4;
  21185. }
  21186. }
  21187. return byteArray;
  21188. };
  21189. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21190. var byteArray = new Uint8Array(dataLength);
  21191. var srcData = new Uint8Array(arrayBuffer);
  21192. var index = 0;
  21193. for (var y = height - 1; y >= 0; y--) {
  21194. for (var x = 0; x < width; x++) {
  21195. var srcPos = dataOffset + (x + y * width) * 3;
  21196. byteArray[index + 2] = srcData[srcPos];
  21197. byteArray[index + 1] = srcData[srcPos + 1];
  21198. byteArray[index] = srcData[srcPos + 2];
  21199. index += 3;
  21200. }
  21201. }
  21202. return byteArray;
  21203. };
  21204. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21205. var byteArray = new Uint8Array(dataLength);
  21206. var srcData = new Uint8Array(arrayBuffer);
  21207. var index = 0;
  21208. for (var y = height - 1; y >= 0; y--) {
  21209. for (var x = 0; x < width; x++) {
  21210. var srcPos = dataOffset + (x + y * width);
  21211. byteArray[index] = srcData[srcPos];
  21212. index++;
  21213. }
  21214. }
  21215. return byteArray;
  21216. };
  21217. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21218. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21219. if (header[off_magic] != DDS_MAGIC) {
  21220. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21221. return;
  21222. }
  21223. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21224. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21225. return;
  21226. }
  21227. if (info.isFourCC) {
  21228. fourCC = header[off_pfFourCC];
  21229. switch (fourCC) {
  21230. case FOURCC_DXT1:
  21231. blockBytes = 8;
  21232. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21233. break;
  21234. case FOURCC_DXT3:
  21235. blockBytes = 16;
  21236. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21237. break;
  21238. case FOURCC_DXT5:
  21239. blockBytes = 16;
  21240. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21241. break;
  21242. default:
  21243. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21244. return;
  21245. }
  21246. }
  21247. mipmapCount = 1;
  21248. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21249. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21250. }
  21251. var bpp = header[off_RGBbpp];
  21252. for (var face = 0; face < faces; face++) {
  21253. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21254. width = header[off_width];
  21255. height = header[off_height];
  21256. dataOffset = header[off_size] + 4;
  21257. for (i = 0; i < mipmapCount; ++i) {
  21258. if (info.isRGB) {
  21259. if (bpp == 24) {
  21260. dataLength = width * height * 3;
  21261. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21262. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21263. } else {
  21264. dataLength = width * height * 4;
  21265. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21266. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21267. }
  21268. } else if (info.isLuminance) {
  21269. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21270. var unpaddedRowSize = width;
  21271. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21272. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21273. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21274. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21275. } else {
  21276. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21277. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21278. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21279. }
  21280. dataOffset += dataLength;
  21281. width *= 0.5;
  21282. height *= 0.5;
  21283. width = Math.max(1.0, width);
  21284. height = Math.max(1.0, height);
  21285. }
  21286. }
  21287. };
  21288. return DDSTools;
  21289. })();
  21290. Internals.DDSTools = DDSTools;
  21291. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21292. var Internals = BABYLON.Internals;
  21293. })(BABYLON || (BABYLON = {}));
  21294. //# sourceMappingURL=babylon.tools.dds.js.map
  21295. var BABYLON;
  21296. (function (BABYLON) {
  21297. var SmartArray = (function () {
  21298. function SmartArray(capacity) {
  21299. this.length = 0;
  21300. this._duplicateId = 0;
  21301. this.data = new Array(capacity);
  21302. this._id = SmartArray._GlobalId++;
  21303. }
  21304. SmartArray.prototype.push = function (value) {
  21305. this.data[this.length++] = value;
  21306. if (this.length > this.data.length) {
  21307. this.data.length *= 2;
  21308. }
  21309. if (!value.__smartArrayFlags) {
  21310. value.__smartArrayFlags = {};
  21311. }
  21312. value.__smartArrayFlags[this._id] = this._duplicateId;
  21313. };
  21314. SmartArray.prototype.pushNoDuplicate = function (value) {
  21315. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21316. return;
  21317. }
  21318. this.push(value);
  21319. };
  21320. SmartArray.prototype.sort = function (compareFn) {
  21321. this.data.sort(compareFn);
  21322. };
  21323. SmartArray.prototype.reset = function () {
  21324. this.length = 0;
  21325. this._duplicateId++;
  21326. };
  21327. SmartArray.prototype.concat = function (array) {
  21328. if (array.length === 0) {
  21329. return;
  21330. }
  21331. if (this.length + array.length > this.data.length) {
  21332. this.data.length = (this.length + array.length) * 2;
  21333. }
  21334. for (var index = 0; index < array.length; index++) {
  21335. this.data[this.length++] = (array.data || array)[index];
  21336. }
  21337. };
  21338. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21339. if (array.length === 0) {
  21340. return;
  21341. }
  21342. if (this.length + array.length > this.data.length) {
  21343. this.data.length = (this.length + array.length) * 2;
  21344. }
  21345. for (var index = 0; index < array.length; index++) {
  21346. var item = (array.data || array)[index];
  21347. this.pushNoDuplicate(item);
  21348. }
  21349. };
  21350. SmartArray.prototype.indexOf = function (value) {
  21351. var position = this.data.indexOf(value);
  21352. if (position >= this.length) {
  21353. return -1;
  21354. }
  21355. return position;
  21356. };
  21357. SmartArray._GlobalId = 0;
  21358. return SmartArray;
  21359. })();
  21360. BABYLON.SmartArray = SmartArray;
  21361. })(BABYLON || (BABYLON = {}));
  21362. //# sourceMappingURL=babylon.smartArray.js.map
  21363. var BABYLON;
  21364. (function (BABYLON) {
  21365. var CannonJSPlugin = (function () {
  21366. function CannonJSPlugin() {
  21367. this._registeredMeshes = [];
  21368. this._physicsMaterials = [];
  21369. this.updateBodyPosition = function (mesh) {
  21370. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21371. var registeredMesh = this._registeredMeshes[index];
  21372. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21373. var body = registeredMesh.body;
  21374. var center = mesh.getBoundingInfo().boundingBox.center;
  21375. body.position.set(center.x, center.z, center.y);
  21376. body.quaternion.x = mesh.rotationQuaternion.x;
  21377. body.quaternion.z = mesh.rotationQuaternion.y;
  21378. body.quaternion.y = mesh.rotationQuaternion.z;
  21379. body.quaternion.w = -mesh.rotationQuaternion.w;
  21380. return;
  21381. }
  21382. }
  21383. };
  21384. }
  21385. CannonJSPlugin.prototype.initialize = function (iterations) {
  21386. if (typeof iterations === "undefined") { iterations = 10; }
  21387. this._world = new CANNON.World();
  21388. this._world.broadphase = new CANNON.NaiveBroadphase();
  21389. this._world.solver.iterations = iterations;
  21390. };
  21391. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21392. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21393. };
  21394. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21395. this._world.step(delta);
  21396. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21397. var registeredMesh = this._registeredMeshes[index];
  21398. if (registeredMesh.isChild) {
  21399. continue;
  21400. }
  21401. // Body position
  21402. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21403. var deltaPos = registeredMesh.delta;
  21404. if (deltaPos) {
  21405. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21406. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21407. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21408. } else {
  21409. registeredMesh.mesh.position.x = bodyX;
  21410. registeredMesh.mesh.position.y = bodyZ;
  21411. registeredMesh.mesh.position.z = bodyY;
  21412. }
  21413. if (!registeredMesh.mesh.rotationQuaternion) {
  21414. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21415. }
  21416. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21417. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21418. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21419. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21420. }
  21421. };
  21422. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21423. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21424. };
  21425. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21426. this.unregisterMesh(mesh);
  21427. mesh.computeWorldMatrix(true);
  21428. switch (impostor) {
  21429. case BABYLON.PhysicsEngine.SphereImpostor:
  21430. var bbox = mesh.getBoundingInfo().boundingBox;
  21431. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21432. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21433. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21434. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21435. case BABYLON.PhysicsEngine.BoxImpostor:
  21436. bbox = mesh.getBoundingInfo().boundingBox;
  21437. var min = bbox.minimumWorld;
  21438. var max = bbox.maximumWorld;
  21439. var box = max.subtract(min).scale(0.5);
  21440. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21441. case BABYLON.PhysicsEngine.PlaneImpostor:
  21442. return this._createPlane(mesh, options);
  21443. case BABYLON.PhysicsEngine.MeshImpostor:
  21444. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21445. var rawFaces = mesh.getIndices();
  21446. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21447. }
  21448. return null;
  21449. };
  21450. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21451. var shape = new CANNON.Sphere(radius);
  21452. if (!options) {
  21453. return shape;
  21454. }
  21455. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21456. };
  21457. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21458. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21459. if (!options) {
  21460. return shape;
  21461. }
  21462. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21463. };
  21464. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21465. var shape = new CANNON.Plane();
  21466. if (!options) {
  21467. return shape;
  21468. }
  21469. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21470. };
  21471. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21472. var verts = [], faces = [];
  21473. mesh.computeWorldMatrix(true);
  21474. for (var i = 0; i < rawVerts.length; i += 3) {
  21475. var transformed = BABYLON.Vector3.Zero();
  21476. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21477. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21478. }
  21479. for (var j = 0; j < rawFaces.length; j += 3) {
  21480. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21481. }
  21482. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21483. if (!options) {
  21484. return shape;
  21485. }
  21486. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21487. };
  21488. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21489. var index;
  21490. var mat;
  21491. for (index = 0; index < this._physicsMaterials.length; index++) {
  21492. mat = this._physicsMaterials[index];
  21493. if (mat.friction === friction && mat.restitution === restitution) {
  21494. return mat;
  21495. }
  21496. }
  21497. var currentMat = new CANNON.Material();
  21498. currentMat.friction = friction;
  21499. currentMat.restitution = restitution;
  21500. this._physicsMaterials.push(currentMat);
  21501. for (index = 0; index < this._physicsMaterials.length; index++) {
  21502. mat = this._physicsMaterials[index];
  21503. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21504. contactMaterial.contactEquationStiffness = 1e10;
  21505. contactMaterial.contactEquationRegularizationTime = 10;
  21506. this._world.addContactMaterial(contactMaterial);
  21507. }
  21508. return currentMat;
  21509. };
  21510. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21511. var initialRotation = null;
  21512. if (mesh.rotationQuaternion) {
  21513. initialRotation = mesh.rotationQuaternion.clone();
  21514. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21515. }
  21516. // The delta between the mesh position and the mesh bounding box center
  21517. var bbox = mesh.getBoundingInfo().boundingBox;
  21518. var deltaPosition = mesh.position.subtract(bbox.center);
  21519. var material = this._addMaterial(friction, restitution);
  21520. var body = new CANNON.RigidBody(mass, shape, material);
  21521. if (initialRotation) {
  21522. body.quaternion.x = initialRotation.x;
  21523. body.quaternion.z = initialRotation.y;
  21524. body.quaternion.y = initialRotation.z;
  21525. body.quaternion.w = -initialRotation.w;
  21526. }
  21527. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21528. this._world.add(body);
  21529. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21530. return body;
  21531. };
  21532. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21533. var compoundShape = new CANNON.Compound();
  21534. for (var index = 0; index < parts.length; index++) {
  21535. var mesh = parts[index].mesh;
  21536. var shape = this.registerMesh(mesh, parts[index].impostor);
  21537. if (index == 0) {
  21538. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21539. } else {
  21540. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21541. }
  21542. }
  21543. var initialMesh = parts[0].mesh;
  21544. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21545. body.parts = parts;
  21546. return body;
  21547. };
  21548. CannonJSPlugin.prototype._unbindBody = function (body) {
  21549. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21550. var registeredMesh = this._registeredMeshes[index];
  21551. if (registeredMesh.body === body) {
  21552. registeredMesh.body = null;
  21553. registeredMesh.delta = 0;
  21554. }
  21555. }
  21556. };
  21557. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21558. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21559. var registeredMesh = this._registeredMeshes[index];
  21560. if (registeredMesh.mesh === mesh) {
  21561. // Remove body
  21562. if (registeredMesh.body) {
  21563. this._world.remove(registeredMesh.body);
  21564. this._unbindBody(registeredMesh.body);
  21565. }
  21566. this._registeredMeshes.splice(index, 1);
  21567. return;
  21568. }
  21569. }
  21570. };
  21571. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21572. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21573. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21574. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21575. var registeredMesh = this._registeredMeshes[index];
  21576. if (registeredMesh.mesh === mesh) {
  21577. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21578. return;
  21579. }
  21580. }
  21581. };
  21582. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21583. var body1 = null, body2 = null;
  21584. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21585. var registeredMesh = this._registeredMeshes[index];
  21586. if (registeredMesh.mesh === mesh1) {
  21587. body1 = registeredMesh.body;
  21588. } else if (registeredMesh.mesh === mesh2) {
  21589. body2 = registeredMesh.body;
  21590. }
  21591. }
  21592. if (!body1 || !body2) {
  21593. return false;
  21594. }
  21595. 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));
  21596. this._world.addConstraint(constraint);
  21597. return true;
  21598. };
  21599. CannonJSPlugin.prototype.dispose = function () {
  21600. while (this._registeredMeshes.length) {
  21601. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21602. }
  21603. };
  21604. CannonJSPlugin.prototype.isSupported = function () {
  21605. return window.CANNON !== undefined;
  21606. };
  21607. return CannonJSPlugin;
  21608. })();
  21609. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21610. })(BABYLON || (BABYLON = {}));
  21611. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21612. var BABYLON;
  21613. (function (BABYLON) {
  21614. var Condition = (function () {
  21615. function Condition(actionManager) {
  21616. this._actionManager = actionManager;
  21617. }
  21618. Condition.prototype.isValid = function () {
  21619. return true;
  21620. };
  21621. Condition.prototype._getProperty = function (propertyPath) {
  21622. return this._actionManager._getProperty(propertyPath);
  21623. };
  21624. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21625. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21626. };
  21627. return Condition;
  21628. })();
  21629. BABYLON.Condition = Condition;
  21630. var ValueCondition = (function (_super) {
  21631. __extends(ValueCondition, _super);
  21632. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21633. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21634. _super.call(this, actionManager);
  21635. this.propertyPath = propertyPath;
  21636. this.value = value;
  21637. this.operator = operator;
  21638. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21639. this._property = this._getProperty(this.propertyPath);
  21640. }
  21641. Object.defineProperty(ValueCondition, "IsEqual", {
  21642. get: function () {
  21643. return ValueCondition._IsEqual;
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(ValueCondition, "IsDifferent", {
  21649. get: function () {
  21650. return ValueCondition._IsDifferent;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(ValueCondition, "IsGreater", {
  21656. get: function () {
  21657. return ValueCondition._IsGreater;
  21658. },
  21659. enumerable: true,
  21660. configurable: true
  21661. });
  21662. Object.defineProperty(ValueCondition, "IsLesser", {
  21663. get: function () {
  21664. return ValueCondition._IsLesser;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. // Methods
  21670. ValueCondition.prototype.isValid = function () {
  21671. switch (this.operator) {
  21672. case ValueCondition.IsGreater:
  21673. return this._target[this._property] > this.value;
  21674. case ValueCondition.IsLesser:
  21675. return this._target[this._property] < this.value;
  21676. case ValueCondition.IsEqual:
  21677. case ValueCondition.IsDifferent:
  21678. var check;
  21679. if (this.value.equals) {
  21680. check = this.value.equals(this._target[this._property]);
  21681. } else {
  21682. check = this.value === this._target[this._property];
  21683. }
  21684. return this.operator === ValueCondition.IsEqual ? check : !check;
  21685. }
  21686. return false;
  21687. };
  21688. ValueCondition._IsEqual = 0;
  21689. ValueCondition._IsDifferent = 1;
  21690. ValueCondition._IsGreater = 2;
  21691. ValueCondition._IsLesser = 3;
  21692. return ValueCondition;
  21693. })(Condition);
  21694. BABYLON.ValueCondition = ValueCondition;
  21695. var PredicateCondition = (function (_super) {
  21696. __extends(PredicateCondition, _super);
  21697. function PredicateCondition(actionManager, predicate) {
  21698. _super.call(this, actionManager);
  21699. this.predicate = predicate;
  21700. }
  21701. PredicateCondition.prototype.isValid = function () {
  21702. return this.predicate();
  21703. };
  21704. return PredicateCondition;
  21705. })(Condition);
  21706. BABYLON.PredicateCondition = PredicateCondition;
  21707. var StateCondition = (function (_super) {
  21708. __extends(StateCondition, _super);
  21709. function StateCondition(actionManager, target, value) {
  21710. _super.call(this, actionManager);
  21711. this.value = value;
  21712. this._target = target;
  21713. }
  21714. // Methods
  21715. StateCondition.prototype.isValid = function () {
  21716. return this._target.state === this.value;
  21717. };
  21718. return StateCondition;
  21719. })(Condition);
  21720. BABYLON.StateCondition = StateCondition;
  21721. })(BABYLON || (BABYLON = {}));
  21722. //# sourceMappingURL=babylon.condition.js.map
  21723. var BABYLON;
  21724. (function (BABYLON) {
  21725. var Action = (function () {
  21726. function Action(triggerOptions, condition) {
  21727. this.triggerOptions = triggerOptions;
  21728. if (triggerOptions.parameter) {
  21729. this.trigger = triggerOptions.trigger;
  21730. this._triggerParameter = triggerOptions.parameter;
  21731. } else {
  21732. this.trigger = triggerOptions;
  21733. }
  21734. this._nextActiveAction = this;
  21735. this._condition = condition;
  21736. }
  21737. // Methods
  21738. Action.prototype._prepare = function () {
  21739. };
  21740. Action.prototype.getTriggerParameter = function () {
  21741. return this._triggerParameter;
  21742. };
  21743. Action.prototype._executeCurrent = function (evt) {
  21744. if (this._condition) {
  21745. var currentRenderId = this._actionManager.getScene().getRenderId();
  21746. // We cache the current evaluation for the current frame
  21747. if (this._condition._evaluationId === currentRenderId) {
  21748. if (!this._condition._currentResult) {
  21749. return;
  21750. }
  21751. } else {
  21752. this._condition._evaluationId = currentRenderId;
  21753. if (!this._condition.isValid()) {
  21754. this._condition._currentResult = false;
  21755. return;
  21756. }
  21757. this._condition._currentResult = true;
  21758. }
  21759. }
  21760. this._nextActiveAction.execute(evt);
  21761. if (this._nextActiveAction._child) {
  21762. if (!this._nextActiveAction._child._actionManager) {
  21763. this._nextActiveAction._child._actionManager = this._actionManager;
  21764. }
  21765. this._nextActiveAction = this._nextActiveAction._child;
  21766. } else {
  21767. this._nextActiveAction = this;
  21768. }
  21769. };
  21770. Action.prototype.execute = function (evt) {
  21771. };
  21772. Action.prototype.then = function (action) {
  21773. this._child = action;
  21774. action._actionManager = this._actionManager;
  21775. action._prepare();
  21776. return action;
  21777. };
  21778. Action.prototype._getProperty = function (propertyPath) {
  21779. return this._actionManager._getProperty(propertyPath);
  21780. };
  21781. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21782. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21783. };
  21784. return Action;
  21785. })();
  21786. BABYLON.Action = Action;
  21787. })(BABYLON || (BABYLON = {}));
  21788. //# sourceMappingURL=babylon.action.js.map
  21789. var BABYLON;
  21790. (function (BABYLON) {
  21791. var ActionEvent = (function () {
  21792. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21793. this.source = source;
  21794. this.pointerX = pointerX;
  21795. this.pointerY = pointerY;
  21796. this.meshUnderPointer = meshUnderPointer;
  21797. this.sourceEvent = sourceEvent;
  21798. }
  21799. ActionEvent.CreateNew = function (source, evt) {
  21800. var scene = source.getScene();
  21801. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21802. };
  21803. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21804. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21805. };
  21806. return ActionEvent;
  21807. })();
  21808. BABYLON.ActionEvent = ActionEvent;
  21809. var ActionManager = (function () {
  21810. function ActionManager(scene) {
  21811. // Members
  21812. this.actions = new Array();
  21813. this._scene = scene;
  21814. scene._actionManagers.push(this);
  21815. }
  21816. Object.defineProperty(ActionManager, "NothingTrigger", {
  21817. get: function () {
  21818. return ActionManager._NothingTrigger;
  21819. },
  21820. enumerable: true,
  21821. configurable: true
  21822. });
  21823. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21824. get: function () {
  21825. return ActionManager._OnPickTrigger;
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21831. get: function () {
  21832. return ActionManager._OnLeftPickTrigger;
  21833. },
  21834. enumerable: true,
  21835. configurable: true
  21836. });
  21837. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21838. get: function () {
  21839. return ActionManager._OnRightPickTrigger;
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21845. get: function () {
  21846. return ActionManager._OnCenterPickTrigger;
  21847. },
  21848. enumerable: true,
  21849. configurable: true
  21850. });
  21851. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21852. get: function () {
  21853. return ActionManager._OnPointerOverTrigger;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21859. get: function () {
  21860. return ActionManager._OnPointerOutTrigger;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21866. get: function () {
  21867. return ActionManager._OnEveryFrameTrigger;
  21868. },
  21869. enumerable: true,
  21870. configurable: true
  21871. });
  21872. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21873. get: function () {
  21874. return ActionManager._OnIntersectionEnterTrigger;
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21880. get: function () {
  21881. return ActionManager._OnIntersectionExitTrigger;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21887. get: function () {
  21888. return ActionManager._OnKeyDownTrigger;
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21894. get: function () {
  21895. return ActionManager._OnKeyUpTrigger;
  21896. },
  21897. enumerable: true,
  21898. configurable: true
  21899. });
  21900. // Methods
  21901. ActionManager.prototype.dispose = function () {
  21902. var index = this._scene._actionManagers.indexOf(this);
  21903. if (index > -1) {
  21904. this._scene._actionManagers.splice(index, 1);
  21905. }
  21906. };
  21907. ActionManager.prototype.getScene = function () {
  21908. return this._scene;
  21909. };
  21910. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21911. for (var index = 0; index < this.actions.length; index++) {
  21912. var action = this.actions[index];
  21913. if (triggers.indexOf(action.trigger) > -1) {
  21914. return true;
  21915. }
  21916. }
  21917. return false;
  21918. };
  21919. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21920. get: function () {
  21921. for (var index = 0; index < this.actions.length; index++) {
  21922. var action = this.actions[index];
  21923. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21924. return true;
  21925. }
  21926. }
  21927. return false;
  21928. },
  21929. enumerable: true,
  21930. configurable: true
  21931. });
  21932. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21933. get: function () {
  21934. for (var index = 0; index < this.actions.length; index++) {
  21935. var action = this.actions[index];
  21936. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21937. return true;
  21938. }
  21939. }
  21940. return false;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. ActionManager.prototype.registerAction = function (action) {
  21946. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21947. if (this.getScene().actionManager !== this) {
  21948. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21949. return null;
  21950. }
  21951. }
  21952. this.actions.push(action);
  21953. action._actionManager = this;
  21954. action._prepare();
  21955. return action;
  21956. };
  21957. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21958. for (var index = 0; index < this.actions.length; index++) {
  21959. var action = this.actions[index];
  21960. if (action.trigger === trigger) {
  21961. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21962. var parameter = action.getTriggerParameter();
  21963. if (parameter) {
  21964. if (evt.sourceEvent.key !== parameter) {
  21965. continue;
  21966. }
  21967. }
  21968. }
  21969. action._executeCurrent(evt);
  21970. }
  21971. }
  21972. };
  21973. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  21974. var properties = propertyPath.split(".");
  21975. for (var index = 0; index < properties.length - 1; index++) {
  21976. target = target[properties[index]];
  21977. }
  21978. return target;
  21979. };
  21980. ActionManager.prototype._getProperty = function (propertyPath) {
  21981. var properties = propertyPath.split(".");
  21982. return properties[properties.length - 1];
  21983. };
  21984. ActionManager._NothingTrigger = 0;
  21985. ActionManager._OnPickTrigger = 1;
  21986. ActionManager._OnLeftPickTrigger = 2;
  21987. ActionManager._OnRightPickTrigger = 3;
  21988. ActionManager._OnCenterPickTrigger = 4;
  21989. ActionManager._OnPointerOverTrigger = 5;
  21990. ActionManager._OnPointerOutTrigger = 6;
  21991. ActionManager._OnEveryFrameTrigger = 7;
  21992. ActionManager._OnIntersectionEnterTrigger = 8;
  21993. ActionManager._OnIntersectionExitTrigger = 9;
  21994. ActionManager._OnKeyDownTrigger = 10;
  21995. ActionManager._OnKeyUpTrigger = 11;
  21996. return ActionManager;
  21997. })();
  21998. BABYLON.ActionManager = ActionManager;
  21999. })(BABYLON || (BABYLON = {}));
  22000. //# sourceMappingURL=babylon.actionManager.js.map
  22001. var BABYLON;
  22002. (function (BABYLON) {
  22003. var InterpolateValueAction = (function (_super) {
  22004. __extends(InterpolateValueAction, _super);
  22005. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22006. if (typeof duration === "undefined") { duration = 1000; }
  22007. _super.call(this, triggerOptions, condition);
  22008. this.propertyPath = propertyPath;
  22009. this.value = value;
  22010. this.duration = duration;
  22011. this.stopOtherAnimations = stopOtherAnimations;
  22012. this._target = target;
  22013. }
  22014. InterpolateValueAction.prototype._prepare = function () {
  22015. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22016. this._property = this._getProperty(this.propertyPath);
  22017. };
  22018. InterpolateValueAction.prototype.execute = function () {
  22019. var scene = this._actionManager.getScene();
  22020. var keys = [
  22021. {
  22022. frame: 0,
  22023. value: this._target[this._property]
  22024. }, {
  22025. frame: 100,
  22026. value: this.value
  22027. }
  22028. ];
  22029. var dataType;
  22030. if (typeof this.value === "number") {
  22031. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22032. } else if (this.value instanceof BABYLON.Color3) {
  22033. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22034. } else if (this.value instanceof BABYLON.Vector3) {
  22035. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22036. } else if (this.value instanceof BABYLON.Matrix) {
  22037. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22038. } else if (this.value instanceof BABYLON.Quaternion) {
  22039. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22040. } else {
  22041. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22042. return;
  22043. }
  22044. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22045. animation.setKeys(keys);
  22046. if (this.stopOtherAnimations) {
  22047. scene.stopAnimation(this._target);
  22048. }
  22049. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22050. };
  22051. return InterpolateValueAction;
  22052. })(BABYLON.Action);
  22053. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22054. })(BABYLON || (BABYLON = {}));
  22055. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22056. var BABYLON;
  22057. (function (BABYLON) {
  22058. var SwitchBooleanAction = (function (_super) {
  22059. __extends(SwitchBooleanAction, _super);
  22060. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22061. _super.call(this, triggerOptions, condition);
  22062. this.propertyPath = propertyPath;
  22063. this._target = target;
  22064. }
  22065. SwitchBooleanAction.prototype._prepare = function () {
  22066. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22067. this._property = this._getProperty(this.propertyPath);
  22068. };
  22069. SwitchBooleanAction.prototype.execute = function () {
  22070. this._target[this._property] = !this._target[this._property];
  22071. };
  22072. return SwitchBooleanAction;
  22073. })(BABYLON.Action);
  22074. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22075. var SetStateAction = (function (_super) {
  22076. __extends(SetStateAction, _super);
  22077. function SetStateAction(triggerOptions, target, value, condition) {
  22078. _super.call(this, triggerOptions, condition);
  22079. this.value = value;
  22080. this._target = target;
  22081. }
  22082. SetStateAction.prototype.execute = function () {
  22083. this._target.state = this.value;
  22084. };
  22085. return SetStateAction;
  22086. })(BABYLON.Action);
  22087. BABYLON.SetStateAction = SetStateAction;
  22088. var SetValueAction = (function (_super) {
  22089. __extends(SetValueAction, _super);
  22090. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22091. _super.call(this, triggerOptions, condition);
  22092. this.propertyPath = propertyPath;
  22093. this.value = value;
  22094. this._target = target;
  22095. }
  22096. SetValueAction.prototype._prepare = function () {
  22097. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22098. this._property = this._getProperty(this.propertyPath);
  22099. };
  22100. SetValueAction.prototype.execute = function () {
  22101. this._target[this._property] = this.value;
  22102. };
  22103. return SetValueAction;
  22104. })(BABYLON.Action);
  22105. BABYLON.SetValueAction = SetValueAction;
  22106. var IncrementValueAction = (function (_super) {
  22107. __extends(IncrementValueAction, _super);
  22108. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22109. _super.call(this, triggerOptions, condition);
  22110. this.propertyPath = propertyPath;
  22111. this.value = value;
  22112. this._target = target;
  22113. }
  22114. IncrementValueAction.prototype._prepare = function () {
  22115. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22116. this._property = this._getProperty(this.propertyPath);
  22117. if (typeof this._target[this._property] !== "number") {
  22118. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22119. }
  22120. };
  22121. IncrementValueAction.prototype.execute = function () {
  22122. this._target[this._property] += this.value;
  22123. };
  22124. return IncrementValueAction;
  22125. })(BABYLON.Action);
  22126. BABYLON.IncrementValueAction = IncrementValueAction;
  22127. var PlayAnimationAction = (function (_super) {
  22128. __extends(PlayAnimationAction, _super);
  22129. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22130. _super.call(this, triggerOptions, condition);
  22131. this.from = from;
  22132. this.to = to;
  22133. this.loop = loop;
  22134. this._target = target;
  22135. }
  22136. PlayAnimationAction.prototype._prepare = function () {
  22137. };
  22138. PlayAnimationAction.prototype.execute = function () {
  22139. var scene = this._actionManager.getScene();
  22140. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22141. };
  22142. return PlayAnimationAction;
  22143. })(BABYLON.Action);
  22144. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22145. var StopAnimationAction = (function (_super) {
  22146. __extends(StopAnimationAction, _super);
  22147. function StopAnimationAction(triggerOptions, target, condition) {
  22148. _super.call(this, triggerOptions, condition);
  22149. this._target = target;
  22150. }
  22151. StopAnimationAction.prototype._prepare = function () {
  22152. };
  22153. StopAnimationAction.prototype.execute = function () {
  22154. var scene = this._actionManager.getScene();
  22155. scene.stopAnimation(this._target);
  22156. };
  22157. return StopAnimationAction;
  22158. })(BABYLON.Action);
  22159. BABYLON.StopAnimationAction = StopAnimationAction;
  22160. var DoNothingAction = (function (_super) {
  22161. __extends(DoNothingAction, _super);
  22162. function DoNothingAction(triggerOptions, condition) {
  22163. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22164. _super.call(this, triggerOptions, condition);
  22165. }
  22166. DoNothingAction.prototype.execute = function () {
  22167. };
  22168. return DoNothingAction;
  22169. })(BABYLON.Action);
  22170. BABYLON.DoNothingAction = DoNothingAction;
  22171. var CombineAction = (function (_super) {
  22172. __extends(CombineAction, _super);
  22173. function CombineAction(triggerOptions, children, condition) {
  22174. _super.call(this, triggerOptions, condition);
  22175. this.children = children;
  22176. }
  22177. CombineAction.prototype._prepare = function () {
  22178. for (var index = 0; index < this.children.length; index++) {
  22179. this.children[index]._actionManager = this._actionManager;
  22180. this.children[index]._prepare();
  22181. }
  22182. };
  22183. CombineAction.prototype.execute = function (evt) {
  22184. for (var index = 0; index < this.children.length; index++) {
  22185. this.children[index].execute(evt);
  22186. }
  22187. };
  22188. return CombineAction;
  22189. })(BABYLON.Action);
  22190. BABYLON.CombineAction = CombineAction;
  22191. var ExecuteCodeAction = (function (_super) {
  22192. __extends(ExecuteCodeAction, _super);
  22193. function ExecuteCodeAction(triggerOptions, func, condition) {
  22194. _super.call(this, triggerOptions, condition);
  22195. this.func = func;
  22196. }
  22197. ExecuteCodeAction.prototype.execute = function (evt) {
  22198. this.func(evt);
  22199. };
  22200. return ExecuteCodeAction;
  22201. })(BABYLON.Action);
  22202. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22203. var SetParentAction = (function (_super) {
  22204. __extends(SetParentAction, _super);
  22205. function SetParentAction(triggerOptions, target, parent, condition) {
  22206. _super.call(this, triggerOptions, condition);
  22207. this._target = target;
  22208. this._parent = parent;
  22209. }
  22210. SetParentAction.prototype._prepare = function () {
  22211. };
  22212. SetParentAction.prototype.execute = function () {
  22213. if (this._target.parent === this._parent) {
  22214. return;
  22215. }
  22216. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22217. invertParentWorldMatrix.invert();
  22218. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22219. this._target.parent = this._parent;
  22220. };
  22221. return SetParentAction;
  22222. })(BABYLON.Action);
  22223. BABYLON.SetParentAction = SetParentAction;
  22224. })(BABYLON || (BABYLON = {}));
  22225. //# sourceMappingURL=babylon.directActions.js.map
  22226. var BABYLON;
  22227. (function (BABYLON) {
  22228. var Geometry = (function () {
  22229. function Geometry(id, scene, vertexData, updatable, mesh) {
  22230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22231. this._totalVertices = 0;
  22232. this._indices = [];
  22233. this.id = id;
  22234. this._engine = scene.getEngine();
  22235. this._meshes = [];
  22236. this._scene = scene;
  22237. // vertexData
  22238. if (vertexData) {
  22239. this.setAllVerticesData(vertexData, updatable);
  22240. } else {
  22241. this._totalVertices = 0;
  22242. this._indices = [];
  22243. }
  22244. // applyToMesh
  22245. if (mesh) {
  22246. this.applyToMesh(mesh);
  22247. }
  22248. }
  22249. Geometry.prototype.getScene = function () {
  22250. return this._scene;
  22251. };
  22252. Geometry.prototype.getEngine = function () {
  22253. return this._engine;
  22254. };
  22255. Geometry.prototype.isReady = function () {
  22256. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22257. };
  22258. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22259. vertexData.applyToGeometry(this, updatable);
  22260. };
  22261. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22262. this._vertexBuffers = this._vertexBuffers || {};
  22263. if (this._vertexBuffers[kind]) {
  22264. this._vertexBuffers[kind].dispose();
  22265. }
  22266. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22267. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22268. stride = this._vertexBuffers[kind].getStrideSize();
  22269. this._totalVertices = data.length / stride;
  22270. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22271. var meshes = this._meshes;
  22272. var numOfMeshes = meshes.length;
  22273. for (var index = 0; index < numOfMeshes; index++) {
  22274. var mesh = meshes[index];
  22275. mesh._resetPointsArrayCache();
  22276. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22277. mesh._createGlobalSubMesh();
  22278. mesh.computeWorldMatrix(true);
  22279. }
  22280. }
  22281. };
  22282. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22283. var vertexBuffer = this.getVertexBuffer(kind);
  22284. if (!vertexBuffer) {
  22285. return;
  22286. }
  22287. vertexBuffer.updateDirectly(data, offset);
  22288. };
  22289. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22290. var vertexBuffer = this.getVertexBuffer(kind);
  22291. if (!vertexBuffer) {
  22292. return;
  22293. }
  22294. vertexBuffer.update(data);
  22295. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22296. var extend;
  22297. var stride = vertexBuffer.getStrideSize();
  22298. this._totalVertices = data.length / stride;
  22299. if (updateExtends) {
  22300. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22301. }
  22302. var meshes = this._meshes;
  22303. var numOfMeshes = meshes.length;
  22304. for (var index = 0; index < numOfMeshes; index++) {
  22305. var mesh = meshes[index];
  22306. mesh._resetPointsArrayCache();
  22307. if (updateExtends) {
  22308. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22309. }
  22310. }
  22311. }
  22312. };
  22313. Geometry.prototype.getTotalVertices = function () {
  22314. if (!this.isReady()) {
  22315. return 0;
  22316. }
  22317. return this._totalVertices;
  22318. };
  22319. Geometry.prototype.getVerticesData = function (kind) {
  22320. var vertexBuffer = this.getVertexBuffer(kind);
  22321. if (!vertexBuffer) {
  22322. return null;
  22323. }
  22324. return vertexBuffer.getData();
  22325. };
  22326. Geometry.prototype.getVertexBuffer = function (kind) {
  22327. if (!this.isReady()) {
  22328. return null;
  22329. }
  22330. return this._vertexBuffers[kind];
  22331. };
  22332. Geometry.prototype.getVertexBuffers = function () {
  22333. if (!this.isReady()) {
  22334. return null;
  22335. }
  22336. return this._vertexBuffers;
  22337. };
  22338. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22339. if (!this._vertexBuffers) {
  22340. if (this._delayInfo) {
  22341. return this._delayInfo.indexOf(kind) !== -1;
  22342. }
  22343. return false;
  22344. }
  22345. return this._vertexBuffers[kind] !== undefined;
  22346. };
  22347. Geometry.prototype.getVerticesDataKinds = function () {
  22348. var result = [];
  22349. if (!this._vertexBuffers && this._delayInfo) {
  22350. for (var kind in this._delayInfo) {
  22351. result.push(kind);
  22352. }
  22353. } else {
  22354. for (kind in this._vertexBuffers) {
  22355. result.push(kind);
  22356. }
  22357. }
  22358. return result;
  22359. };
  22360. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22361. if (this._indexBuffer) {
  22362. this._engine._releaseBuffer(this._indexBuffer);
  22363. }
  22364. this._indices = indices;
  22365. if (this._meshes.length !== 0 && this._indices) {
  22366. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22367. }
  22368. if (totalVertices !== undefined) {
  22369. this._totalVertices = totalVertices;
  22370. }
  22371. var meshes = this._meshes;
  22372. var numOfMeshes = meshes.length;
  22373. for (var index = 0; index < numOfMeshes; index++) {
  22374. meshes[index]._createGlobalSubMesh();
  22375. }
  22376. };
  22377. Geometry.prototype.getTotalIndices = function () {
  22378. if (!this.isReady()) {
  22379. return 0;
  22380. }
  22381. return this._indices.length;
  22382. };
  22383. Geometry.prototype.getIndices = function () {
  22384. if (!this.isReady()) {
  22385. return null;
  22386. }
  22387. return this._indices;
  22388. };
  22389. Geometry.prototype.getIndexBuffer = function () {
  22390. if (!this.isReady()) {
  22391. return null;
  22392. }
  22393. return this._indexBuffer;
  22394. };
  22395. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22396. var meshes = this._meshes;
  22397. var index = meshes.indexOf(mesh);
  22398. if (index === -1) {
  22399. return;
  22400. }
  22401. for (var kind in this._vertexBuffers) {
  22402. this._vertexBuffers[kind].dispose();
  22403. }
  22404. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22405. this._indexBuffer = null;
  22406. }
  22407. meshes.splice(index, 1);
  22408. mesh._geometry = null;
  22409. if (meshes.length == 0 && shouldDispose) {
  22410. this.dispose();
  22411. }
  22412. };
  22413. Geometry.prototype.applyToMesh = function (mesh) {
  22414. if (mesh._geometry === this) {
  22415. return;
  22416. }
  22417. var previousGeometry = mesh._geometry;
  22418. if (previousGeometry) {
  22419. previousGeometry.releaseForMesh(mesh);
  22420. }
  22421. var meshes = this._meshes;
  22422. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22423. mesh._geometry = this;
  22424. this._scene.pushGeometry(this);
  22425. meshes.push(mesh);
  22426. if (this.isReady()) {
  22427. this._applyToMesh(mesh);
  22428. } else {
  22429. mesh._boundingInfo = this._boundingInfo;
  22430. }
  22431. };
  22432. Geometry.prototype._applyToMesh = function (mesh) {
  22433. var numOfMeshes = this._meshes.length;
  22434. for (var kind in this._vertexBuffers) {
  22435. if (numOfMeshes === 1) {
  22436. this._vertexBuffers[kind].create();
  22437. }
  22438. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22439. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22440. mesh._resetPointsArrayCache();
  22441. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22442. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22443. mesh._createGlobalSubMesh();
  22444. }
  22445. }
  22446. // indexBuffer
  22447. if (numOfMeshes === 1 && this._indices) {
  22448. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22449. }
  22450. if (this._indexBuffer) {
  22451. this._indexBuffer.references = numOfMeshes;
  22452. }
  22453. };
  22454. Geometry.prototype.load = function (scene, onLoaded) {
  22455. var _this = this;
  22456. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22457. return;
  22458. }
  22459. if (this.isReady()) {
  22460. if (onLoaded) {
  22461. onLoaded();
  22462. }
  22463. return;
  22464. }
  22465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22466. scene._addPendingData(this);
  22467. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22468. _this._delayLoadingFunction(JSON.parse(data), _this);
  22469. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22470. _this._delayInfo = [];
  22471. scene._removePendingData(_this);
  22472. var meshes = _this._meshes;
  22473. var numOfMeshes = meshes.length;
  22474. for (var index = 0; index < numOfMeshes; index++) {
  22475. _this._applyToMesh(meshes[index]);
  22476. }
  22477. if (onLoaded) {
  22478. onLoaded();
  22479. }
  22480. }, function () {
  22481. }, scene.database);
  22482. };
  22483. Geometry.prototype.dispose = function () {
  22484. var meshes = this._meshes;
  22485. var numOfMeshes = meshes.length;
  22486. for (var index = 0; index < numOfMeshes; index++) {
  22487. this.releaseForMesh(meshes[index]);
  22488. }
  22489. this._meshes = [];
  22490. for (var kind in this._vertexBuffers) {
  22491. this._vertexBuffers[kind].dispose();
  22492. }
  22493. this._vertexBuffers = [];
  22494. this._totalVertices = 0;
  22495. if (this._indexBuffer) {
  22496. this._engine._releaseBuffer(this._indexBuffer);
  22497. }
  22498. this._indexBuffer = null;
  22499. this._indices = [];
  22500. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22501. this.delayLoadingFile = null;
  22502. this._delayLoadingFunction = null;
  22503. this._delayInfo = [];
  22504. this._boundingInfo = null; // todo: .dispose()
  22505. var geometries = this._scene.getGeometries();
  22506. index = geometries.indexOf(this);
  22507. if (index > -1) {
  22508. geometries.splice(index, 1);
  22509. }
  22510. };
  22511. Geometry.prototype.copy = function (id) {
  22512. var vertexData = new BABYLON.VertexData();
  22513. vertexData.indices = [];
  22514. var indices = this.getIndices();
  22515. for (var index = 0; index < indices.length; index++) {
  22516. vertexData.indices.push(indices[index]);
  22517. }
  22518. var updatable = false;
  22519. var stopChecking = false;
  22520. for (var kind in this._vertexBuffers) {
  22521. vertexData.set(this.getVerticesData(kind), kind);
  22522. if (!stopChecking) {
  22523. updatable = this.getVertexBuffer(kind).isUpdatable();
  22524. stopChecking = !updatable;
  22525. }
  22526. }
  22527. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  22528. geometry.delayLoadState = this.delayLoadState;
  22529. geometry.delayLoadingFile = this.delayLoadingFile;
  22530. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22531. for (kind in this._delayInfo) {
  22532. geometry._delayInfo = geometry._delayInfo || [];
  22533. geometry._delayInfo.push(kind);
  22534. }
  22535. // Bounding info
  22536. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22537. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22538. return geometry;
  22539. };
  22540. // Statics
  22541. Geometry.ExtractFromMesh = function (mesh, id) {
  22542. var geometry = mesh._geometry;
  22543. if (!geometry) {
  22544. return null;
  22545. }
  22546. return geometry.copy(id);
  22547. };
  22548. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22549. // be aware Math.random() could cause collisions
  22550. Geometry.RandomId = function () {
  22551. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22552. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  22553. return v.toString(16);
  22554. });
  22555. };
  22556. return Geometry;
  22557. })();
  22558. BABYLON.Geometry = Geometry;
  22559. (function (Geometry) {
  22560. /////// Primitives //////////////////////////////////////////////
  22561. (function (Primitives) {
  22562. /// Abstract class
  22563. var _Primitive = (function (_super) {
  22564. __extends(_Primitive, _super);
  22565. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22566. this._beingRegenerated = true;
  22567. this._canBeRegenerated = canBeRegenerated;
  22568. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22569. this._beingRegenerated = false;
  22570. }
  22571. _Primitive.prototype.canBeRegenerated = function () {
  22572. return this._canBeRegenerated;
  22573. };
  22574. _Primitive.prototype.regenerate = function () {
  22575. if (!this._canBeRegenerated) {
  22576. return;
  22577. }
  22578. this._beingRegenerated = true;
  22579. this.setAllVerticesData(this._regenerateVertexData(), false);
  22580. this._beingRegenerated = false;
  22581. };
  22582. _Primitive.prototype.asNewGeometry = function (id) {
  22583. return _super.prototype.copy.call(this, id);
  22584. };
  22585. // overrides
  22586. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22587. if (!this._beingRegenerated) {
  22588. return;
  22589. }
  22590. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22591. };
  22592. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22593. if (!this._beingRegenerated) {
  22594. return;
  22595. }
  22596. _super.prototype.setVerticesData.call(this, kind, data, false);
  22597. };
  22598. // to override
  22599. // protected
  22600. _Primitive.prototype._regenerateVertexData = function () {
  22601. throw new Error("Abstract method");
  22602. };
  22603. _Primitive.prototype.copy = function (id) {
  22604. throw new Error("Must be overriden in sub-classes.");
  22605. };
  22606. return _Primitive;
  22607. })(Geometry);
  22608. Primitives._Primitive = _Primitive;
  22609. var Box = (function (_super) {
  22610. __extends(Box, _super);
  22611. function Box(id, scene, size, canBeRegenerated, mesh) {
  22612. this.size = size;
  22613. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22614. }
  22615. Box.prototype._regenerateVertexData = function () {
  22616. return BABYLON.VertexData.CreateBox(this.size);
  22617. };
  22618. Box.prototype.copy = function (id) {
  22619. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22620. };
  22621. return Box;
  22622. })(_Primitive);
  22623. Primitives.Box = Box;
  22624. var Sphere = (function (_super) {
  22625. __extends(Sphere, _super);
  22626. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22627. this.segments = segments;
  22628. this.diameter = diameter;
  22629. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22630. }
  22631. Sphere.prototype._regenerateVertexData = function () {
  22632. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22633. };
  22634. Sphere.prototype.copy = function (id) {
  22635. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22636. };
  22637. return Sphere;
  22638. })(_Primitive);
  22639. Primitives.Sphere = Sphere;
  22640. var Cylinder = (function (_super) {
  22641. __extends(Cylinder, _super);
  22642. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22643. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22644. this.height = height;
  22645. this.diameterTop = diameterTop;
  22646. this.diameterBottom = diameterBottom;
  22647. this.tessellation = tessellation;
  22648. this.subdivisions = subdivisions;
  22649. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22650. }
  22651. Cylinder.prototype._regenerateVertexData = function () {
  22652. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22653. };
  22654. Cylinder.prototype.copy = function (id) {
  22655. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22656. };
  22657. return Cylinder;
  22658. })(_Primitive);
  22659. Primitives.Cylinder = Cylinder;
  22660. var Torus = (function (_super) {
  22661. __extends(Torus, _super);
  22662. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22663. this.diameter = diameter;
  22664. this.thickness = thickness;
  22665. this.tessellation = tessellation;
  22666. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22667. }
  22668. Torus.prototype._regenerateVertexData = function () {
  22669. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22670. };
  22671. Torus.prototype.copy = function (id) {
  22672. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22673. };
  22674. return Torus;
  22675. })(_Primitive);
  22676. Primitives.Torus = Torus;
  22677. var Ground = (function (_super) {
  22678. __extends(Ground, _super);
  22679. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22680. this.width = width;
  22681. this.height = height;
  22682. this.subdivisions = subdivisions;
  22683. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22684. }
  22685. Ground.prototype._regenerateVertexData = function () {
  22686. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22687. };
  22688. Ground.prototype.copy = function (id) {
  22689. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22690. };
  22691. return Ground;
  22692. })(_Primitive);
  22693. Primitives.Ground = Ground;
  22694. var TiledGround = (function (_super) {
  22695. __extends(TiledGround, _super);
  22696. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22697. this.xmin = xmin;
  22698. this.zmin = zmin;
  22699. this.xmax = xmax;
  22700. this.zmax = zmax;
  22701. this.subdivisions = subdivisions;
  22702. this.precision = precision;
  22703. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22704. }
  22705. TiledGround.prototype._regenerateVertexData = function () {
  22706. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22707. };
  22708. TiledGround.prototype.copy = function (id) {
  22709. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22710. };
  22711. return TiledGround;
  22712. })(_Primitive);
  22713. Primitives.TiledGround = TiledGround;
  22714. var Plane = (function (_super) {
  22715. __extends(Plane, _super);
  22716. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22717. this.size = size;
  22718. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22719. }
  22720. Plane.prototype._regenerateVertexData = function () {
  22721. return BABYLON.VertexData.CreatePlane(this.size);
  22722. };
  22723. Plane.prototype.copy = function (id) {
  22724. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22725. };
  22726. return Plane;
  22727. })(_Primitive);
  22728. Primitives.Plane = Plane;
  22729. var TorusKnot = (function (_super) {
  22730. __extends(TorusKnot, _super);
  22731. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22732. this.radius = radius;
  22733. this.tube = tube;
  22734. this.radialSegments = radialSegments;
  22735. this.tubularSegments = tubularSegments;
  22736. this.p = p;
  22737. this.q = q;
  22738. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22739. }
  22740. TorusKnot.prototype._regenerateVertexData = function () {
  22741. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22742. };
  22743. TorusKnot.prototype.copy = function (id) {
  22744. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22745. };
  22746. return TorusKnot;
  22747. })(_Primitive);
  22748. Primitives.TorusKnot = TorusKnot;
  22749. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22750. var Primitives = Geometry.Primitives;
  22751. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22752. var Geometry = BABYLON.Geometry;
  22753. })(BABYLON || (BABYLON = {}));
  22754. //# sourceMappingURL=babylon.geometry.js.map
  22755. var BABYLON;
  22756. (function (BABYLON) {
  22757. var Gamepads = (function () {
  22758. function Gamepads(ongamedpadconnected) {
  22759. var _this = this;
  22760. this.babylonGamepads = [];
  22761. this.oneGamepadConnected = false;
  22762. this.isMonitoring = false;
  22763. this.gamepadEventSupported = 'GamepadEvent' in window;
  22764. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22765. 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=";
  22766. this._callbackGamepadConnected = ongamedpadconnected;
  22767. if (this.gamepadSupportAvailable) {
  22768. // Checking if the gamepad connected event is supported (like in Firefox)
  22769. if (this.gamepadEventSupported) {
  22770. window.addEventListener('gamepadconnected', function (evt) {
  22771. _this._onGamepadConnected(evt);
  22772. }, false);
  22773. window.addEventListener('gamepaddisconnected', function (evt) {
  22774. _this._onGamepadDisconnected(evt);
  22775. }, false);
  22776. } else {
  22777. this._startMonitoringGamepads();
  22778. }
  22779. if (!this.oneGamepadConnected) {
  22780. this._insertGamepadDOMInstructions();
  22781. }
  22782. } else {
  22783. this._insertGamepadDOMNotSupported();
  22784. }
  22785. }
  22786. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22787. Gamepads.gamepadDOMInfo = document.createElement("div");
  22788. var buttonAImage = document.createElement("img");
  22789. buttonAImage.src = this.buttonADataURL;
  22790. var spanMessage = document.createElement("span");
  22791. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22792. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22793. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22794. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22795. Gamepads.gamepadDOMInfo.style.width = "100%";
  22796. Gamepads.gamepadDOMInfo.style.height = "48px";
  22797. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22798. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22799. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22800. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22801. buttonAImage.style.position = "relative";
  22802. buttonAImage.style.bottom = "8px";
  22803. spanMessage.style.position = "relative";
  22804. spanMessage.style.fontSize = "32px";
  22805. spanMessage.style.bottom = "32px";
  22806. spanMessage.style.color = "green";
  22807. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22808. };
  22809. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22810. Gamepads.gamepadDOMInfo = document.createElement("div");
  22811. var spanMessage = document.createElement("span");
  22812. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22813. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22814. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22815. Gamepads.gamepadDOMInfo.style.width = "100%";
  22816. Gamepads.gamepadDOMInfo.style.height = "40px";
  22817. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22818. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22819. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22820. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22821. spanMessage.style.position = "relative";
  22822. spanMessage.style.fontSize = "32px";
  22823. spanMessage.style.color = "red";
  22824. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22825. };
  22826. Gamepads.prototype.dispose = function () {
  22827. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22828. };
  22829. Gamepads.prototype._onGamepadConnected = function (evt) {
  22830. var newGamepad = this._addNewGamepad(evt.gamepad);
  22831. if (this._callbackGamepadConnected)
  22832. this._callbackGamepadConnected(newGamepad);
  22833. this._startMonitoringGamepads();
  22834. };
  22835. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22836. if (!this.oneGamepadConnected) {
  22837. this.oneGamepadConnected = true;
  22838. if (Gamepads.gamepadDOMInfo) {
  22839. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22840. Gamepads.gamepadDOMInfo = null;
  22841. }
  22842. }
  22843. var newGamepad;
  22844. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22845. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22846. } else {
  22847. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22848. }
  22849. this.babylonGamepads.push(newGamepad);
  22850. return newGamepad;
  22851. };
  22852. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22853. for (var i in this.babylonGamepads) {
  22854. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22855. this.babylonGamepads.splice(i, 1);
  22856. break;
  22857. }
  22858. }
  22859. // If no gamepads are left, stop the polling loop.
  22860. if (this.babylonGamepads.length == 0) {
  22861. this._stopMonitoringGamepads();
  22862. }
  22863. };
  22864. Gamepads.prototype._startMonitoringGamepads = function () {
  22865. if (!this.isMonitoring) {
  22866. this.isMonitoring = true;
  22867. this._checkGamepadsStatus();
  22868. }
  22869. };
  22870. Gamepads.prototype._stopMonitoringGamepads = function () {
  22871. this.isMonitoring = false;
  22872. };
  22873. Gamepads.prototype._checkGamepadsStatus = function () {
  22874. var _this = this;
  22875. // updating gamepad objects
  22876. this._updateGamepadObjects();
  22877. for (var i in this.babylonGamepads) {
  22878. this.babylonGamepads[i].update();
  22879. }
  22880. if (this.isMonitoring) {
  22881. if (window.requestAnimationFrame) {
  22882. window.requestAnimationFrame(function () {
  22883. _this._checkGamepadsStatus();
  22884. });
  22885. } else if (window.mozRequestAnimationFrame) {
  22886. window.mozRequestAnimationFrame(function () {
  22887. _this._checkGamepadsStatus();
  22888. });
  22889. } else if (window.webkitRequestAnimationFrame) {
  22890. window.webkitRequestAnimationFrame(function () {
  22891. _this._checkGamepadsStatus();
  22892. });
  22893. }
  22894. }
  22895. };
  22896. // This function is called only on Chrome, which does not yet support
  22897. // connection/disconnection events, but requires you to monitor
  22898. // an array for changes.
  22899. Gamepads.prototype._updateGamepadObjects = function () {
  22900. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22901. for (var i = 0; i < gamepads.length; i++) {
  22902. if (gamepads[i]) {
  22903. if (!(gamepads[i].index in this.babylonGamepads)) {
  22904. var newGamepad = this._addNewGamepad(gamepads[i]);
  22905. if (this._callbackGamepadConnected) {
  22906. this._callbackGamepadConnected(newGamepad);
  22907. }
  22908. } else {
  22909. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22910. }
  22911. }
  22912. }
  22913. };
  22914. return Gamepads;
  22915. })();
  22916. BABYLON.Gamepads = Gamepads;
  22917. var StickValues = (function () {
  22918. function StickValues(x, y) {
  22919. this.x = x;
  22920. this.y = y;
  22921. }
  22922. return StickValues;
  22923. })();
  22924. BABYLON.StickValues = StickValues;
  22925. var Gamepad = (function () {
  22926. function Gamepad(id, index, browserGamepad) {
  22927. this.id = id;
  22928. this.index = index;
  22929. this.browserGamepad = browserGamepad;
  22930. if (this.browserGamepad.axes.length >= 2) {
  22931. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22932. }
  22933. if (this.browserGamepad.axes.length >= 4) {
  22934. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22935. }
  22936. }
  22937. Gamepad.prototype.onleftstickchanged = function (callback) {
  22938. this._onleftstickchanged = callback;
  22939. };
  22940. Gamepad.prototype.onrightstickchanged = function (callback) {
  22941. this._onrightstickchanged = callback;
  22942. };
  22943. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22944. get: function () {
  22945. return this._leftStick;
  22946. },
  22947. set: function (newValues) {
  22948. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22949. this._onleftstickchanged(newValues);
  22950. }
  22951. this._leftStick = newValues;
  22952. },
  22953. enumerable: true,
  22954. configurable: true
  22955. });
  22956. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22957. get: function () {
  22958. return this._rightStick;
  22959. },
  22960. set: function (newValues) {
  22961. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  22962. this._onrightstickchanged(newValues);
  22963. }
  22964. this._rightStick = newValues;
  22965. },
  22966. enumerable: true,
  22967. configurable: true
  22968. });
  22969. Gamepad.prototype.update = function () {
  22970. if (this._leftStick) {
  22971. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22972. }
  22973. if (this._rightStick) {
  22974. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22975. }
  22976. };
  22977. return Gamepad;
  22978. })();
  22979. BABYLON.Gamepad = Gamepad;
  22980. var GenericPad = (function (_super) {
  22981. __extends(GenericPad, _super);
  22982. function GenericPad(id, index, gamepad) {
  22983. _super.call(this, id, index, gamepad);
  22984. this.id = id;
  22985. this.index = index;
  22986. this.gamepad = gamepad;
  22987. this._buttons = new Array(gamepad.buttons.length);
  22988. }
  22989. GenericPad.prototype.onbuttondown = function (callback) {
  22990. this._onbuttondown = callback;
  22991. };
  22992. GenericPad.prototype.onbuttonup = function (callback) {
  22993. this._onbuttonup = callback;
  22994. };
  22995. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  22996. if (newValue !== currentValue) {
  22997. if (this._onbuttondown && newValue === 1) {
  22998. this._onbuttondown(buttonIndex);
  22999. }
  23000. if (this._onbuttonup && newValue === 0) {
  23001. this._onbuttonup(buttonIndex);
  23002. }
  23003. }
  23004. return newValue;
  23005. };
  23006. GenericPad.prototype.update = function () {
  23007. _super.prototype.update.call(this);
  23008. for (var index = 0; index < this._buttons.length; index++) {
  23009. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23010. }
  23011. };
  23012. return GenericPad;
  23013. })(Gamepad);
  23014. BABYLON.GenericPad = GenericPad;
  23015. (function (Xbox360Button) {
  23016. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23017. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23018. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23019. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23020. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23021. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23022. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23023. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23024. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23025. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23026. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23027. var Xbox360Button = BABYLON.Xbox360Button;
  23028. (function (Xbox360Dpad) {
  23029. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23030. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23031. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23032. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23033. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23034. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23035. var Xbox360Pad = (function (_super) {
  23036. __extends(Xbox360Pad, _super);
  23037. function Xbox360Pad() {
  23038. _super.apply(this, arguments);
  23039. this._leftTrigger = 0;
  23040. this._rightTrigger = 0;
  23041. this._buttonA = 0;
  23042. this._buttonB = 0;
  23043. this._buttonX = 0;
  23044. this._buttonY = 0;
  23045. this._buttonBack = 0;
  23046. this._buttonStart = 0;
  23047. this._buttonLB = 0;
  23048. this._buttonRB = 0;
  23049. this._buttonLeftStick = 0;
  23050. this._buttonRightStick = 0;
  23051. this._dPadUp = 0;
  23052. this._dPadDown = 0;
  23053. this._dPadLeft = 0;
  23054. this._dPadRight = 0;
  23055. }
  23056. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23057. this._onlefttriggerchanged = callback;
  23058. };
  23059. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23060. this._onrighttriggerchanged = callback;
  23061. };
  23062. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23063. get: function () {
  23064. return this._leftTrigger;
  23065. },
  23066. set: function (newValue) {
  23067. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23068. this._onlefttriggerchanged(newValue);
  23069. }
  23070. this._leftTrigger = newValue;
  23071. },
  23072. enumerable: true,
  23073. configurable: true
  23074. });
  23075. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23076. get: function () {
  23077. return this._rightTrigger;
  23078. },
  23079. set: function (newValue) {
  23080. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23081. this._onrighttriggerchanged(newValue);
  23082. }
  23083. this._rightTrigger = newValue;
  23084. },
  23085. enumerable: true,
  23086. configurable: true
  23087. });
  23088. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23089. this._onbuttondown = callback;
  23090. };
  23091. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23092. this._onbuttonup = callback;
  23093. };
  23094. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23095. this._ondpaddown = callback;
  23096. };
  23097. Xbox360Pad.prototype.ondpadup = function (callback) {
  23098. this._ondpadup = callback;
  23099. };
  23100. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23101. if (newValue !== currentValue) {
  23102. if (this._onbuttondown && newValue === 1) {
  23103. this._onbuttondown(buttonType);
  23104. }
  23105. if (this._onbuttonup && newValue === 0) {
  23106. this._onbuttonup(buttonType);
  23107. }
  23108. }
  23109. return newValue;
  23110. };
  23111. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23112. if (newValue !== currentValue) {
  23113. if (this._ondpaddown && newValue === 1) {
  23114. this._ondpaddown(buttonType);
  23115. }
  23116. if (this._ondpadup && newValue === 0) {
  23117. this._ondpadup(buttonType);
  23118. }
  23119. }
  23120. return newValue;
  23121. };
  23122. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23123. get: function () {
  23124. return this._buttonA;
  23125. },
  23126. set: function (value) {
  23127. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23128. },
  23129. enumerable: true,
  23130. configurable: true
  23131. });
  23132. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23133. get: function () {
  23134. return this._buttonB;
  23135. },
  23136. set: function (value) {
  23137. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23138. },
  23139. enumerable: true,
  23140. configurable: true
  23141. });
  23142. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23143. get: function () {
  23144. return this._buttonX;
  23145. },
  23146. set: function (value) {
  23147. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23148. },
  23149. enumerable: true,
  23150. configurable: true
  23151. });
  23152. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23153. get: function () {
  23154. return this._buttonY;
  23155. },
  23156. set: function (value) {
  23157. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23158. },
  23159. enumerable: true,
  23160. configurable: true
  23161. });
  23162. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23163. get: function () {
  23164. return this._buttonStart;
  23165. },
  23166. set: function (value) {
  23167. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23168. },
  23169. enumerable: true,
  23170. configurable: true
  23171. });
  23172. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23173. get: function () {
  23174. return this._buttonBack;
  23175. },
  23176. set: function (value) {
  23177. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23178. },
  23179. enumerable: true,
  23180. configurable: true
  23181. });
  23182. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23183. get: function () {
  23184. return this._buttonLB;
  23185. },
  23186. set: function (value) {
  23187. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23188. },
  23189. enumerable: true,
  23190. configurable: true
  23191. });
  23192. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23193. get: function () {
  23194. return this._buttonRB;
  23195. },
  23196. set: function (value) {
  23197. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23198. },
  23199. enumerable: true,
  23200. configurable: true
  23201. });
  23202. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23203. get: function () {
  23204. return this._buttonLeftStick;
  23205. },
  23206. set: function (value) {
  23207. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23208. },
  23209. enumerable: true,
  23210. configurable: true
  23211. });
  23212. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23213. get: function () {
  23214. return this._buttonRightStick;
  23215. },
  23216. set: function (value) {
  23217. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23218. },
  23219. enumerable: true,
  23220. configurable: true
  23221. });
  23222. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23223. get: function () {
  23224. return this._dPadUp;
  23225. },
  23226. set: function (value) {
  23227. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23228. },
  23229. enumerable: true,
  23230. configurable: true
  23231. });
  23232. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23233. get: function () {
  23234. return this._dPadDown;
  23235. },
  23236. set: function (value) {
  23237. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23238. },
  23239. enumerable: true,
  23240. configurable: true
  23241. });
  23242. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23243. get: function () {
  23244. return this._dPadLeft;
  23245. },
  23246. set: function (value) {
  23247. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23253. get: function () {
  23254. return this._dPadRight;
  23255. },
  23256. set: function (value) {
  23257. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23258. },
  23259. enumerable: true,
  23260. configurable: true
  23261. });
  23262. Xbox360Pad.prototype.update = function () {
  23263. _super.prototype.update.call(this);
  23264. this.buttonA = this.browserGamepad.buttons[0].value;
  23265. this.buttonB = this.browserGamepad.buttons[1].value;
  23266. this.buttonX = this.browserGamepad.buttons[2].value;
  23267. this.buttonY = this.browserGamepad.buttons[3].value;
  23268. this.buttonLB = this.browserGamepad.buttons[4].value;
  23269. this.buttonRB = this.browserGamepad.buttons[5].value;
  23270. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23271. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23272. this.buttonBack = this.browserGamepad.buttons[8].value;
  23273. this.buttonStart = this.browserGamepad.buttons[9].value;
  23274. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23275. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23276. this.dPadUp = this.browserGamepad.buttons[12].value;
  23277. this.dPadDown = this.browserGamepad.buttons[13].value;
  23278. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23279. this.dPadRight = this.browserGamepad.buttons[15].value;
  23280. };
  23281. return Xbox360Pad;
  23282. })(Gamepad);
  23283. BABYLON.Xbox360Pad = Xbox360Pad;
  23284. })(BABYLON || (BABYLON = {}));
  23285. //# sourceMappingURL=babylon.gamepads.js.map
  23286. var BABYLON;
  23287. (function (BABYLON) {
  23288. // We're mainly based on the logic defined into the FreeCamera code
  23289. var GamepadCamera = (function (_super) {
  23290. __extends(GamepadCamera, _super);
  23291. function GamepadCamera(name, position, scene) {
  23292. var _this = this;
  23293. _super.call(this, name, position, scene);
  23294. this.angularSensibility = 200;
  23295. this.moveSensibility = 75;
  23296. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23297. _this._onNewGameConnected(gamepad);
  23298. });
  23299. }
  23300. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23301. // Only the first gamepad can control the camera
  23302. if (gamepad.index === 0) {
  23303. this._gamepad = gamepad;
  23304. }
  23305. };
  23306. GamepadCamera.prototype._checkInputs = function () {
  23307. if (!this._gamepad) {
  23308. return;
  23309. }
  23310. var LSValues = this._gamepad.leftStick;
  23311. var normalizedLX = LSValues.x / this.moveSensibility;
  23312. var normalizedLY = LSValues.y / this.moveSensibility;
  23313. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23314. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23315. var RSValues = this._gamepad.rightStick;
  23316. var normalizedRX = RSValues.x / this.angularSensibility;
  23317. var normalizedRY = RSValues.y / this.angularSensibility;
  23318. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23319. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23320. ;
  23321. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23322. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23323. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23324. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23325. };
  23326. GamepadCamera.prototype.dispose = function () {
  23327. this._gamepads.dispose();
  23328. _super.prototype.dispose.call(this);
  23329. };
  23330. return GamepadCamera;
  23331. })(BABYLON.FreeCamera);
  23332. BABYLON.GamepadCamera = GamepadCamera;
  23333. })(BABYLON || (BABYLON = {}));
  23334. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23335. var BABYLON;
  23336. (function (BABYLON) {
  23337. var LinesMesh = (function (_super) {
  23338. __extends(LinesMesh, _super);
  23339. function LinesMesh(name, scene, updatable) {
  23340. if (typeof updatable === "undefined") { updatable = false; }
  23341. _super.call(this, name, scene);
  23342. this.color = new BABYLON.Color3(1, 1, 1);
  23343. this.alpha = 1;
  23344. this._indices = new Array();
  23345. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23346. attributes: ["position"],
  23347. uniforms: ["worldViewProjection", "color"],
  23348. needAlphaBlending: true
  23349. });
  23350. }
  23351. Object.defineProperty(LinesMesh.prototype, "material", {
  23352. get: function () {
  23353. return this._colorShader;
  23354. },
  23355. enumerable: true,
  23356. configurable: true
  23357. });
  23358. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23359. get: function () {
  23360. return false;
  23361. },
  23362. enumerable: true,
  23363. configurable: true
  23364. });
  23365. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23366. get: function () {
  23367. return false;
  23368. },
  23369. enumerable: true,
  23370. configurable: true
  23371. });
  23372. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23373. var engine = this.getScene().getEngine();
  23374. var indexToBind = this._geometry.getIndexBuffer();
  23375. // VBOs
  23376. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23377. // Color
  23378. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23379. };
  23380. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23381. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23382. return;
  23383. }
  23384. var engine = this.getScene().getEngine();
  23385. // Draw order
  23386. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23387. };
  23388. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23389. return null;
  23390. };
  23391. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23392. this._colorShader.dispose();
  23393. _super.prototype.dispose.call(this, doNotRecurse);
  23394. };
  23395. return LinesMesh;
  23396. })(BABYLON.Mesh);
  23397. BABYLON.LinesMesh = LinesMesh;
  23398. })(BABYLON || (BABYLON = {}));
  23399. //# sourceMappingURL=babylon.linesMesh.js.map
  23400. var BABYLON;
  23401. (function (BABYLON) {
  23402. var OutlineRenderer = (function () {
  23403. function OutlineRenderer(scene) {
  23404. this._scene = scene;
  23405. }
  23406. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23407. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23408. var scene = this._scene;
  23409. var engine = this._scene.getEngine();
  23410. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23411. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23412. return;
  23413. }
  23414. var mesh = subMesh.getRenderingMesh();
  23415. var material = subMesh.getMaterial();
  23416. engine.enableEffect(this._effect);
  23417. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23418. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23419. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23420. // Bones
  23421. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23422. if (useBones) {
  23423. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23424. }
  23425. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23426. // Alpha test
  23427. if (material && material.needAlphaTesting()) {
  23428. var alphaTexture = material.getAlphaTestTexture();
  23429. this._effect.setTexture("diffuseSampler", alphaTexture);
  23430. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23431. }
  23432. if (hardwareInstancedRendering) {
  23433. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23434. } else {
  23435. if (batch.renderSelf[subMesh._id]) {
  23436. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23437. // Draw
  23438. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23439. }
  23440. if (batch.visibleInstances[subMesh._id]) {
  23441. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23442. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23443. this._effect.setMatrix("world", instance.getWorldMatrix());
  23444. // Draw
  23445. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23446. }
  23447. }
  23448. }
  23449. };
  23450. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23451. var defines = [];
  23452. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23453. var mesh = subMesh.getMesh();
  23454. var material = subMesh.getMaterial();
  23455. // Alpha test
  23456. if (material && material.needAlphaTesting()) {
  23457. defines.push("#define ALPHATEST");
  23458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23459. attribs.push(BABYLON.VertexBuffer.UVKind);
  23460. defines.push("#define UV1");
  23461. }
  23462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23463. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23464. defines.push("#define UV2");
  23465. }
  23466. }
  23467. // Bones
  23468. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23471. defines.push("#define BONES");
  23472. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23473. }
  23474. // Instances
  23475. if (useInstances) {
  23476. defines.push("#define INSTANCES");
  23477. attribs.push("world0");
  23478. attribs.push("world1");
  23479. attribs.push("world2");
  23480. attribs.push("world3");
  23481. }
  23482. // Get correct effect
  23483. var join = defines.join("\n");
  23484. if (this._cachedDefines != join) {
  23485. this._cachedDefines = join;
  23486. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23487. }
  23488. return this._effect.isReady();
  23489. };
  23490. return OutlineRenderer;
  23491. })();
  23492. BABYLON.OutlineRenderer = OutlineRenderer;
  23493. })(BABYLON || (BABYLON = {}));
  23494. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23495. var BABYLON;
  23496. (function (BABYLON) {
  23497. var MeshAssetTask = (function () {
  23498. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23499. this.name = name;
  23500. this.meshesNames = meshesNames;
  23501. this.rootUrl = rootUrl;
  23502. this.sceneFilename = sceneFilename;
  23503. this.isCompleted = false;
  23504. }
  23505. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23506. var _this = this;
  23507. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23508. _this.loadedMeshes = meshes;
  23509. _this.loadedParticleSystems = particleSystems;
  23510. _this.loadedSkeletons = skeletons;
  23511. _this.isCompleted = true;
  23512. if (_this.onSuccess) {
  23513. _this.onSuccess(_this);
  23514. }
  23515. onSuccess();
  23516. }, null, function () {
  23517. if (_this.onError) {
  23518. _this.onError(_this);
  23519. }
  23520. onError();
  23521. });
  23522. };
  23523. return MeshAssetTask;
  23524. })();
  23525. BABYLON.MeshAssetTask = MeshAssetTask;
  23526. var TextFileAssetTask = (function () {
  23527. function TextFileAssetTask(name, url) {
  23528. this.name = name;
  23529. this.url = url;
  23530. this.isCompleted = false;
  23531. }
  23532. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23533. var _this = this;
  23534. BABYLON.Tools.LoadFile(this.url, function (data) {
  23535. _this.text = data;
  23536. _this.isCompleted = true;
  23537. if (_this.onSuccess) {
  23538. _this.onSuccess(_this);
  23539. }
  23540. onSuccess();
  23541. }, null, scene.database, false, function () {
  23542. if (_this.onError) {
  23543. _this.onError(_this);
  23544. }
  23545. onError();
  23546. });
  23547. };
  23548. return TextFileAssetTask;
  23549. })();
  23550. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23551. var BinaryFileAssetTask = (function () {
  23552. function BinaryFileAssetTask(name, url) {
  23553. this.name = name;
  23554. this.url = url;
  23555. this.isCompleted = false;
  23556. }
  23557. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23558. var _this = this;
  23559. BABYLON.Tools.LoadFile(this.url, function (data) {
  23560. _this.data = data;
  23561. _this.isCompleted = true;
  23562. if (_this.onSuccess) {
  23563. _this.onSuccess(_this);
  23564. }
  23565. onSuccess();
  23566. }, null, scene.database, true, function () {
  23567. if (_this.onError) {
  23568. _this.onError(_this);
  23569. }
  23570. onError();
  23571. });
  23572. };
  23573. return BinaryFileAssetTask;
  23574. })();
  23575. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23576. var ImageAssetTask = (function () {
  23577. function ImageAssetTask(name, url) {
  23578. this.name = name;
  23579. this.url = url;
  23580. this.isCompleted = false;
  23581. }
  23582. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23583. var _this = this;
  23584. var img = new Image();
  23585. img.onload = function () {
  23586. _this.image = img;
  23587. _this.isCompleted = true;
  23588. if (_this.onSuccess) {
  23589. _this.onSuccess(_this);
  23590. }
  23591. onSuccess();
  23592. };
  23593. img.onerror = function () {
  23594. if (_this.onError) {
  23595. _this.onError(_this);
  23596. }
  23597. onError();
  23598. };
  23599. img.src = this.url;
  23600. };
  23601. return ImageAssetTask;
  23602. })();
  23603. BABYLON.ImageAssetTask = ImageAssetTask;
  23604. var TextureAssetTask = (function () {
  23605. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23606. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23607. this.name = name;
  23608. this.url = url;
  23609. this.noMipmap = noMipmap;
  23610. this.invertY = invertY;
  23611. this.samplingMode = samplingMode;
  23612. this.isCompleted = false;
  23613. }
  23614. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23615. var _this = this;
  23616. var onload = function () {
  23617. _this.isCompleted = true;
  23618. if (_this.onSuccess) {
  23619. _this.onSuccess(_this);
  23620. }
  23621. onSuccess();
  23622. };
  23623. var onerror = function () {
  23624. if (_this.onError) {
  23625. _this.onError(_this);
  23626. }
  23627. onError();
  23628. };
  23629. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23630. };
  23631. return TextureAssetTask;
  23632. })();
  23633. BABYLON.TextureAssetTask = TextureAssetTask;
  23634. var AssetsManager = (function () {
  23635. function AssetsManager(scene) {
  23636. this._tasks = new Array();
  23637. this._waitingTasksCount = 0;
  23638. this.useDefaultLoadingScreen = true;
  23639. this._scene = scene;
  23640. }
  23641. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23642. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23643. this._tasks.push(task);
  23644. return task;
  23645. };
  23646. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23647. var task = new TextFileAssetTask(taskName, url);
  23648. this._tasks.push(task);
  23649. return task;
  23650. };
  23651. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23652. var task = new BinaryFileAssetTask(taskName, url);
  23653. this._tasks.push(task);
  23654. return task;
  23655. };
  23656. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23657. var task = new ImageAssetTask(taskName, url);
  23658. this._tasks.push(task);
  23659. return task;
  23660. };
  23661. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23662. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23663. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23664. this._tasks.push(task);
  23665. return task;
  23666. };
  23667. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23668. this._waitingTasksCount--;
  23669. if (this._waitingTasksCount === 0) {
  23670. if (this.onFinish) {
  23671. this.onFinish(this._tasks);
  23672. }
  23673. this._scene.getEngine().hideLoadingUI();
  23674. }
  23675. };
  23676. AssetsManager.prototype._runTask = function (task) {
  23677. var _this = this;
  23678. task.run(this._scene, function () {
  23679. if (_this.onTaskSuccess) {
  23680. _this.onTaskSuccess(task);
  23681. }
  23682. _this._decreaseWaitingTasksCount();
  23683. }, function () {
  23684. if (_this.onTaskError) {
  23685. _this.onTaskError(task);
  23686. }
  23687. _this._decreaseWaitingTasksCount();
  23688. });
  23689. };
  23690. AssetsManager.prototype.reset = function () {
  23691. this._tasks = new Array();
  23692. return this;
  23693. };
  23694. AssetsManager.prototype.load = function () {
  23695. this._waitingTasksCount = this._tasks.length;
  23696. if (this._waitingTasksCount === 0) {
  23697. if (this.onFinish) {
  23698. this.onFinish(this._tasks);
  23699. }
  23700. return this;
  23701. }
  23702. if (this.useDefaultLoadingScreen) {
  23703. this._scene.getEngine().displayLoadingUI();
  23704. }
  23705. for (var index = 0; index < this._tasks.length; index++) {
  23706. var task = this._tasks[index];
  23707. this._runTask(task);
  23708. }
  23709. return this;
  23710. };
  23711. return AssetsManager;
  23712. })();
  23713. BABYLON.AssetsManager = AssetsManager;
  23714. })(BABYLON || (BABYLON = {}));
  23715. //# sourceMappingURL=babylon.assetsManager.js.map
  23716. var BABYLON;
  23717. (function (BABYLON) {
  23718. var VRDeviceOrientationCamera = (function (_super) {
  23719. __extends(VRDeviceOrientationCamera, _super);
  23720. function VRDeviceOrientationCamera(name, position, scene) {
  23721. _super.call(this, name, position, scene);
  23722. this._alpha = 0;
  23723. this._beta = 0;
  23724. this._gamma = 0;
  23725. }
  23726. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23727. this._alpha = +evt.alpha | 0;
  23728. this._beta = +evt.beta | 0;
  23729. this._gamma = +evt.gamma | 0;
  23730. if (this._gamma < 0) {
  23731. this._gamma = 90 + this._gamma;
  23732. } else {
  23733. // Incline it in the correct angle.
  23734. this._gamma = 270 - this._gamma;
  23735. }
  23736. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23737. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23738. this.rotation.z = this._beta / 180.0 * Math.PI;
  23739. };
  23740. return VRDeviceOrientationCamera;
  23741. })(BABYLON.OculusCamera);
  23742. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23743. })(BABYLON || (BABYLON = {}));
  23744. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23745. var BABYLON;
  23746. (function (BABYLON) {
  23747. var WebVRCamera = (function (_super) {
  23748. __extends(WebVRCamera, _super);
  23749. function WebVRCamera(name, position, scene) {
  23750. _super.call(this, name, position, scene);
  23751. this._hmdDevice = null;
  23752. this._sensorDevice = null;
  23753. this._cacheState = null;
  23754. this._cacheQuaternion = new BABYLON.Quaternion();
  23755. this._cacheRotation = BABYLON.Vector3.Zero();
  23756. this._vrEnabled = false;
  23757. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23758. }
  23759. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23760. var size = devices.length;
  23761. var i = 0;
  23762. // Reset devices.
  23763. this._sensorDevice = null;
  23764. this._hmdDevice = null;
  23765. while (i < size && this._hmdDevice === null) {
  23766. if (devices[i] instanceof HMDVRDevice) {
  23767. this._hmdDevice = devices[i];
  23768. }
  23769. i++;
  23770. }
  23771. i = 0;
  23772. while (i < size && this._sensorDevice === null) {
  23773. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23774. this._sensorDevice = devices[i];
  23775. }
  23776. i++;
  23777. }
  23778. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23779. };
  23780. WebVRCamera.prototype._update = function () {
  23781. if (this._vrEnabled) {
  23782. this._cacheState = this._sensorDevice.getState();
  23783. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23784. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23785. this.rotation.x = -this._cacheRotation.z;
  23786. this.rotation.y = -this._cacheRotation.y;
  23787. this.rotation.z = this._cacheRotation.x;
  23788. }
  23789. _super.prototype._update.call(this);
  23790. };
  23791. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23792. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23793. if (navigator.getVRDevices) {
  23794. navigator.getVRDevices().then(this._getWebVRDevices);
  23795. } else if (navigator.mozGetVRDevices) {
  23796. navigator.mozGetVRDevices(this._getWebVRDevices);
  23797. }
  23798. };
  23799. WebVRCamera.prototype.detachControl = function (element) {
  23800. _super.prototype.detachControl.call(this, element);
  23801. this._vrEnabled = false;
  23802. };
  23803. return WebVRCamera;
  23804. })(BABYLON.OculusCamera);
  23805. BABYLON.WebVRCamera = WebVRCamera;
  23806. })(BABYLON || (BABYLON = {}));
  23807. //# sourceMappingURL=babylon.webVRCamera.js.map
  23808. var BABYLON;
  23809. (function (BABYLON) {
  23810. // Standard optimizations
  23811. var SceneOptimization = (function () {
  23812. function SceneOptimization(priority) {
  23813. if (typeof priority === "undefined") { priority = 0; }
  23814. this.priority = priority;
  23815. this.apply = function (scene) {
  23816. return true;
  23817. };
  23818. }
  23819. return SceneOptimization;
  23820. })();
  23821. BABYLON.SceneOptimization = SceneOptimization;
  23822. var TextureOptimization = (function (_super) {
  23823. __extends(TextureOptimization, _super);
  23824. function TextureOptimization(priority, maximumSize) {
  23825. if (typeof priority === "undefined") { priority = 0; }
  23826. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23827. var _this = this;
  23828. _super.call(this, priority);
  23829. this.priority = priority;
  23830. this.maximumSize = maximumSize;
  23831. this.apply = function (scene) {
  23832. var allDone = true;
  23833. for (var index = 0; index < scene.textures.length; index++) {
  23834. var texture = scene.textures[index];
  23835. if (!texture.canRescale) {
  23836. continue;
  23837. }
  23838. var currentSize = texture.getSize();
  23839. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23840. if (maxDimension > _this.maximumSize) {
  23841. texture.scale(0.5);
  23842. allDone = false;
  23843. }
  23844. }
  23845. return allDone;
  23846. };
  23847. }
  23848. return TextureOptimization;
  23849. })(SceneOptimization);
  23850. BABYLON.TextureOptimization = TextureOptimization;
  23851. var HardwareScalingOptimization = (function (_super) {
  23852. __extends(HardwareScalingOptimization, _super);
  23853. function HardwareScalingOptimization(priority, maximumScale) {
  23854. if (typeof priority === "undefined") { priority = 0; }
  23855. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23856. var _this = this;
  23857. _super.call(this, priority);
  23858. this.priority = priority;
  23859. this.maximumScale = maximumScale;
  23860. this._currentScale = 1;
  23861. this.apply = function (scene) {
  23862. _this._currentScale++;
  23863. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23864. return _this._currentScale >= _this.maximumScale;
  23865. };
  23866. }
  23867. return HardwareScalingOptimization;
  23868. })(SceneOptimization);
  23869. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23870. var ShadowsOptimization = (function (_super) {
  23871. __extends(ShadowsOptimization, _super);
  23872. function ShadowsOptimization() {
  23873. _super.apply(this, arguments);
  23874. this.apply = function (scene) {
  23875. scene.shadowsEnabled = false;
  23876. return true;
  23877. };
  23878. }
  23879. return ShadowsOptimization;
  23880. })(SceneOptimization);
  23881. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23882. var PostProcessesOptimization = (function (_super) {
  23883. __extends(PostProcessesOptimization, _super);
  23884. function PostProcessesOptimization() {
  23885. _super.apply(this, arguments);
  23886. this.apply = function (scene) {
  23887. scene.postProcessesEnabled = false;
  23888. return true;
  23889. };
  23890. }
  23891. return PostProcessesOptimization;
  23892. })(SceneOptimization);
  23893. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23894. var LensFlaresOptimization = (function (_super) {
  23895. __extends(LensFlaresOptimization, _super);
  23896. function LensFlaresOptimization() {
  23897. _super.apply(this, arguments);
  23898. this.apply = function (scene) {
  23899. scene.lensFlaresEnabled = false;
  23900. return true;
  23901. };
  23902. }
  23903. return LensFlaresOptimization;
  23904. })(SceneOptimization);
  23905. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23906. var ParticlesOptimization = (function (_super) {
  23907. __extends(ParticlesOptimization, _super);
  23908. function ParticlesOptimization() {
  23909. _super.apply(this, arguments);
  23910. this.apply = function (scene) {
  23911. scene.particlesEnabled = false;
  23912. return true;
  23913. };
  23914. }
  23915. return ParticlesOptimization;
  23916. })(SceneOptimization);
  23917. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23918. var RenderTargetsOptimization = (function (_super) {
  23919. __extends(RenderTargetsOptimization, _super);
  23920. function RenderTargetsOptimization() {
  23921. _super.apply(this, arguments);
  23922. this.apply = function (scene) {
  23923. scene.renderTargetsEnabled = false;
  23924. return true;
  23925. };
  23926. }
  23927. return RenderTargetsOptimization;
  23928. })(SceneOptimization);
  23929. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23930. var MergeMeshesOptimization = (function (_super) {
  23931. __extends(MergeMeshesOptimization, _super);
  23932. function MergeMeshesOptimization() {
  23933. _super.apply(this, arguments);
  23934. var _this = this;
  23935. this._canBeMerged = function (abstractMesh) {
  23936. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23937. return false;
  23938. }
  23939. var mesh = abstractMesh;
  23940. if (!mesh.isVisible || !mesh.isEnabled()) {
  23941. return false;
  23942. }
  23943. if (mesh.instances.length > 0) {
  23944. return false;
  23945. }
  23946. if (mesh.skeleton || mesh.hasLODLevels) {
  23947. return false;
  23948. }
  23949. return true;
  23950. };
  23951. this.apply = function (scene) {
  23952. var globalPool = scene.meshes.slice(0);
  23953. var globalLength = globalPool.length;
  23954. for (var index = 0; index < globalLength; index++) {
  23955. var currentPool = new Array();
  23956. var current = globalPool[index];
  23957. // Checks
  23958. if (!_this._canBeMerged(current)) {
  23959. continue;
  23960. }
  23961. currentPool.push(current);
  23962. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  23963. var otherMesh = globalPool[subIndex];
  23964. if (!_this._canBeMerged(otherMesh)) {
  23965. continue;
  23966. }
  23967. if (otherMesh.material !== current.material) {
  23968. continue;
  23969. }
  23970. if (otherMesh.checkCollisions !== current.checkCollisions) {
  23971. continue;
  23972. }
  23973. currentPool.push(otherMesh);
  23974. globalLength--;
  23975. globalPool.splice(subIndex, 1);
  23976. subIndex--;
  23977. }
  23978. if (currentPool.length < 2) {
  23979. continue;
  23980. }
  23981. // Merge meshes
  23982. BABYLON.Mesh.MergeMeshes(currentPool);
  23983. }
  23984. return true;
  23985. };
  23986. }
  23987. return MergeMeshesOptimization;
  23988. })(SceneOptimization);
  23989. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  23990. // Options
  23991. var SceneOptimizerOptions = (function () {
  23992. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  23993. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  23994. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  23995. this.targetFrameRate = targetFrameRate;
  23996. this.trackerDuration = trackerDuration;
  23997. this.optimizations = new Array();
  23998. }
  23999. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24000. var result = new SceneOptimizerOptions(targetFrameRate);
  24001. var priority = 0;
  24002. result.optimizations.push(new MergeMeshesOptimization(priority));
  24003. result.optimizations.push(new ShadowsOptimization(priority));
  24004. result.optimizations.push(new LensFlaresOptimization(priority));
  24005. // Next priority
  24006. priority++;
  24007. result.optimizations.push(new PostProcessesOptimization(priority));
  24008. result.optimizations.push(new ParticlesOptimization(priority));
  24009. // Next priority
  24010. priority++;
  24011. result.optimizations.push(new TextureOptimization(priority, 1024));
  24012. return result;
  24013. };
  24014. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24015. var result = new SceneOptimizerOptions(targetFrameRate);
  24016. var priority = 0;
  24017. result.optimizations.push(new MergeMeshesOptimization(priority));
  24018. result.optimizations.push(new ShadowsOptimization(priority));
  24019. result.optimizations.push(new LensFlaresOptimization(priority));
  24020. // Next priority
  24021. priority++;
  24022. result.optimizations.push(new PostProcessesOptimization(priority));
  24023. result.optimizations.push(new ParticlesOptimization(priority));
  24024. // Next priority
  24025. priority++;
  24026. result.optimizations.push(new TextureOptimization(priority, 512));
  24027. // Next priority
  24028. priority++;
  24029. result.optimizations.push(new RenderTargetsOptimization(priority));
  24030. // Next priority
  24031. priority++;
  24032. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24033. return result;
  24034. };
  24035. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24036. var result = new SceneOptimizerOptions(targetFrameRate);
  24037. var priority = 0;
  24038. result.optimizations.push(new MergeMeshesOptimization(priority));
  24039. result.optimizations.push(new ShadowsOptimization(priority));
  24040. result.optimizations.push(new LensFlaresOptimization(priority));
  24041. // Next priority
  24042. priority++;
  24043. result.optimizations.push(new PostProcessesOptimization(priority));
  24044. result.optimizations.push(new ParticlesOptimization(priority));
  24045. // Next priority
  24046. priority++;
  24047. result.optimizations.push(new TextureOptimization(priority, 256));
  24048. // Next priority
  24049. priority++;
  24050. result.optimizations.push(new RenderTargetsOptimization(priority));
  24051. // Next priority
  24052. priority++;
  24053. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24054. return result;
  24055. };
  24056. return SceneOptimizerOptions;
  24057. })();
  24058. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24059. // Scene optimizer tool
  24060. var SceneOptimizer = (function () {
  24061. function SceneOptimizer() {
  24062. }
  24063. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24064. // TODO: add an epsilon
  24065. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24066. if (onSuccess) {
  24067. onSuccess();
  24068. }
  24069. return;
  24070. }
  24071. // Apply current level of optimizations
  24072. var allDone = true;
  24073. var noOptimizationApplied = true;
  24074. for (var index = 0; index < options.optimizations.length; index++) {
  24075. var optimization = options.optimizations[index];
  24076. if (optimization.priority === currentPriorityLevel) {
  24077. noOptimizationApplied = false;
  24078. allDone = allDone && optimization.apply(scene);
  24079. }
  24080. }
  24081. // If no optimization was applied, this is a failure :(
  24082. if (noOptimizationApplied) {
  24083. if (onFailure) {
  24084. onFailure();
  24085. }
  24086. return;
  24087. }
  24088. // If all optimizations were done, move to next level
  24089. if (allDone) {
  24090. currentPriorityLevel++;
  24091. }
  24092. // Let's the system running for a specific amount of time before checking FPS
  24093. scene.executeWhenReady(function () {
  24094. setTimeout(function () {
  24095. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24096. }, options.trackerDuration);
  24097. });
  24098. };
  24099. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24100. if (!options) {
  24101. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24102. }
  24103. // Let's the system running for a specific amount of time before checking FPS
  24104. scene.executeWhenReady(function () {
  24105. setTimeout(function () {
  24106. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24107. }, options.trackerDuration);
  24108. });
  24109. };
  24110. return SceneOptimizer;
  24111. })();
  24112. BABYLON.SceneOptimizer = SceneOptimizer;
  24113. })(BABYLON || (BABYLON = {}));
  24114. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24115. var BABYLON;
  24116. (function (BABYLON) {
  24117. (function (Internals) {
  24118. var MeshLODLevel = (function () {
  24119. function MeshLODLevel(distance, mesh) {
  24120. this.distance = distance;
  24121. this.mesh = mesh;
  24122. }
  24123. return MeshLODLevel;
  24124. })();
  24125. Internals.MeshLODLevel = MeshLODLevel;
  24126. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24127. var Internals = BABYLON.Internals;
  24128. })(BABYLON || (BABYLON = {}));
  24129. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24130. var BABYLON;
  24131. (function (BABYLON) {
  24132. var AudioEngine = (function () {
  24133. function AudioEngine() {
  24134. this.audioContext = null;
  24135. this.canUseWebAudio = false;
  24136. try {
  24137. if (typeof AudioContext !== 'undefined') {
  24138. this.audioContext = new AudioContext();
  24139. this.canUseWebAudio = true;
  24140. } else if (typeof webkitAudioContext !== 'undefined') {
  24141. this.audioContext = new webkitAudioContext();
  24142. this.canUseWebAudio = true;
  24143. }
  24144. } catch (e) {
  24145. this.canUseWebAudio = false;
  24146. }
  24147. // create a global volume gain node
  24148. if (this.canUseWebAudio) {
  24149. this.masterGain = this.audioContext.createGain();
  24150. this.masterGain.gain.value = 1;
  24151. this.masterGain.connect(this.audioContext.destination);
  24152. }
  24153. }
  24154. AudioEngine.prototype.getGlobalVolume = function () {
  24155. if (this.canUseWebAudio) {
  24156. return this.masterGain.gain.value;
  24157. } else {
  24158. return -1;
  24159. }
  24160. };
  24161. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24162. if (this.canUseWebAudio) {
  24163. this.masterGain.gain.value = newVolume;
  24164. }
  24165. };
  24166. return AudioEngine;
  24167. })();
  24168. BABYLON.AudioEngine = AudioEngine;
  24169. })(BABYLON || (BABYLON = {}));
  24170. //# sourceMappingURL=babylon.audioengine.js.map
  24171. var BABYLON;
  24172. (function (BABYLON) {
  24173. var Sound = (function () {
  24174. /**
  24175. * Create a sound and attach it to a scene
  24176. * @param name Name of your sound
  24177. * @param url Url to the sound to load async
  24178. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24179. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  24180. */
  24181. function Sound(name, url, scene, readyToPlayCallback, options) {
  24182. var _this = this;
  24183. this.autoplay = false;
  24184. this.loop = false;
  24185. this.useCustomAttenuation = false;
  24186. this.spatialSound = false;
  24187. this.refDistance = 1;
  24188. this.rolloffFactor = 1;
  24189. this.maxDistance = 100;
  24190. this._position = BABYLON.Vector3.Zero();
  24191. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24192. this._volume = 1;
  24193. this._isLoaded = false;
  24194. this._isReadyToPlay = false;
  24195. this._isPlaying = false;
  24196. this._isDirectional = false;
  24197. // Used if you'd like to create a directional sound.
  24198. // If not set, the sound will be omnidirectional
  24199. this._coneInnerAngle = null;
  24200. this._coneOuterAngle = null;
  24201. this._coneOuterGain = null;
  24202. this._name = name;
  24203. this._scene = scene;
  24204. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24205. this._readyToPlayCallback = readyToPlayCallback;
  24206. // Default custom attenuation function is a linear attenuation
  24207. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance) {
  24208. if (currentDistance < maxDistance) {
  24209. return currentVolume * (1 - currentDistance / maxDistance);
  24210. } else {
  24211. return 0;
  24212. }
  24213. };
  24214. if (options) {
  24215. if (options.maxDistance) {
  24216. this.maxDistance = options.maxDistance;
  24217. }
  24218. if (options.autoplay) {
  24219. this.autoplay = options.autoplay;
  24220. }
  24221. if (options.loop) {
  24222. this.loop = options.loop;
  24223. }
  24224. if (options.volume) {
  24225. this._volume = options.volume;
  24226. }
  24227. if (options.useCustomAttenuation) {
  24228. this.maxDistance = Number.MAX_VALUE;
  24229. this.useCustomAttenuation = options.useCustomAttenuation;
  24230. }
  24231. if (options.spatialSound) {
  24232. this.spatialSound = options.spatialSound;
  24233. }
  24234. }
  24235. if (this._audioEngine.canUseWebAudio) {
  24236. this._soundGain = this._audioEngine.audioContext.createGain();
  24237. this._soundGain.gain.value = this._volume;
  24238. if (this.spatialSound) {
  24239. this._createSpatialParameters();
  24240. } else {
  24241. this._audioNode = this._soundGain;
  24242. }
  24243. this._scene.mainSoundTrack.AddSound(this);
  24244. BABYLON.Tools.LoadFile(url, function (data) {
  24245. _this._soundLoaded(data);
  24246. }, null, null, true);
  24247. }
  24248. }
  24249. Sound.prototype._createSpatialParameters = function () {
  24250. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24251. this._soundPanner.distanceModel = "linear";
  24252. this._soundPanner.maxDistance = this.maxDistance;
  24253. this._soundGain.connect(this._soundPanner);
  24254. this._audioNode = this._soundPanner;
  24255. };
  24256. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24257. if (this._audioEngine.canUseWebAudio) {
  24258. this._audioNode.disconnect();
  24259. this._audioNode.connect(soundTrackAudioNode);
  24260. }
  24261. };
  24262. /**
  24263. * Transform this sound into a directional source
  24264. * @param coneInnerAngle Size of the inner cone in degree
  24265. * @param coneOuterAngle Size of the outer cone in degree
  24266. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24267. */
  24268. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24269. if (coneOuterAngle < coneInnerAngle) {
  24270. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24271. return;
  24272. }
  24273. this._coneInnerAngle = coneInnerAngle;
  24274. this._coneOuterAngle = coneOuterAngle;
  24275. this._coneOuterGain = coneOuterGain;
  24276. this._isDirectional = true;
  24277. if (this._isPlaying && this.loop) {
  24278. this.stop();
  24279. this.play();
  24280. }
  24281. };
  24282. Sound.prototype.setPosition = function (newPosition) {
  24283. this._position = newPosition;
  24284. if (this._isPlaying && this.spatialSound) {
  24285. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24286. }
  24287. };
  24288. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24289. this._localDirection = newLocalDirection;
  24290. if (this._connectedMesh && this._isPlaying) {
  24291. this._updateDirection();
  24292. }
  24293. };
  24294. Sound.prototype._updateDirection = function () {
  24295. var mat = this._connectedMesh.getWorldMatrix();
  24296. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24297. direction.normalize();
  24298. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24299. };
  24300. Sound.prototype.updateDistanceFromListener = function () {
  24301. if (this._connectedMesh && this.useCustomAttenuation) {
  24302. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24303. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance);
  24304. }
  24305. };
  24306. Sound.prototype.setAttenuationFunction = function (callback) {
  24307. this._customAttenuationFunction = callback;
  24308. };
  24309. /**
  24310. * Play the sound
  24311. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24312. */
  24313. Sound.prototype.play = function (time) {
  24314. if (this._isReadyToPlay) {
  24315. try {
  24316. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24317. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24318. this._soundSource.buffer = this._audioBuffer;
  24319. if (this.spatialSound) {
  24320. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24321. if (this._isDirectional) {
  24322. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24323. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24324. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24325. if (this._connectedMesh) {
  24326. this._updateDirection();
  24327. } else {
  24328. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24329. }
  24330. }
  24331. }
  24332. this._soundSource.connect(this._audioNode);
  24333. this._soundSource.loop = this.loop;
  24334. this._soundSource.start(startTime);
  24335. this._isPlaying = true;
  24336. } catch (ex) {
  24337. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24338. }
  24339. }
  24340. };
  24341. /**
  24342. * Stop the sound
  24343. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24344. */
  24345. Sound.prototype.stop = function (time) {
  24346. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24347. this._soundSource.stop(stopTime);
  24348. this._isPlaying = false;
  24349. };
  24350. Sound.prototype.pause = function () {
  24351. // TODO
  24352. };
  24353. Sound.prototype.setVolume = function (newVolume) {
  24354. this._volume = newVolume;
  24355. this._soundGain.gain.value = newVolume;
  24356. };
  24357. Sound.prototype.getVolume = function () {
  24358. return this._volume;
  24359. };
  24360. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24361. var _this = this;
  24362. this._connectedMesh = meshToConnectTo;
  24363. if (!this.spatialSound) {
  24364. this._createSpatialParameters();
  24365. this.spatialSound = true;
  24366. }
  24367. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24368. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24369. });
  24370. };
  24371. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24372. this.setPosition(connectedMesh.position);
  24373. if (this._isDirectional && this._isPlaying) {
  24374. this._updateDirection();
  24375. }
  24376. };
  24377. Sound.prototype._soundLoaded = function (audioData) {
  24378. var _this = this;
  24379. this._isLoaded = true;
  24380. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24381. _this._audioBuffer = buffer;
  24382. _this._isReadyToPlay = true;
  24383. if (_this.autoplay) {
  24384. _this.play();
  24385. }
  24386. if (_this._readyToPlayCallback) {
  24387. _this._readyToPlayCallback();
  24388. }
  24389. }, function (error) {
  24390. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24391. });
  24392. };
  24393. return Sound;
  24394. })();
  24395. BABYLON.Sound = Sound;
  24396. })(BABYLON || (BABYLON = {}));
  24397. //# sourceMappingURL=babylon.sound.js.map
  24398. var BABYLON;
  24399. (function (BABYLON) {
  24400. var SoundTrack = (function () {
  24401. function SoundTrack(scene, options) {
  24402. this.id = -1;
  24403. this._isMainTrack = false;
  24404. this._scene = scene;
  24405. this._audioEngine = scene.getEngine().getAudioEngine();
  24406. this.soundCollection = new Array();
  24407. if (this._audioEngine.canUseWebAudio) {
  24408. this._trackGain = this._audioEngine.audioContext.createGain();
  24409. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24410. //this._trackConvolver.connect(this._trackGain);
  24411. this._trackGain.connect(this._audioEngine.masterGain);
  24412. if (options) {
  24413. if (options.volume) {
  24414. this._trackGain.gain.value = options.volume;
  24415. }
  24416. if (options.mainTrack) {
  24417. this._isMainTrack = options.mainTrack;
  24418. }
  24419. }
  24420. }
  24421. if (!this._isMainTrack) {
  24422. this._scene.soundTracks.push(this);
  24423. this.id = this._scene.soundTracks.length - 1;
  24424. }
  24425. }
  24426. SoundTrack.prototype.AddSound = function (sound) {
  24427. sound.connectToSoundTrackAudioNode(this._trackGain);
  24428. if (sound.soundTrackId) {
  24429. if (sound.soundTrackId === -1) {
  24430. this._scene.mainSoundTrack.RemoveSound(sound);
  24431. } else {
  24432. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24433. }
  24434. }
  24435. this.soundCollection.push(sound);
  24436. sound.soundTrackId = this.id;
  24437. };
  24438. SoundTrack.prototype.RemoveSound = function (sound) {
  24439. var index = this.soundCollection.indexOf(sound);
  24440. if (index !== -1) {
  24441. this.soundCollection.splice(index, 1);
  24442. }
  24443. };
  24444. SoundTrack.prototype.setVolume = function (newVolume) {
  24445. if (this._audioEngine.canUseWebAudio) {
  24446. this._trackGain.gain.value = newVolume;
  24447. }
  24448. };
  24449. return SoundTrack;
  24450. })();
  24451. BABYLON.SoundTrack = SoundTrack;
  24452. })(BABYLON || (BABYLON = {}));
  24453. //# sourceMappingURL=babylon.soundtrack.js.map
  24454. var BABYLON;
  24455. (function (BABYLON) {
  24456. var DebugLayer = (function () {
  24457. function DebugLayer(scene) {
  24458. var _this = this;
  24459. this._enabled = false;
  24460. this._labelsEnabled = false;
  24461. this._displayStatistics = true;
  24462. this._displayTree = false;
  24463. this._displayLogs = false;
  24464. this._identityMatrix = BABYLON.Matrix.Identity();
  24465. this.axisRatio = 0.02;
  24466. this.accentColor = "orange";
  24467. this._scene = scene;
  24468. this._syncPositions = function () {
  24469. var engine = _this._scene.getEngine();
  24470. var canvasRect = engine.getRenderingCanvasClientRect();
  24471. if (_this._showUI) {
  24472. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24473. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24474. _this._statsDiv.style.width = "300px";
  24475. _this._statsDiv.style.height = "360px";
  24476. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24477. _this._optionsDiv.style.left = "0px";
  24478. _this._optionsDiv.style.top = "10px";
  24479. _this._optionsDiv.style.width = "200px";
  24480. _this._optionsDiv.style.height = "auto";
  24481. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24482. _this._logDiv.style.left = "0px";
  24483. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24484. _this._logDiv.style.width = "600px";
  24485. _this._logDiv.style.height = "160px";
  24486. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24487. _this._treeDiv.style.top = "10px";
  24488. _this._treeDiv.style.width = "300px";
  24489. _this._treeDiv.style.height = "auto";
  24490. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24491. }
  24492. _this._globalDiv.style.left = canvasRect.left + "px";
  24493. _this._globalDiv.style.top = canvasRect.top + "px";
  24494. _this._drawingCanvas.style.left = "0px";
  24495. _this._drawingCanvas.style.top = "0px";
  24496. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24497. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24498. var devicePixelRatio = window.devicePixelRatio || 1;
  24499. var context = _this._drawingContext;
  24500. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24501. _this._ratio = devicePixelRatio / backingStoreRatio;
  24502. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24503. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24504. };
  24505. this._onCanvasClick = function (evt) {
  24506. _this._clickPosition = {
  24507. x: evt.clientX * _this._ratio,
  24508. y: evt.clientY * _this._ratio
  24509. };
  24510. };
  24511. this._syncData = function () {
  24512. if (_this._showUI) {
  24513. if (_this._displayStatistics) {
  24514. _this._displayStats();
  24515. _this._statsDiv.style.display = "";
  24516. } else {
  24517. _this._statsDiv.style.display = "none";
  24518. }
  24519. if (_this._displayLogs) {
  24520. _this._logDiv.style.display = "";
  24521. } else {
  24522. _this._logDiv.style.display = "none";
  24523. }
  24524. if (_this._displayTree) {
  24525. _this._treeDiv.style.display = "";
  24526. if (_this._needToRefreshMeshesTree) {
  24527. _this._needToRefreshMeshesTree = false;
  24528. _this._refreshMeshesTreeContent();
  24529. }
  24530. } else {
  24531. _this._treeDiv.style.display = "none";
  24532. }
  24533. }
  24534. if (_this._labelsEnabled || !_this._showUI) {
  24535. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24536. var engine = _this._scene.getEngine();
  24537. var viewport = _this._scene.activeCamera.viewport;
  24538. var globalViewport = viewport.toGlobal(engine);
  24539. // Meshes
  24540. var meshes = _this._scene.getActiveMeshes();
  24541. for (var index = 0; index < meshes.length; index++) {
  24542. var mesh = meshes.data[index];
  24543. var position = mesh.getBoundingInfo().boundingSphere.center;
  24544. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24545. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24546. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24547. }
  24548. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24549. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24550. mesh.renderOverlay = !mesh.renderOverlay;
  24551. }, function () {
  24552. return mesh.renderOverlay ? 'red' : 'black';
  24553. });
  24554. }
  24555. }
  24556. // Cameras
  24557. var cameras = _this._scene.cameras;
  24558. for (index = 0; index < cameras.length; index++) {
  24559. var camera = cameras[index];
  24560. if (camera === _this._scene.activeCamera) {
  24561. continue;
  24562. }
  24563. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24564. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24565. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24566. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24567. _this._scene.activeCamera = camera;
  24568. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24569. }, function () {
  24570. return "purple";
  24571. });
  24572. }
  24573. }
  24574. // Lights
  24575. var lights = _this._scene.lights;
  24576. for (index = 0; index < lights.length; index++) {
  24577. var light = lights[index];
  24578. if (light.position) {
  24579. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24580. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24581. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24582. light.setEnabled(!light.isEnabled());
  24583. }, function () {
  24584. return light.isEnabled() ? "orange" : "gray";
  24585. });
  24586. }
  24587. }
  24588. }
  24589. }
  24590. _this._clickPosition = undefined;
  24591. };
  24592. }
  24593. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24594. while (this._treeSubsetDiv.hasChildNodes()) {
  24595. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24596. }
  24597. // Add meshes
  24598. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24599. sortedArray.sort(function (a, b) {
  24600. if (a.name === b.name) {
  24601. return 0;
  24602. }
  24603. return (a.name > b.name) ? 1 : -1;
  24604. });
  24605. for (var index = 0; index < sortedArray.length; index++) {
  24606. var mesh = sortedArray[index];
  24607. if (!mesh.isEnabled()) {
  24608. continue;
  24609. }
  24610. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24611. m.isVisible = element.checked;
  24612. }, mesh);
  24613. }
  24614. };
  24615. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24616. this._drawingContext.beginPath();
  24617. this._drawingContext.moveTo(zero.x, zero.y);
  24618. this._drawingContext.lineTo(unit.x, unit.y);
  24619. this._drawingContext.strokeStyle = color;
  24620. this._drawingContext.lineWidth = 4;
  24621. this._drawingContext.stroke();
  24622. this._drawingContext.font = "normal 14px Segoe UI";
  24623. this._drawingContext.fillStyle = color;
  24624. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24625. };
  24626. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24627. var position = mesh.getBoundingInfo().boundingSphere.center;
  24628. var worldMatrix = mesh.getWorldMatrix();
  24629. 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());
  24630. var unit = (unprojectedVector.subtract(position)).length();
  24631. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24632. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24633. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24634. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24635. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24636. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24637. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24638. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24639. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24640. };
  24641. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24642. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24643. this._drawingContext.font = "normal 12px Segoe UI";
  24644. var textMetrics = this._drawingContext.measureText(text);
  24645. var centerX = projectedPosition.x - textMetrics.width / 2;
  24646. var centerY = projectedPosition.y;
  24647. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24648. onClick();
  24649. }
  24650. this._drawingContext.beginPath();
  24651. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24652. this._drawingContext.fillStyle = getFillStyle();
  24653. this._drawingContext.globalAlpha = 0.5;
  24654. this._drawingContext.fill();
  24655. this._drawingContext.globalAlpha = 1.0;
  24656. this._drawingContext.strokeStyle = '#FFFFFF';
  24657. this._drawingContext.lineWidth = 1;
  24658. this._drawingContext.stroke();
  24659. this._drawingContext.fillStyle = "#FFFFFF";
  24660. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24661. this._drawingContext.beginPath();
  24662. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24663. this._drawingContext.fill();
  24664. }
  24665. };
  24666. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24667. if (!this._clickPosition) {
  24668. return false;
  24669. }
  24670. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24671. return false;
  24672. }
  24673. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24674. return false;
  24675. }
  24676. return true;
  24677. };
  24678. DebugLayer.prototype.isVisible = function () {
  24679. return this._enabled;
  24680. };
  24681. DebugLayer.prototype.hide = function () {
  24682. if (!this._enabled) {
  24683. return;
  24684. }
  24685. this._enabled = false;
  24686. var engine = this._scene.getEngine();
  24687. this._scene.unregisterAfterRender(this._syncData);
  24688. document.body.removeChild(this._globalDiv);
  24689. window.removeEventListener("resize", this._syncPositions);
  24690. this._scene.forceShowBoundingBoxes = false;
  24691. this._scene.forceWireframe = false;
  24692. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24693. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24694. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24695. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24696. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24697. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24698. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24699. this._scene.shadowsEnabled = true;
  24700. this._scene.particlesEnabled = true;
  24701. this._scene.postProcessesEnabled = true;
  24702. this._scene.collisionsEnabled = true;
  24703. this._scene.lightsEnabled = true;
  24704. this._scene.texturesEnabled = true;
  24705. this._scene.lensFlaresEnabled = true;
  24706. this._scene.proceduralTexturesEnabled = true;
  24707. this._scene.renderTargetsEnabled = true;
  24708. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24709. };
  24710. DebugLayer.prototype.show = function (showUI) {
  24711. if (typeof showUI === "undefined") { showUI = true; }
  24712. if (this._enabled) {
  24713. return;
  24714. }
  24715. this._enabled = true;
  24716. this._showUI = showUI;
  24717. var engine = this._scene.getEngine();
  24718. this._globalDiv = document.createElement("div");
  24719. document.body.appendChild(this._globalDiv);
  24720. this._generateDOMelements();
  24721. window.addEventListener("resize", this._syncPositions);
  24722. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24723. this._syncPositions();
  24724. this._scene.registerAfterRender(this._syncData);
  24725. };
  24726. DebugLayer.prototype._clearLabels = function () {
  24727. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24728. for (var index = 0; index < this._scene.meshes.length; index++) {
  24729. var mesh = this._scene.meshes[index];
  24730. mesh.renderOverlay = false;
  24731. }
  24732. };
  24733. DebugLayer.prototype._generateheader = function (root, text) {
  24734. var header = document.createElement("div");
  24735. header.innerHTML = text + "&nbsp;";
  24736. header.style.textAlign = "right";
  24737. header.style.width = "100%";
  24738. header.style.color = "white";
  24739. header.style.backgroundColor = "Black";
  24740. header.style.padding = "5px 5px 4px 0px";
  24741. header.style.marginLeft = "-5px";
  24742. header.style.fontWeight = "bold";
  24743. root.appendChild(header);
  24744. };
  24745. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24746. var label = document.createElement("label");
  24747. label.innerHTML = title;
  24748. label.style.color = color;
  24749. root.appendChild(label);
  24750. root.appendChild(document.createElement("br"));
  24751. };
  24752. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24753. if (typeof tag === "undefined") { tag = null; }
  24754. var label = document.createElement("label");
  24755. var boundingBoxesCheckbox = document.createElement("input");
  24756. boundingBoxesCheckbox.type = "checkbox";
  24757. boundingBoxesCheckbox.checked = initialState;
  24758. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24759. task(evt.target, tag);
  24760. });
  24761. label.appendChild(boundingBoxesCheckbox);
  24762. var container = document.createElement("span");
  24763. var leftPart = document.createElement("span");
  24764. var rightPart = document.createElement("span");
  24765. rightPart.style.cssFloat = "right";
  24766. leftPart.innerHTML = leftTitle;
  24767. rightPart.innerHTML = rightTitle;
  24768. rightPart.style.fontSize = "12px";
  24769. rightPart.style.maxWidth = "200px";
  24770. container.appendChild(leftPart);
  24771. container.appendChild(rightPart);
  24772. label.appendChild(container);
  24773. root.appendChild(label);
  24774. root.appendChild(document.createElement("br"));
  24775. };
  24776. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24777. if (typeof tag === "undefined") { tag = null; }
  24778. var label = document.createElement("label");
  24779. var boundingBoxesCheckbox = document.createElement("input");
  24780. boundingBoxesCheckbox.type = "checkbox";
  24781. boundingBoxesCheckbox.checked = initialState;
  24782. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24783. task(evt.target, tag);
  24784. });
  24785. label.appendChild(boundingBoxesCheckbox);
  24786. label.appendChild(document.createTextNode(title));
  24787. root.appendChild(label);
  24788. root.appendChild(document.createElement("br"));
  24789. };
  24790. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24791. if (typeof tag === "undefined") { tag = null; }
  24792. var label = document.createElement("label");
  24793. var boundingBoxesRadio = document.createElement("input");
  24794. boundingBoxesRadio.type = "radio";
  24795. boundingBoxesRadio.name = name;
  24796. boundingBoxesRadio.checked = initialState;
  24797. boundingBoxesRadio.addEventListener("change", function (evt) {
  24798. task(evt.target, tag);
  24799. });
  24800. label.appendChild(boundingBoxesRadio);
  24801. label.appendChild(document.createTextNode(title));
  24802. root.appendChild(label);
  24803. root.appendChild(document.createElement("br"));
  24804. };
  24805. DebugLayer.prototype._generateDOMelements = function () {
  24806. var _this = this;
  24807. this._globalDiv.id = "DebugLayer";
  24808. this._globalDiv.style.position = "absolute";
  24809. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24810. this._globalDiv.style.fontSize = "14px";
  24811. this._globalDiv.style.color = "white";
  24812. // Drawing canvas
  24813. this._drawingCanvas = document.createElement("canvas");
  24814. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24815. this._drawingCanvas.style.position = "absolute";
  24816. this._drawingCanvas.style.pointerEvents = "none";
  24817. this._drawingContext = this._drawingCanvas.getContext("2d");
  24818. this._globalDiv.appendChild(this._drawingCanvas);
  24819. if (this._showUI) {
  24820. var background = "rgba(128, 128, 128, 0.4)";
  24821. var border = "rgb(180, 180, 180) solid 1px";
  24822. // Stats
  24823. this._statsDiv = document.createElement("div");
  24824. this._statsDiv.id = "DebugLayerStats";
  24825. this._statsDiv.style.border = border;
  24826. this._statsDiv.style.position = "absolute";
  24827. this._statsDiv.style.background = background;
  24828. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24829. this._statsDiv.style.pointerEvents = "none";
  24830. this._statsDiv.style.overflowY = "auto";
  24831. this._generateheader(this._statsDiv, "STATISTICS");
  24832. this._statsSubsetDiv = document.createElement("div");
  24833. this._statsSubsetDiv.style.paddingTop = "5px";
  24834. this._statsSubsetDiv.style.paddingBottom = "5px";
  24835. this._statsDiv.appendChild(this._statsSubsetDiv);
  24836. // Tree
  24837. this._treeDiv = document.createElement("div");
  24838. this._treeDiv.id = "DebugLayerTree";
  24839. this._treeDiv.style.border = border;
  24840. this._treeDiv.style.position = "absolute";
  24841. this._treeDiv.style.background = background;
  24842. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24843. this._treeDiv.style.display = "none";
  24844. this._generateheader(this._treeDiv, "MESHES TREE");
  24845. this._treeSubsetDiv = document.createElement("div");
  24846. this._treeSubsetDiv.style.paddingTop = "5px";
  24847. this._treeSubsetDiv.style.paddingRight = "5px";
  24848. this._treeSubsetDiv.style.overflowY = "auto";
  24849. this._treeSubsetDiv.style.maxHeight = "300px";
  24850. this._treeDiv.appendChild(this._treeSubsetDiv);
  24851. this._needToRefreshMeshesTree = true;
  24852. // Logs
  24853. this._logDiv = document.createElement("div");
  24854. this._logDiv.style.border = border;
  24855. this._logDiv.id = "DebugLayerLogs";
  24856. this._logDiv.style.position = "absolute";
  24857. this._logDiv.style.background = background;
  24858. this._logDiv.style.padding = "0px 0px 0px 5px";
  24859. this._logDiv.style.display = "none";
  24860. this._generateheader(this._logDiv, "LOGS");
  24861. this._logSubsetDiv = document.createElement("div");
  24862. this._logSubsetDiv.style.height = "127px";
  24863. this._logSubsetDiv.style.paddingTop = "5px";
  24864. this._logSubsetDiv.style.overflowY = "auto";
  24865. this._logSubsetDiv.style.fontSize = "12px";
  24866. this._logSubsetDiv.style.fontFamily = "consolas";
  24867. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24868. this._logDiv.appendChild(this._logSubsetDiv);
  24869. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24870. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24871. };
  24872. // Options
  24873. this._optionsDiv = document.createElement("div");
  24874. this._optionsDiv.id = "DebugLayerOptions";
  24875. this._optionsDiv.style.border = border;
  24876. this._optionsDiv.style.position = "absolute";
  24877. this._optionsDiv.style.background = background;
  24878. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24879. this._optionsDiv.style.overflowY = "auto";
  24880. this._generateheader(this._optionsDiv, "OPTIONS");
  24881. this._optionsSubsetDiv = document.createElement("div");
  24882. this._optionsSubsetDiv.style.paddingTop = "5px";
  24883. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24884. this._optionsSubsetDiv.style.overflowY = "auto";
  24885. this._optionsSubsetDiv.style.maxHeight = "200px";
  24886. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24887. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24888. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24889. _this._displayStatistics = element.checked;
  24890. });
  24891. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24892. _this._displayLogs = element.checked;
  24893. });
  24894. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24895. _this._displayTree = element.checked;
  24896. _this._needToRefreshMeshesTree = true;
  24897. });
  24898. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24899. _this._scene.forceShowBoundingBoxes = element.checked;
  24900. });
  24901. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24902. _this._labelsEnabled = element.checked;
  24903. if (!_this._labelsEnabled) {
  24904. _this._clearLabels();
  24905. }
  24906. });
  24907. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24908. if (element.checked) {
  24909. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24910. } else {
  24911. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24912. }
  24913. });
  24914. ;
  24915. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24916. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24917. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24918. if (element.checked) {
  24919. _this._scene.forceWireframe = false;
  24920. _this._scene.forcePointsCloud = false;
  24921. }
  24922. });
  24923. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24924. if (element.checked) {
  24925. _this._scene.forceWireframe = true;
  24926. _this._scene.forcePointsCloud = false;
  24927. }
  24928. });
  24929. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  24930. if (element.checked) {
  24931. _this._scene.forceWireframe = false;
  24932. _this._scene.forcePointsCloud = true;
  24933. }
  24934. });
  24935. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24936. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  24937. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  24938. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  24939. });
  24940. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  24941. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  24942. });
  24943. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  24944. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  24945. });
  24946. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  24947. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  24948. });
  24949. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  24950. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  24951. });
  24952. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  24953. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  24954. });
  24955. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  24956. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  24957. });
  24958. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  24959. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  24960. });
  24961. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24962. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  24963. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  24964. _this._scene.animationsEnabled = element.checked;
  24965. });
  24966. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  24967. _this._scene.collisionsEnabled = element.checked;
  24968. });
  24969. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  24970. _this._scene.fogEnabled = element.checked;
  24971. });
  24972. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  24973. _this._scene.lensFlaresEnabled = element.checked;
  24974. });
  24975. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  24976. _this._scene.lightsEnabled = element.checked;
  24977. });
  24978. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  24979. _this._scene.particlesEnabled = element.checked;
  24980. });
  24981. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  24982. _this._scene.postProcessesEnabled = element.checked;
  24983. });
  24984. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  24985. _this._scene.proceduralTexturesEnabled = element.checked;
  24986. });
  24987. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  24988. _this._scene.renderTargetsEnabled = element.checked;
  24989. });
  24990. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  24991. _this._scene.shadowsEnabled = element.checked;
  24992. });
  24993. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  24994. _this._scene.skeletonsEnabled = element.checked;
  24995. });
  24996. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  24997. _this._scene.texturesEnabled = element.checked;
  24998. });
  24999. this._globalDiv.appendChild(this._statsDiv);
  25000. this._globalDiv.appendChild(this._logDiv);
  25001. this._globalDiv.appendChild(this._optionsDiv);
  25002. this._globalDiv.appendChild(this._treeDiv);
  25003. }
  25004. };
  25005. DebugLayer.prototype._displayStats = function () {
  25006. var scene = this._scene;
  25007. var engine = scene.getEngine();
  25008. 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>";
  25009. };
  25010. return DebugLayer;
  25011. })();
  25012. BABYLON.DebugLayer = DebugLayer;
  25013. })(BABYLON || (BABYLON = {}));
  25014. //# sourceMappingURL=babylon.debugLayer.js.map
  25015. var BABYLON;
  25016. (function (BABYLON) {
  25017. var RawTexture = (function (_super) {
  25018. __extends(RawTexture, _super);
  25019. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25020. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25021. if (typeof invertY === "undefined") { invertY = false; }
  25022. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25023. _super.call(this, null, scene, !generateMipMaps, invertY);
  25024. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25025. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25026. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25027. }
  25028. // Statics
  25029. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25030. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25031. if (typeof invertY === "undefined") { invertY = false; }
  25032. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25033. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25034. };
  25035. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25036. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25037. if (typeof invertY === "undefined") { invertY = false; }
  25038. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25040. };
  25041. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25042. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25043. if (typeof invertY === "undefined") { invertY = false; }
  25044. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25045. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25046. };
  25047. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25048. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25049. if (typeof invertY === "undefined") { invertY = false; }
  25050. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25051. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25052. };
  25053. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25054. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25055. if (typeof invertY === "undefined") { invertY = false; }
  25056. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25057. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25058. };
  25059. return RawTexture;
  25060. })(BABYLON.Texture);
  25061. BABYLON.RawTexture = RawTexture;
  25062. })(BABYLON || (BABYLON = {}));
  25063. //# sourceMappingURL=babylon.rawTexture.js.map
  25064. var BABYLON;
  25065. (function (BABYLON) {
  25066. var IndexedVector2 = (function (_super) {
  25067. __extends(IndexedVector2, _super);
  25068. function IndexedVector2(original, index) {
  25069. _super.call(this, original.x, original.y);
  25070. this.index = index;
  25071. }
  25072. return IndexedVector2;
  25073. })(BABYLON.Vector2);
  25074. var PolygonPoints = (function () {
  25075. function PolygonPoints() {
  25076. this.elements = new Array();
  25077. }
  25078. PolygonPoints.prototype.add = function (originalPoints) {
  25079. var _this = this;
  25080. var result = new Array();
  25081. originalPoints.forEach(function (point) {
  25082. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y))) {
  25083. var newPoint = new IndexedVector2(point, _this.elements.length);
  25084. result.push(newPoint);
  25085. _this.elements.push(newPoint);
  25086. }
  25087. });
  25088. return result;
  25089. };
  25090. PolygonPoints.prototype.computeBounds = function () {
  25091. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25092. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25093. this.elements.forEach(function (point) {
  25094. // x
  25095. if (point.x < lmin.x) {
  25096. lmin.x = point.x;
  25097. } else if (point.x > lmax.x) {
  25098. lmax.x = point.x;
  25099. }
  25100. // y
  25101. if (point.y < lmin.y) {
  25102. lmin.y = point.y;
  25103. } else if (point.y > lmax.y) {
  25104. lmax.y = point.y;
  25105. }
  25106. });
  25107. return {
  25108. min: lmin,
  25109. max: lmax,
  25110. width: lmax.x - lmin.x,
  25111. height: lmax.y - lmin.y
  25112. };
  25113. };
  25114. return PolygonPoints;
  25115. })();
  25116. var Polygon = (function () {
  25117. function Polygon() {
  25118. }
  25119. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25120. return [
  25121. new BABYLON.Vector2(xmin, ymin),
  25122. new BABYLON.Vector2(xmax, ymin),
  25123. new BABYLON.Vector2(xmax, ymax),
  25124. new BABYLON.Vector2(xmin, ymax)
  25125. ];
  25126. };
  25127. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25128. if (typeof cx === "undefined") { cx = 0; }
  25129. if (typeof cy === "undefined") { cy = 0; }
  25130. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25131. var result = new Array();
  25132. var angle = 0;
  25133. var increment = (Math.PI * 2) / numberOfSides;
  25134. for (var i = 0; i < numberOfSides; i++) {
  25135. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25136. angle -= increment;
  25137. }
  25138. return result;
  25139. };
  25140. Polygon.Parse = function (input) {
  25141. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25142. return (!isNaN(val));
  25143. });
  25144. var i, result = [];
  25145. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25146. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25147. }
  25148. return result;
  25149. };
  25150. Polygon.StartingAt = function (x, y) {
  25151. return BABYLON.Path2.StartingAt(x, y);
  25152. };
  25153. return Polygon;
  25154. })();
  25155. BABYLON.Polygon = Polygon;
  25156. var PolygonMeshBuilder = (function () {
  25157. function PolygonMeshBuilder(name, contours, scene) {
  25158. this._points = new PolygonPoints();
  25159. if (!("poly2tri" in window)) {
  25160. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25161. }
  25162. this._name = name;
  25163. this._scene = scene;
  25164. var points;
  25165. if (contours instanceof BABYLON.Path2) {
  25166. points = contours.getPoints();
  25167. } else {
  25168. points = contours;
  25169. }
  25170. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25171. }
  25172. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25173. this._swctx.addHole(this._points.add(hole));
  25174. return this;
  25175. };
  25176. PolygonMeshBuilder.prototype.build = function (updatable) {
  25177. if (typeof updatable === "undefined") { updatable = false; }
  25178. var result = new BABYLON.Mesh(this._name, this._scene);
  25179. var normals = [];
  25180. var positions = [];
  25181. var uvs = [];
  25182. var bounds = this._points.computeBounds();
  25183. this._points.elements.forEach(function (p) {
  25184. normals.push(0, 1.0, 0);
  25185. positions.push(p.x, 0, p.y);
  25186. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25187. });
  25188. var indices = [];
  25189. this._swctx.triangulate();
  25190. this._swctx.getTriangles().forEach(function (triangle) {
  25191. triangle.getPoints().forEach(function (point) {
  25192. indices.push(point.index);
  25193. });
  25194. });
  25195. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25196. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25197. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25198. result.setIndices(indices);
  25199. return result;
  25200. };
  25201. return PolygonMeshBuilder;
  25202. })();
  25203. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25204. })(BABYLON || (BABYLON = {}));
  25205. //# sourceMappingURL=babylon.polygonMesh.js.map